<?


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

#echo $funtion_test = "got here";

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


/// include php mailer
include_once($master_config_root_path . "/shared/PHPMailer/PHPMailerAutoload.php");


function phpmailer_propay(
							$send_to_emailaddress
							,$send_to_name
							,$reply_to_email
							,$reply_to_name
							,$subject
							,$message_html
							,$path_to_attachment_file_1=""
							,$attachment_file_name_1=""
							,$path_to_attachment_file_2=""
							,$attachment_file_name_2=""
							,$path_to_attachment_file_3=""
							,$attachment_file_name_3=""
							,$path_to_attachment_file_4=""
							,$attachment_file_name_4=""
							,$path_to_attachment_file_5=""
							,$attachment_file_name_5=""
							,$path_to_attachment_file_6=""
							,$attachment_file_name_6=""
							,$path_to_attachment_file_7=""
							,$attachment_file_name_7=""
							,$path_to_attachment_file_8=""
							,$attachment_file_name_8=""
							,$path_to_attachment_file_EXCEL=""
							,$attachment_file_name_EXCEL=""
						) {
	
	
	$mail = new PHPMailer;

	//$mail->SMTPDebug = 3;                               // Enable verbose debug output
	
	$mail->isSMTP();                                      // Set mailer to use SMTP
	
	
	$smtp_server = 2;
	if(stristr($send_to_emailaddress,"nsdb.com")) $smtp_server = 1; // GMAIL
	if(stristr($send_to_emailaddress,"gmail.com")) $smtp_server = 1; // GMAIL
	if(stristr($send_to_emailaddress,"payyap.network")) $smtp_server = 1; // GMAIL
	//$smtp_server = 3;
	
	// NSDB
	if($smtp_server == 1) { 
		$mail->Host = 'mx.nsdb.com';
		$mail->Username = 'shea.writer@corp.nsdb.com';		// SMTP username
		$mail->Password = 'P455w0rd!';						// SMTP password
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	if($smtp_server == 2) {  	
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	/// sendgrid
	if($smtp_server == 3) {
		
		$mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		$mail->Username = 'apikey';                 												// SMTP username
		$mail->Password = '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';	// SMTP password
		$mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		$mail->SMTPAuth = true;                               										// Enable SMTP authentication
		$mail->Port = 587;                                    										// TCP port to connect to
	

	}	
	
	
	
	
	
	$mail->setFrom('support@PAYYAP.network', 'PAYYAP.network');
	//$mail->setFrom($reply_to_email,$reply_to_name);
	//$mail->setFrom("mobileshea@gmail.com","Shea (Mobile)");
	$mail->addReplyTo($reply_to_email,$reply_to_name);
	
	$mail->addAddress($send_to_emailaddress, $send_to_name);     					// Add a recipient
	$mail->addAddress("verify@propay.com","PAYYAP (Verify)");
	
	$mail->addCC("support@payyap.network","PAYYAP.network");
	$mail->addBCC('payyap.cc@gmail.com',"PAYYAP (gmail:cc)");
	
	
	if($path_to_attachment_file_EXCEL) $mail->addAttachment($path_to_attachment_file_EXCEL, $attachment_file_name_EXCEL); // Add attachments
	if($path_to_attachment_file_1) $mail->addAttachment($path_to_attachment_file_1, $attachment_file_name_1);    	// Optional name
	if($path_to_attachment_file_2) $mail->addAttachment($path_to_attachment_file_2, $attachment_file_name_2);    	// Optional name	
	if($path_to_attachment_file_3) $mail->addAttachment($path_to_attachment_file_3, $attachment_file_name_3);    	// Optional name
	if($path_to_attachment_file_4) $mail->addAttachment($path_to_attachment_file_4, $attachment_file_name_4);    	// Optional name
	if($path_to_attachment_file_5) $mail->addAttachment($path_to_attachment_file_5, $attachment_file_name_5);    	// Optional name
	if($path_to_attachment_file_6) $mail->addAttachment($path_to_attachment_file_6, $attachment_file_name_6);    	// Optional name
	if($path_to_attachment_file_7) $mail->addAttachment($path_to_attachment_file_7, $attachment_file_name_7);    	// Optional name
	if($path_to_attachment_file_8) $mail->addAttachment($path_to_attachment_file_8, $attachment_file_name_8);    	// Optional name
	
	$mail->isHTML(true);                                  							// Set email format to HTML
	
	$mail->Subject = $subject;
	$mail->Body    = $message_html;
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		//test('Mailer Error',$mail->ErrorInfo);
	} else {
	    //test('Message has been sent');
	}
	
}





function phpmailer_INTELITRUTH(
							$send_to_emailaddress
							,$send_to_name
							,$reply_to_email
							,$reply_to_name
							,$subject
							,$message_html
							,$path_to_attachment_file_1=""
							,$attachment_file_name_1=""
							,$path_to_attachment_file_2=""
							,$attachment_file_name_2=""
							,$path_to_attachment_file_3=""
							,$attachment_file_name_3=""
							,$path_to_attachment_file_4=""
							,$attachment_file_name_4=""
							,$path_to_attachment_file_5=""
							,$attachment_file_name_5=""
							,$path_to_attachment_file_6=""
							,$attachment_file_name_6=""
							,$path_to_attachment_file_7=""
							,$attachment_file_name_7=""
							,$path_to_attachment_file_8=""
							,$attachment_file_name_8=""
							,$path_to_attachment_file_EXCEL=""
							,$attachment_file_name_EXCEL=""
						) {
	
	
	$mail = new PHPMailer;

	//$mail->SMTPDebug = 3;                               // Enable verbose debug output
	
	$mail->isSMTP();                                      // Set mailer to use SMTP
	
	
	$smtp_server = 2;
	# if(stristr($send_to_emailaddress,"nsdb.com")) $smtp_server = 1; // GMAIL
	# if(stristr($send_to_emailaddress,"gmail.com")) $smtp_server = 1; // GMAIL
	# if(stristr($send_to_emailaddress,"payyap.network")) $smtp_server = 1; // GMAIL
	# //$smtp_server = 3;
	
	// NSDB
	if($smtp_server == 1) { 
		$mail->Host = 'mx.nsdb.com';
		$mail->Username = 'intelitruth@corp.nsdb.com';			// SMTP username
		$mail->Password = 'kqe$u3AD3hK$vYNj224azTr2sV9rGyHB';	// SMTP password
		$mail->SMTPAuth = true;									// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';								// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;										// TCP port to connect to   
	}
	
	if($smtp_server == 2) {  	
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	/// sendgrid
	if($smtp_server == 3) {
		
		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;                                    										// TCP port to connect to
	
	
		# //// INTELITRUTH
		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;
		
		#####################################
		### INTELITRUTH
		#####################################
		//$mail = new PHPMailer;
		//$mail->isSMTP();
		$mail->CharSet = 'UTF-8';
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		
		$mail->SMTPSecure = 'tls';
		$mail->SMTPAuth = true;
		$mail->Port = 587;
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);
		
		                                    										// TCP port to connect to	
	}	
	
	
	
	
	
	//$mail->setFrom('support@Intelitruth.com', 'Intelitruth');
	//$mail->setFrom($reply_to_email,$reply_to_name);
	//$mail->setFrom("mobileshea@gmail.com","Shea (Mobile)");
	
	$mail->setFrom($reply_to_email, $reply_to_name);
	$mail->addReplyTo($reply_to_email,$reply_to_name);
	$mail->addAddress($send_to_emailaddress, $send_to_name);     					// Add a recipient
	$mail->addBCC("client_bcc@corp.intelitruth.com");

	
	if($path_to_attachment_file_EXCEL) $mail->addAttachment($path_to_attachment_file_EXCEL, $attachment_file_name_EXCEL); // Add attachments
	if($path_to_attachment_file_1) $mail->addAttachment($path_to_attachment_file_1, $attachment_file_name_1);    	// Optional name
	if($path_to_attachment_file_2) $mail->addAttachment($path_to_attachment_file_2, $attachment_file_name_2);    	// Optional name	
	if($path_to_attachment_file_3) $mail->addAttachment($path_to_attachment_file_3, $attachment_file_name_3);    	// Optional name
	if($path_to_attachment_file_4) $mail->addAttachment($path_to_attachment_file_4, $attachment_file_name_4);    	// Optional name
	if($path_to_attachment_file_5) $mail->addAttachment($path_to_attachment_file_5, $attachment_file_name_5);    	// Optional name
	if($path_to_attachment_file_6) $mail->addAttachment($path_to_attachment_file_6, $attachment_file_name_6);    	// Optional name
	if($path_to_attachment_file_7) $mail->addAttachment($path_to_attachment_file_7, $attachment_file_name_7);    	// Optional name
	if($path_to_attachment_file_8) $mail->addAttachment($path_to_attachment_file_8, $attachment_file_name_8);    	// Optional name
	
	$mail->isHTML(true);                                  							// Set email format to HTML
	
	$mail->Subject = $subject;
	$mail->Body    = $message_html;
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}
	
}



















function phpmailer_INTELITRUTH_invoicer(
							$send_to_emailaddress
							,$send_to_name
							,$reply_to_email
							,$reply_to_name
							,$subject
							,$message_html
							,$path_to_attachment_file_1=""
							,$attachment_file_name_1=""
							,$path_to_attachment_file_2=""
							,$attachment_file_name_2=""
							,$path_to_attachment_file_3=""
							,$attachment_file_name_3=""
							,$path_to_attachment_file_4=""
							,$attachment_file_name_4=""
							,$path_to_attachment_file_5=""
							,$attachment_file_name_5=""
							,$path_to_attachment_file_6=""
							,$attachment_file_name_6=""
							,$path_to_attachment_file_7=""
							,$attachment_file_name_7=""
							,$path_to_attachment_file_8=""
							,$attachment_file_name_8=""
							,$path_to_attachment_file_EXCEL=""
							,$attachment_file_name_EXCEL=""
						) {
	
	
	//test("send_to_emailaddress",$send_to_emailaddress);
	//test("message_html",$message_html);
	
	$mail = new PHPMailer;

	//$mail->SMTPDebug = 3;                               // Enable verbose debug output
	
	$mail->isSMTP();                                      // Set mailer to use SMTP
	
	
	$smtp_server = 2;

	
	// NSDB
	if($smtp_server == 1) { 
		$mail->Host = 'mx.nsdb.com';
		$mail->Username = 'intelitruth@corp.nsdb.com';			// SMTP username
		$mail->Password = 'kqe$u3AD3hK$vYNj224azTr2sV9rGyHB';	// SMTP password
		$mail->SMTPAuth = true;									// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';								// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;										// TCP port to connect to   
		$mail->addBCC("mobileshea@yahoo.com");
	}
	
	if($smtp_server == 2) {  	
		
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
		$mail->addBCC("mobileshea@yahoo.com");
	}
	
	/// sendgrid
	if($smtp_server == 3) {
		
		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;                                    										// TCP port to connect to
		
	
		//// INTELITRUTH
		
		# $mail->addBCC("client_bcc@corp.nsdb.com");
		# $mail->addBCC("mobileshea@yahoo.com");
		# 
		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;   
		
		
		#####################################
		### INTELITRUTH
		#####################################
		$mail = new PHPMailer;
		$mail->isSMTP();
		$mail->CharSet = 'UTF-8';
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		
		$mail->SMTPSecure = 'tls';
		$mail->SMTPAuth = true;
		$mail->Port = 587;
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);                                 										// TCP port to connect to	
	}	
	
	
	
	
	
	
	
	if($smtp_server == 4) {  	
		$mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		$mail->Username = 'shea.writer@intelitruth.com';			// SMTP username
		$mail->Password = 'D0wnund3r!';						// SMTP password
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	
	
	
	
	
	
	
	
	
	
	
	//$mail->setFrom('support@Intelitruth.com', 'Intelitruth');
	//$mail->setFrom($reply_to_email,$reply_to_name);
	//$mail->setFrom("mobileshea@gmail.com","Shea (Mobile)");
	
	$mail->setFrom($reply_to_email, $reply_to_name);
	$mail->addReplyTo($reply_to_email,$reply_to_name);
	$mail->addAddress($send_to_emailaddress, $send_to_name);    // Add a recipient
	$mail->addBCC("client_bcc@corp.intelitruth.com");

	
	if($path_to_attachment_file_EXCEL) $mail->addAttachment($path_to_attachment_file_EXCEL, $attachment_file_name_EXCEL); // Add attachments
	if($path_to_attachment_file_1) $mail->addAttachment($path_to_attachment_file_1, $attachment_file_name_1);    	// Optional name
	if($path_to_attachment_file_2) $mail->addAttachment($path_to_attachment_file_2, $attachment_file_name_2);    	// Optional name	
	if($path_to_attachment_file_3) $mail->addAttachment($path_to_attachment_file_3, $attachment_file_name_3);    	// Optional name
	if($path_to_attachment_file_4) $mail->addAttachment($path_to_attachment_file_4, $attachment_file_name_4);    	// Optional name
	if($path_to_attachment_file_5) $mail->addAttachment($path_to_attachment_file_5, $attachment_file_name_5);    	// Optional name
	if($path_to_attachment_file_6) $mail->addAttachment($path_to_attachment_file_6, $attachment_file_name_6);    	// Optional name
	if($path_to_attachment_file_7) $mail->addAttachment($path_to_attachment_file_7, $attachment_file_name_7);    	// Optional name
	if($path_to_attachment_file_8) $mail->addAttachment($path_to_attachment_file_8, $attachment_file_name_8);    	// Optional name
	
	$mail->isHTML(true);                                  							// Set email format to HTML
	
	$mail->Subject = $subject;
	$mail->Body    = $message_html;
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}
	
}






function phpmailer_INTELITRUTH_v2($send_to_name,$send_to_emailaddress,$send_from_name,$send_from_email,$reply_to_name,$reply_to_email,$subject,$message_html) {
	
	
	
	//test("send_to_emailaddress",$send_to_emailaddress);
	//test("message_html",$message_html);
	
	### $mail = new PHPMailer;
	### 
	### //$mail->SMTPDebug = 3;                               // Enable verbose debug output
	### 
	### $mail->isSMTP();                                      // Set mailer to use SMTP
	### 
	### //// INTELITRUTH
	### $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
	### $mail->Username = 'apikey';                 												// SMTP username
	### $mail->Password = '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';	// SMTP password
	### $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
	### $mail->SMTPAuth = true;                               										// Enable SMTP authentication
	### $mail->Port = 587;                                    										// TCP port to connect to	
	
	#####################################
	### INTELITRUTH
	#####################################
	$mail = new PHPMailer;
	$mail->isSMTP();
	$mail->CharSet = 'UTF-8';
	
	// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
	// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
	// $mail->Password = 'Bangk0k!';						// SMTP password
	
	$mail->Host = 'smtp.gmail.com'; 
	$mail->Username = 'mailbox@nsdb.com';
	$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
	
	
	$mail->SMTPSecure = 'tls';
	$mail->SMTPAuth = true;
	$mail->Port = 587;
	$mail->SMTPOptions = array(
		'ssl' => array(
			'verify_peer' => false,
			'verify_peer_name' => false,
			'allow_self_signed' => true
		)
	);

	$mail->setFrom($send_from_email, $send_from_name);
	
	$mail->addReplyTo($reply_to_email, $reply_to_name);
	
	$mail->addAddress($send_to_emailaddress, $send_to_name);    // Add a recipient
	
	$mail->addBCC("client_bcc@corp.intelitruth.com");

	$mail->isHTML(true);                                  							// Set email format to HTML
	
	$mail->Subject = $subject;
	
	$mail->Body    = $message_html;
	
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}
	
}













function phpmailer_INTELITRUTH_v3($send_to_name="",$send_to_email="",$send_CC_name="",$send_CC_email="",$send_from_name="",$send_from_email="",$reply_to_name="",$reply_to_email="",$attachment_path_1="",$attachment_file_1="",$attachment_path_2="",$attachment_file_2="",$subject="",$message_html="") {
	
	
	
	# //test("send_to_emailaddress",$send_to_emailaddress);
	# //test("message_html",$message_html);
	# 
	# $mail = new PHPMailer;
	# $mail->SMTPDebug = 3;                               // Enable verbose debug output
	# 
	# $mail->isSMTP();                                      // Set mailer to use SMTP
	# 
	# //// INTELITRUTH
	# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
	# $mail->Username = 'apikey';                 												// SMTP username
	# $mail->Password = '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';	// SMTP password
	# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
	# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
	# $mail->Port = 587;   
	
	
	#####################################
	### INTELITRUTH
	#####################################
	$mail = new PHPMailer;
	$mail->isSMTP();
	$mail->CharSet = 'UTF-8';
	
	// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
	// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
	// $mail->Password = 'Bangk0k!';						// SMTP password
	
	$mail->Host = 'smtp.gmail.com'; 
	$mail->Username = 'mailbox@nsdb.com';
	$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
	
	
	$mail->SMTPSecure = 'tls';
	$mail->SMTPAuth = true;
	$mail->Port = 587;
	$mail->SMTPOptions = array(
		'ssl' => array(
			'verify_peer' => false,
			'verify_peer_name' => false,
			'allow_self_signed' => true
		)
	);
	
	                                 										// TCP port to connect to	
		

	$mail->addAddress($send_to_email, $send_to_name); 
	
	$mail->AddCC($send_CC_email, $send_CC_name);
	
	$mail->setFrom($send_from_email, $send_from_name);
	
	$mail->addReplyTo($reply_to_email, $reply_to_name);
	
	$mail->addBCC("client_bcc@corp.intelitruth.com");
	
	
	if($attachment_path_1) $mail->addAttachment($attachment_path_1, $attachment_file_1);    	// Optional name
	if($attachment_path_2) $mail->addAttachment($attachment_path_1, $attachment_file_2);    	// Optional name
	
	

	$mail->isHTML(true);                                  							// Set email format to HTML
	
	$mail->Subject = $subject;
	
	$mail->Body    = $message_html;
	
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}
	
}








function phpmailer_IDCOIN_v1($send_to_name,$send_to_emailaddress,$send_from_name,$send_from_email,$reply_to_name,$reply_to_email,$subject,$message_html) {
	
	
	
	//test("send_to_emailaddress",$send_to_emailaddress);
	//test("message_html",$message_html);
	
	# $mail = new PHPMailer;
	# //$mail->SMTPDebug = 3;                               // Enable verbose debug output
	# 
	# $mail->isSMTP();                                      // Set mailer to use SMTP
	# 
	# //// INTELITRUTH
	# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
	# $mail->Username = 'apikey';                 												// SMTP username
	# $mail->Password = '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';	// SMTP password
	# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
	# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
	# $mail->Port = 587;                                    										// TCP port to connect to	
	
	#####################################
	### INTELITRUTH
	#####################################
	$mail = new PHPMailer;
	$mail->isSMTP();
	$mail->CharSet = 'UTF-8';
	
	// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
	// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
	// $mail->Password = 'Bangk0k!';						// SMTP password
	
	$mail->Host = 'smtp.gmail.com'; 
	$mail->Username = 'mailbox@nsdb.com';
	$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
	
	
	$mail->SMTPSecure = 'tls';
	$mail->SMTPAuth = true;
	$mail->Port = 587;
	$mail->SMTPOptions = array(
		'ssl' => array(
			'verify_peer' => false,
			'verify_peer_name' => false,
			'allow_self_signed' => true
		)
	);
	

	$mail->setFrom($send_from_email, $send_from_name);
	
	$mail->addReplyTo($reply_to_email, $reply_to_name);
	
	$mail->addAddress($send_to_emailaddress, $send_to_name);    // Add a recipient
	
	$mail->addBCC("bcc@idcoin.net");

	$mail->isHTML(true);                                  							// Set email format to HTML
	
	$mail->Subject = $subject;
	
	$mail->Body    = $message_html;
	
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}
	
}












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




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


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

}

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


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

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

function echo_blingk_network_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_value .= "<span style='font-size:" . $font_size . "; font-family:arial-black,verdana; font-weight:bold; color:#333333;'> Network</span>";
	
	return $return_value;
}





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



function echo_html_service_logo() {
	
	if(stristr($_SESSION['template']['company']['text_name'],"vSIGN")) return echo_vSIGN();
	if(stristr($_SESSION['template']['company']['text_name'],"vPASS")) return echo_vPASS();
	if(stristr($_SESSION['template']['company']['text_name'],"BANGK")) return echo_bangk($font_size="18px",$reg_size="12px");
	
	if(stristr($_SESSION['template']['company']['text_name'],"v-wave.network")) return echo_vWAVE();

}





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

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

function echo_vSIGN($font_size="",$sup_size="") {

	$font_size = "";
	$sup_size = "";
	return "<span style='font-size:$font_size;'>". $_SESSION['template']['company']['html_name'] . "</span>";

}
function echo_vocaSIGN($font_size,$sup_size) {

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



function echo_vPASS($sup_text) {

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



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


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

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

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


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



function echo_BBL($special) {

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




function echo_pinpass($sup_text="") {

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


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

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

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

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



### END ECHO_XXXXXX:



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

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






function payment_option_countries($payment_option) {

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

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

function is_my_country_supported($option,$iso3) {

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

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




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


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

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

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


function logger3($log_name="",$log_value="",$action_code="",$log_filename="") {
	
	/// comment-out to turn on:
	//$action_code = "OFF";
	
	
	if($action_code != "OFF") {
		global $master_config_logger; // set in /BANGK!/master_config.php (global)
		global $master_config_logger_vPASS_authorizations;
		global $master_config_logger_vSIGN_authorizations;
		//global $SCRIPT_NAME;
		
		//test("LOGGER: log_value: " . $log_value);
		//test("PHP_SELF: " . $_SERVER["PHP_SELF"]);
		
		if(
		/* general */	
		( stristr($master_config_logger,"ON") ) || 
		
		
		/* vPASS authorizations related only */
		( ($master_config_logger_vPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"voice_authorization.api") ) ||
		( ($master_config_logger_vPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"vPASS_api_listener.gate") ) ||
		( ($master_config_logger_vPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"authorization_database_voicefiles.auth") ) ||
		( ($master_config_logger_vPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"vPASS_For_Internet_biometric_account_lookup.gate") ) ||
		( ($master_config_logger_vPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"database_the_voicefile.gate") ) ||
		( ($master_config_logger_vPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"register_the_voice_biometric_voicefileid_array.gate") ) ||
		( ($master_config_logger_vPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"function_check_biometrics_now.gate") ) ||
		
		
		/* vSIGN authorizations related only */	
		( ($master_config_logger_vSIGN_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"voice_authorization.api") ) ||
		( ($master_config_logger_vSIGN_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"vSIGN_api_listener.gate") ) ||
		( ($master_config_logger_vSIGN_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"authorization_database_voicefiles.auth") )
		
		
		) {
			$filename = explode("/",$_SERVER["PHP_SELF"]);
			if(isset($filename[4])) {
				$write_file = $filename[4];
			} else if(isset($filename[3])) {
				$write_file = $filename[3];
			} else if(isset($filename[2])) {
				$write_file = $filename[2];
			} else if(isset($filename[1])) {
				$write_file = $filename[1];	
			}
			//$filename = explode("?",$filename[1]);
			//$filename = explode(".",$filename[0]);
			
			if($log_filename) $write_file = $log_filename;
			
		
			if( (is_array($log_value)) || (is_object($log_value)) ) {
				$output = var_export($log_value, true); //array2string($log_value,,$parentkey);
				$outstring = date("Y-m-d H:i:s",time()) . " : " . $log_name . " : " . $output . "\n\n";
			} else {
				$outstring = date("Y-m-d H:i:s",time()) . " : " . $log_name . " : " . $log_value . "\n\n";
			}
			
			if(!isset($log_file)) $log_file = "";
			
			if(!$log_file) {
				$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 datetime_v2($time="") {
	if($time) {
		return date("Y-m-d H:i:s",$time);
	} else {
		return date("Y-m-d H:i:s",time());
	}
		
}


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

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

function bonus($bonusid) {

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





### MYSQL BASICS: ###


function dbINSERT($query="",$dbname="",$charset="") {
	
	global $master_config_database_type;
	include("/BANGK!/shared/database_config.shared");

	### dynamic db
	if($dbname) $name_of_database = $dbname;
	
	$con = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$name_of_database);
	test("con",$con);
	
	//$charset = "utf8";
	if($charset) $result_set_charset = mysqli_set_charset($con,$charset);
	//test("result_set_charset",$result_set_charset);
	
	$result_query = mysqli_query($con,$query);
	test("result_query",$result_query);
	
	
	$id = mysqli_insert_id($con);
	test("id",$id);
	
	mysqli_free_result($result_query);
	test("result_query",$result_query);
	
	mysqli_close($con);
	//test("result_set_charset",$result_set_charset);
	
	return $id;

}




function dbOBJECT($query="",$name_of_database="",$charset="") {
	
	
	
	test("query",$query);
	test("name_of_database",$name_of_database);
	test("charset",$charset);
	
	global $master_config_database_type;
	include("/BANGK!/shared/database_config.shared");

	
	
	$con = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$name_of_database); # opens persistent connection
	test("con",$con);
	
	//$charset = "utf8";
	if($charset) $result_set_charset = mysqli_set_charset($con,$charset);
	//test("result_set_charset",$result_set_charset);
	
	$result_query = mysqli_query($con,$query);
	test("result_query",$result_query);
	
	
	$object = mysqli_fetch_object($result_query);
	test("object",$object);
	
	mysqli_free_result($result_query);
	test("result_query",$result_query);
	
	mysqli_close($con);
	//test("result_set_charset",$result_set_charset);
	
	return $object;

}



function dbARRAY($query="",$name_of_database="",$charset="") {
	
	global $master_config_database_type;
	include("/BANGK!/shared/database_config.shared");

	$con = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$name_of_database); # opens persistent connection
	test("con",$con);
	
	//$charset = "utf8";
	if($charset) $result_set_charset = mysqli_set_charset($con,$charset);
	test("result_set_charset",$result_set_charset);
	
	$result_query = mysqli_query($con,$query);
	test("result_query",$result_query);
	
	
	$array = mysqli_fetch_array($result_query,MYSQLI_ASSOC);
	test("array",$array);
	
	
	mysqli_free_result($result_query);
	test("result_query",$result_query);
	
	mysqli_close($con);
	//test("result_set_charset",$result_set_charset);
	
	return $array;

}

function dbARRAYS($query="",$name_of_database="",$charset="") {
	
	global $master_config_database_type;
	include("/BANGK!/shared/database_config.shared");

	$con = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$name_of_database); # opens persistent connection
	test("con",$con);
	
	//$charset = "utf8";
	if($charset) $result_set_charset = mysqli_set_charset($con,$charset);
	//test("result_set_charset",$result_set_charset);
	
	$result_query = mysqli_query($con,$query);
	test("result_query",$result_query);
	
	
	while($array_results = mysqli_fetch_array($result_query,MYSQLI_ASSOC)) {
		$array[] = $array_results;
	}
	test("array",$array);
	
	
	mysqli_free_result($result_query);
	test("result_query",$result_query);
	
	mysqli_close($con);
	//test("result_set_charset",$result_set_charset);
	
	return $array;
}







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

	### dynamic db
	if($dbname != NULL) $name_of_database = $dbname;
	
	//test("mysqlhost",$mysqlhost);
	//test("mysqluser",$mysqluser);
	//test("mysqlpass",$mysqlpass);
	//test("name_of_database",$name_of_database);
	
	$mysql = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$name_of_database); # opens persistent connection
	
	//test("mysql",$mysql);
	
	//test("---","---");
	
	
	//mysql_select_db($name_of_database);
	
	//test("query",$query);
	
	
	$result = mysqli_query($mysql,$query);
	//test("result",$result);
	
	if($result) $row = mysqli_fetch_assoc($result);
	
	
	//test("row",$row);
	
	if($row) {
		
		
		$object = new stdClass();

			foreach ($row as $k=> $v) {
				$object->{$k} = $v;
			}



		//$object = json_decode(json_encode($row), FALSE);
		
		//test("object",$object);
		
		
		return $object; 
	
	} else {
		return NULL; 
	}
}



	


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

	### dynamic db
	if($dbname != NULL) $name_of_database = $dbname;
	
	$mysql = mysqli_connect($mysqlhost,$mysqluser,$mysqlpass,$name_of_database); # opens persistent connection
	//mysql_select_db($name_of_database);
	
	$result = mysqli_query($mysql,$query);
	if($result) {
		$ID = mysqli_insert_id($mysql);
		return $ID;
	} else {
		return NULL;
	}
}

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

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

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



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

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






function disclaimer($company="") {
	
	//test("company",$company);
	if(stristr($company,"tube")) {
		//echo 1;
		$disclaimer = '';
		$disclaimer .= '<b>DISCLAIMER, EXPECTATIONS & "VALUE TO BUSINESS":</b><ul>';
		$disclaimer .= '<li><img src="https://Transcriber.wiki/link_images/star_2.png" style="height:20px; display:none;"><span style="font-weight:bold; color:#000000;"><span style="color:#CC0000;">Transcriber</span>.wiki</span> is a free (unlimited) service:';
		$disclaimer .= '<br>';
		$disclaimer .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="https://Transcriber.wiki/link_images/star_2.png" style="height:20px; display:;">&nbsp;&nbsp;<b>Designed to make your videos "<u>key word searchable</u>".</b><ul>';
		$disclaimer .= '<li><img src="https://Transcriber.wiki/link_images/GREEN-STYLE-YES.png" style="height:15px; display:none;">Helps users quickly identify and <i><b>deep-link</b></i> directly to <span style="color:#CC0000;">"<u>key moments</u>"</span> in your video!</li>';
		$disclaimer .= '<li><img src="https://Transcriber.wiki/link_images/GREEN-STYLE-YES.png" style="height:15px; display:none;">Makes your videos "<u>search engine relevant</u>" (ie, massively boosts traffic to your videos from Google, Bing, etc.)</li>';
		$disclaimer .= '</ul>';
		$disclaimer .= '<li><span style="font-weight:bold;color:#000000;"><span style="color:#CC0000;">Transcriber</span>.wiki</span> is not intended to be used for any "legal" purpose.</li>';
		$disclaimer .= '<li><span style="font-weight:bold;color:#000000;"><span style="color:#CC0000;">Transcriber</span>.wiki</span> delivers 70% - 95% transcription accuracy from most YouTube&trade; videos.</li><ul>';
		$disclaimer .= '<li><b>HINT:</b> The more clearly you speak, the more accurate the transcription will be!';
		$disclaimer .= '<li>For +95% accuracy ASR (speech-to-text) "tuning" services, please contact IVR.works&trade; via email: sales@ivr.works</li>';
		$disclaimer .= '</ul>';
		$disclaimer .= '</ul>';
		//test("disclaimer",$disclaimer);
		//return $disclaimer;
	}
	//echo 2;
	
	return $disclaimer;
	

}


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

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




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


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





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

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



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

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








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

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



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

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

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

}

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


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

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



function bmail($to,$subject,$message,$domain_prefix=null,$hide_images="") {
	
	
	logger3("bmail(to)",$to);
	logger3("bmail(domain_prefix)",$domain_prefix);
	logger3("bmail(hide_images)",$hide_images);
	
	
	global $master_config_admin_emailaddress;
	logger3("bmail(master_config_admin_emailaddress)",$master_config_admin_emailaddress);
	
	
	global $whitelabel_business_account_details_array;
	logger3("bmail(whitelabel_business_account_details_array)",whitelabel_business_account_details_array);
	
	
	
	logger3("bmail(whitelabel_business_account_details_array)",$whitelabel_business_account_details_array);
	
	
	
	
	//// whitelabel from name
	$insert_email_from_name = $_SESSION['template']['company']['domain'];
	
	if($whitelabel_business_account_details_array['accountname']) $insert_email_from_name = $whitelabel_business_account_details_array['accountname'];
	logger3("bmail(insert_email_from_name)",$insert_email_from_name);
	
	
	
	
	//// whitelabel from emailaddress
	$insert_email_from_email = $_SESSION['template']['company']['emailaddress_support'];
	if($whitelabel_business_account_details_array['emailaddress']) $insert_email_from_email = $whitelabel_business_account_details_array['emailaddress'];
	logger3("bmail(insert_email_from_email)",$insert_email_from_email);
	
	
	
	//// whitelabel from logo
	$insert_email_from_logo = $_SESSION['template']['company']['logo_topleft'];
	logger3("bmail(): whitelabel_business_account_details_array['url_to_whitelabel_banner_2048X475']",$whitelabel_business_account_details_array['url_to_whitelabel_banner_2048X475']);
	if($whitelabel_business_account_details_array['url_to_whitelabel_banner_2048X475']) $insert_email_from_logo = $whitelabel_business_account_details_array['url_to_whitelabel_banner_2048X475'];
	logger3("bmail(insert_email_from_logo)",$insert_email_from_logo);
	
	//// whitelabel URL
	$insert_email_from_url = "https://".$_SESSION['template']['company']['domain'];
	if($whitelabel_business_account_details_array['url']) $insert_email_from_url = $whitelabel_business_account_details_array['url'];
	logger3("bmail(insert_email_from_url)",$insert_email_from_url);
	

		
	
	$mail = new PHPMailer;
	$send_to_emailaddress = $to;
	$message_html = emailpage($message,$email_insert_style=NULL,$hide_images);
	
	$mail->isSMTP();                                      // Set mailer to use SMTP
	
	
	$smtp_server = 2;
	if(stristr($send_to_emailaddress,"nsdb.com")) $smtp_server = 1; // GMAIL
	if(stristr($send_to_emailaddress,"gmail.com")) $smtp_server = 1; // GMAIL
	if(stristr($send_to_emailaddress,"payyap.network")) $smtp_server = 1; // GMAIL
	//$smtp_server = 3;
	
	// NSDB
	if($smtp_server == 1) { 
		$mail->Host = 'mx.nsdb.com';
		$mail->Username = 'shea.writer@corp.nsdb.com';		// SMTP username
		$mail->Password = 'P455w0rd!';						// SMTP password
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	if($smtp_server == 2) {  	
		
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	/// sendgrid
	if($smtp_server == 3) {
		
		# /// PAYYAP
		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;                                    										// TCP port to connect to
		
		# //// INTELITRUTH
		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;
		
		
		#####################################
		### INTELITRUTH
		#####################################
		$mail = new PHPMailer;
		$mail->isSMTP();
		$mail->CharSet = 'UTF-8';
		
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		
		$mail->SMTPSecure = 'tls';
		$mail->SMTPAuth = true;
		$mail->Port = 587;
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);                                  										// TCP port to connect to
		
		
	}	
	
	
	
	
	
	$mail->setFrom($insert_email_from_email, $insert_email_from_name);
	
	$mail->addAddress($send_to_emailaddress, $send_to_name);     					// Add a recipient
	//$mail->addAddress('ellen@example.com');               						// Name is optional
	
	$mail->addReplyTo($insert_email_from_email,$insert_email_from_name);
	
	//$mail->addCC('cc@example.com');
	//$mail->addBCC("payyap.cc@gmail.com");
	
	//$mail->addAttachment($path_to_attachment_file_1,$attachment_file_name_1);         // Add attachments
	//$mail->addAttachment($path_to_attachment_file_2, $attachment_file_name_2);    // Optional name
	//$mail->addAttachment($path_to_attachment_file_3, $attachment_file_name_3);    // Optional name
	
	$mail->isHTML(true);                                  // Set email format to HTML
	
	$mail->Subject = $subject;
	$mail->Body    = $message_html;
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}


	
	
	
	return;
	
	# 	logger3("bmail() test",0);
	# 	
	# 	
	# 		
	# 		
	# 
	# 	if(empty($_SESSION['template']['company']['name'])) $_SESSION['template']['company']['name'] = "BANGK!";
	# 	if(empty($_SESSION['template']['company']['emailaddress_support'])) $_SESSION['template']['company']['emailaddress_support'] = "support@BANGK.com";
	# 	
	# 	logger3("bmail() test",1);
	# 	//$bmail_from = $_SESSION['template']['company']['emailaddress_support'];
	# 	$bmail_from = $_SESSION['template']['company']['emailaddress_support'];
	# 	//if($domain_prefix) $bmail_from = "support@$domain_prefix.bangk.com";
	# 	
	# 	if(empty($domain_prefix)) $domain_prefix = "support";
	# 	
	# 	logger3("bmail() test",2);
	# 	$headers = "";
	# 	$headers .= "From: ".$domain_prefix."." .$_SESSION['template']['company']['name'] . " <" . $bmail_from . ">\r\n";
	# 	$headers .= "Reply-To: support." . $_SESSION['template']['company']['name'] . " <" . $bmail_from . ">\r\n";
	# 	$headers .= "MIME-Version: 1.0\r\n";
	# 	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	# 	
	# 
	# 	if(stristr($_SESSION['template']['company']['name'],"PAYYAP")) {
	# 		logger3("bmail() test","PAYYAP");
	# 		$headers = "";
	# 		$headers .= "From: " .$_SESSION['template']['company']['name'] . " <" . $bmail_from . ">\r\n";
	# 		$headers .= "Reply-To: " . $_SESSION['template']['company']['name'] . " <" . $bmail_from . ">\r\n";
	# 		$headers .= "MIME-Version: 1.0\r\n";
	# 		$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	# 	}
	# 
	# 	logger3("bmail() test",3);
	# 	
	# 	
	# 	$message = emailpage($message,$email_insert_style=NULL,$hide_images);
	# 	
	# 	logger3("bmail() test",4);
	# 
	# 	global $master_config_email_development_override;
	# 	
	# 	
	# 	if(!empty($master_config_email_development_override)) $to = $master_config_email_development_override;
	# 	
	# 	global $master_config_gmailer_status;
	# 	
	# 	
	# 	//quick_mailer($to,$subject,$message,$activate_unsubscribe=false);
	# 	//return;	
	# 	if($master_config_gmailer_status == "bangk@nsdb.com") {
	# 		
	# 		logger3("bmail() test",5);
	# 		bangk_nsdb_gmailer($to,$subject,$html_message=$message);
	# 	} else {
	# 		
	# 		logger3("bmail() test",6);
	# 		# $to_address = $to;
	# 		# $from_address = "inbox@bangk.com";
	# 		# $from_name = "BANGK";
	# 		# $subject = $subject;
	# 		# $text_message = "na";
	# 		# $html_message = $message;
	# 		# $source_ip = "74.81.189.4";
	# 		# $domain_name = "bangk.com";
	# 		# ########## VERSION N1.1 ##########
	# 		# EMMMAIL_N1_1($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $source_ip,$domain_name);
	# 
	# 		mail($to, $subject, $message, $headers);
	# 	}
	# 	
	# 	logger3("bmail() test",7);
	
}




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

	// DO NOT REPORT THE FOLLOWING IP WHITELIST:
	if(
	(stristr($_SERVER['REMOTE_ADDR'],"74.81.189"))  /* CRON */
	) {
		//test(1,0);
		return;
	}
	
	
	global $master_config_admin_emailaddress;
	
	
	$html_message = "";
	
	if(!empty($additional_message)) {
		
		$html_message = "<hr>" . $additional_message . "<hr>";
		
	}
	$html_message .= "<table style='width:100%;'><tr><td style='width:100%; font-size:18px; line-height:35px; border-color:#000088; border-style:ridge; border-width:3px; padding:20px;'>
	
HTTP_HOST / SERVER_ADDR: ". $_SERVER['HTTP_HOST'] . " [". $_SERVER['SERVER_ADDR'] ."]

<br>

SCRIPT_FILENAME: ". $_SERVER['SCRIPT_FILENAME'] . "

<br>


HTTP_REFERER: ". $_SERVER['HTTP_REFERER'] . "

<br>

IP COUNTRY (ISO3): ".$_SESSION['session']['geo']['ip']. " (".$_SESSION['session']['geo']['city'].", ".$_SESSION['session']['geo']['iso3'].")<br>

HTTP_USER_AGENT: [". $_SERVER['HTTP_USER_AGENT'] ."]

<br>

HTTP_COOKIE: [". $_SERVER['HTTP_COOKIE'] ."]

<hr>

_SESSION['member']['memberid']: [". $_SESSION['member']['memberid'] ."]<br>

_SESSION['account']['accountid']: [". $_SESSION['account']['accountid'] ."]

</td><tr></table>
";
	
	
	//$reply_to_email_address = "alerts@nsdb.com";
	if(empty($reply_to_email_address)) $reply_to_email_address = $master_config_admin_emailaddress;
	
	$headers = "";
	$headers .= "From: NSDB ECP ALERT <" . $reply_to_email_address . ">\r\n";
	$headers .= "Reply-To: NSDB ECP ALERT <" . $reply_to_email_address . ">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	//$message = emailpage($html_message,$email_insert_style=NULL);
	
	
	$subject = $_SERVER['HTTP_HOST'] ." (".$_SESSION['session']['geo']['city'].", ".$_SESSION['session']['geo']['iso3'].")";
	
	
	if(!empty($additional_subject)) {
		
		$subject = $subject . " && " . $additional_message;
		
	}	
	
	//test("master_config_admin_emailaddress",$master_config_admin_emailaddress);
	//test("subject",$subject);
	//test("html_message",$html_message);
	//test("headers",$headers);

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





function bmailalert($subject,$message) {
	
	logger3("bmailalert()",0);

	global $master_config_admin_emailaddress;
	global $whitelabel_business_account_details_array;
	
	//// from name
	$insert_email_from_name = $_SESSION['template']['company']['domain'];
	if($whitelabel_business_account_details_array['accountname']) $tmp_email_from_name = $whitelabel_business_account_details_array['accountname'];

	//// from emailaddress
	$insert_email_from_email = $_SESSION['template']['company']['emailaddress_support'];
	if($whitelabel_business_account_details_array['emailaddress']) $tmp_email_from_email = $whitelabel_business_account_details_array['emailaddress'];

	
	
	logger3("bmailalert()",1);
	
	$headers = "";
	$headers .= "From: " .$insert_email_from_name . " <" . $insert_email_from_email . ">\r\n";
	$headers .= "Reply-To: " . $insert_email_from_name . " <" . $insert_email_from_email . ">\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);
	
	logger3("bmailalert()",2);
	
	logger3("bmailalert(master_config_admin_emailaddress)",$master_config_admin_emailaddress);
	logger3("bmailalert(subject)",$subject);
	logger3("bmailalert(message)",$message);
	logger3("bmailalert(headers)",$headers);
	
	//mail($to=$master_config_admin_emailaddress, $subject, $message, $headers);
	
	logger3("bmailalert()",3);
	
}


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

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

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

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



function quick_mailer($to,$subject,$message,$activate_unsubscribe=false,$mail_exchange="") {


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

	global $whitelabel_business_account_details_array;
	
	
	global $GLOBAL_SET_ENTERPRISE_LOGO;
	logger3("1-GLOBAL_SET_ENTERPRISE_LOGO",$GLOBAL_SET_ENTERPRISE_LOGO);
	
	$GLOBAL_SET_ENTERPRISE_LOGO_MAILER = $GLOBAL_SET_ENTERPRISE_LOGO;
	logger3("1-GLOBAL_SET_ENTERPRISE_LOGO_MAILER",$GLOBAL_SET_ENTERPRISE_LOGO_MAILER);
	
	//// from name
	$insert_email_from_name = $_SESSION['template']['company']['domain'];
	if($whitelabel_business_account_details_array['accountname']) $insert_email_from_name = $whitelabel_business_account_details_array['accountname'];
	if(!$insert_email_from_name) $insert_email_from_name = "OcularKYC.io";

	//// from emailaddress
	$insert_email_from_email = $_SESSION['template']['company']['emailaddress_support'];
	if($whitelabel_business_account_details_array['emailaddress']) $insert_email_from_email = $whitelabel_business_account_details_array['emailaddress'];
	if(!$insert_email_from_email) $insert_email_from_email = "support@ocularkyc.io";





	$headers = "";
	$headers .= "From: " . $insert_email_from_name . " <" . $insert_email_from_email . ">\r\n";
	$headers .= "Reply-To: " . $insert_email_from_name . " <" . $insert_email_from_email . ">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	
	if($activate_unsubscribe != false) {
		### ADD UNSUBSCRIBE:
		
		$unsubscribe_domain = $_SESSION['template']['company']['domain'];
		if(!$unsubscribe_domain) $unsubscribe_domain = "payyap.network";
		
		$message .= "
		
		<hr><span style='font-size:14px;'><a href='https://UNSUBSCRIBE.". $unsubscribe_domain ."/?emailaddress=". $to ."' target='_UNSUBSCRIBE' >Click here to UNSUBSCRIBE<a/> from these ". $insert_email_from_name ." hints & reminders.</span>
		
		";
		$unsubscribe_domain = "";
	}
	
	$message = emailpage($message,$email_insert_style=NULL);
	


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

	//test("to",$to);
	//test("subject",$subject);
	//test("message",$message);
	
	//mail($to, $subject, $message, $headers);
	
	$send_to_emailaddress = $to;
	$message_html = $message;
	$mail = new PHPMailer;
	$mail->isSMTP();                                      // Set mailer to use SMTP
	
	$smtp_server = 2;
	if(stristr($send_to_emailaddress,"nsdb.com")) $smtp_server = 1; // GMAIL
	if(stristr($send_to_emailaddress,"gmail.com")) $smtp_server = 1; // GMAIL
	if(stristr($send_to_emailaddress,"payyap.network")) $smtp_server = 1; // GMAIL
	//$smtp_server = 3;
	if(stristr($mail_exchange,"sendgrid")) $smtp_server = 3;
	
	// NSDB
	if($smtp_server == 1) { 
		$mail->Host = 'mx.nsdb.com';
		$mail->Username = 'shea.writer@corp.nsdb.com';		// SMTP username
		$mail->Password = 'P455w0rd!';						// SMTP password
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	if($smtp_server == 2) {  	
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	/// sendgrid
	if($smtp_server == 3) {
		
		

		
		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;                                    										// TCP port to connect to
		# 
		# 
		# //// INTELITRUTH
		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587; 
		
		
		#####################################
		### INTELITRUTH
		#####################################
		//$mail = new PHPMailer;
		//$mail->isSMTP();
		$mail->CharSet = 'UTF-8';
		
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		
		
		$mail->SMTPSecure = 'tls';
		$mail->SMTPAuth = true;
		$mail->Port = 587;
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);                                   										// TCP port to connect to
		
	
	
	
	}	
	                                 										// TCP port to connect to
	
	
	
						 							
	
	
	$mail->setFrom($insert_email_from_email, $insert_email_from_name);
	
	$mail->addAddress($send_to_emailaddress, $send_to_name);     // Add a recipient
	
	//$mail->addAddress('ellen@example.com');               // Name is optional
	
	$mail->addReplyTo($insert_email_from_email,$insert_email_from_name);
	
	//$mail->addCC('cc@example.com');
	
	$mail->addBCC('payyap.cc@gmail.com');
	
	$mail->addAttachment($path_to_attachment_file_1,$attachment_file_name_1);         // Add attachments
	$mail->addAttachment($path_to_attachment_file_2, $attachment_file_name_2);    // Optional name
	$mail->addAttachment($path_to_attachment_file_3, $attachment_file_name_3);    // Optional name
	$mail->isHTML(true);                                  // Set email format to HTML
	
	$mail->Subject = $subject;
	$mail->Body    = $message_html;
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}

	
}





function quick_mailer_v2($to,$subject,$message,$activate_unsubscribe=false,$mail_exchange="") {



	
	////////////////////////
	/// FROM NAME
	$insert_email_from_name = $_SESSION['template']['company']['name'];

	////////////////////////
	/// FROM EMAIL
	$insert_email_from_email = $_SESSION['template']['company']['emailaddress_support'];

	////////////////////////
	/// UPPER LEFT LOGO
	/// $GLOBAL_SET_ENTERPRISE_LOGO_MAILER
	
	
	

	$headers = "";
	$headers .= "From: " . $insert_email_from_name . " <" . $insert_email_from_email . ">\r\n";
	$headers .= "Reply-To: " . $insert_email_from_name . " <" . $insert_email_from_email . ">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	
	/////////////////////////////
	/// START: ADD UNSUBSCRIBE
	
	if($activate_unsubscribe != false) {
		
		$unsubscribe_domain = $_SESSION['template']['company']['domain'];
		if(!$unsubscribe_domain) $unsubscribe_domain = "payyap.network";
		
		$message .= "
		
		<hr><span style='font-size:14px;'><a href='https://UNSUBSCRIBE.". $unsubscribe_domain ."/?emailaddress=". $to ."' target='_UNSUBSCRIBE' >Click here to UNSUBSCRIBE<a/> from these ". $insert_email_from_name ." hints & reminders.</span>
		
		";
		$unsubscribe_domain = "";
	}

	/// END: ADD UNSUBSCRIBE
	/////////////////////////////
	
	
	
		
	$message = emailpage($message,$email_insert_style=NULL);
	
	
	$send_to_emailaddress = $to;
	$message_html = $message;
	$mail = new PHPMailer;
	$mail->isSMTP();                                      // Set mailer to use SMTP
	
	////////////////////////
	$smtp_server = 2;
	////////////////////////


	////////////////////////
	/// NSDB
	if($smtp_server == 1) { 
		$mail->Host = 'mx.nsdb.com';
		$mail->Username = 'shea.writer@corp.nsdb.com';		// SMTP username
		$mail->Password = 'P455w0rd!';						// SMTP password
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	////////////////////////
	/// GMAIL
	if($smtp_server == 2) {  	
		
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	////////////////////////
	/// SENDGRID
	if($smtp_server == 3) {

		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;                                    										// TCP port to connect to
		# 
		# 
		# //// INTELITRUTH
		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;  
		
		
		#####################################
		### INTELITRUTH
		#####################################
		//$mail = new PHPMailer;
		//$mail->isSMTP();
		$mail->CharSet = 'UTF-8';
		$mail->Host = 'smtp.gmail.com';
		$mail->Username = 'kycid.network@gmail.com';
		$mail->Password = 'Bangk0k!';
		
		$mail->SMTPSecure = 'tls';
		$mail->SMTPAuth = true;
		$mail->Port = 587;
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);
		
		                                  										// TCP port to connect to
	}	
	
	
	
	////////////////////////////
	/// TCP port to connect to
	
	$mail->setFrom($insert_email_from_email, $insert_email_from_name);
	
	$mail->addAddress($send_to_emailaddress, $send_to_name);     // Add a recipient
	
	//$mail->addAddress('ellen@example.com');               // Name is optional
	
	$mail->addReplyTo($insert_email_from_email,$insert_email_from_name);
	
	//$mail->addCC('cc@example.com');
	
	$mail->addBCC('payyap.cc@gmail.com');
	
	$mail->addAttachment($path_to_attachment_file_1,$attachment_file_name_1);         // Add attachments
	$mail->addAttachment($path_to_attachment_file_2, $attachment_file_name_2);    // Optional name
	$mail->addAttachment($path_to_attachment_file_3, $attachment_file_name_3);    // Optional name
	$mail->isHTML(true);                                  // Set email format to HTML
	
	$mail->Subject = $subject;
	$mail->Body    = $message_html;
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}

	
}





function mailer_highlandgames($to_name,$to_emailaddress,$subject,$html_message,$from_name,$from_email_address) {
	
	
	
	/*
	#####################################
	### sendgrid@corp.nsdb.com
	### NSDB_v2
	#####################################
	$mail = new PHPMailer;
	$mail->isSMTP(); 
	$mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
	$mail->Username = 'apikey';                 												// SMTP username
	$mail->Password = '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';	// SMTP password  (NSDB_v2)
	$mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
	$mail->SMTPAuth = true;                               										// Enable SMTP authentication
	$mail->Port = 587;                                    										// TCP port to connect to
	*/



	#####################################
	### sendgrid@corp.nsdb.com
	### NSDB_v2
	#####################################
	$mail = new PHPMailer;
	$mail->isSMTP(); 
	
	// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
	// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
	// $mail->Password = 'Bangk0k!';						// SMTP password
	
	$mail->Host = 'smtp.gmail.com'; 
	$mail->Username = 'mailbox@nsdb.com';
	$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
	
	$mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
	$mail->SMTPAuth = true;                               										// Enable SMTP authentication
	$mail->Port = 587;                                    										// TCP port to connect to






	
	////////////////////////////
	/// TCP port to connect to
	
	$mail->setFrom($from_email_address, $from_name);
	
	$mail->addAddress($to_emailaddress, $to_name);     // Add a recipient
		
	$mail->addReplyTo($from_email_address,$from_name);
	
	//$mail->addCC('cc@example.com');
	
	$mail->addBCC("shea.writer@nsdb.com","Shea Writer");

	$mail->isHTML(true);                                  // Set email format to HTML
	
	$mail->Subject = $subject;
	
	$mail->Body    = $html_message;
	
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}
}



function mailer_intelitruth_registration($to_name,$to_emailaddress,$subject,$html_message,$from_name,$reply_to_email_address) {
	
	#####################################
	### sendgrid@corp.nsdb.com
	### intelitruth_v2
	#####################################
	$mail = new PHPMailer;
	$mail->isSMTP(); 
	
	# $mail->addCustomHeader('MIME-Version', '1.0');
	# $mail->addCustomHeader('Content-type', 'text/html; charset=UTF-8');
	$mail->CharSet = 'UTF-8';
	
	# /*
	# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
	# $mail->Username = 'apikey';                 												// SMTP username
	# 
	# # $mail->Password = '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';	// SMTP password
	# $mail->Password = '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';
	# 
	# 
	# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
	# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
	# $mail->Port = 587;                                    										// TCP port to connect to
	# */
	
	
	
	

		
	# $mail->Host = 'in-v3.mailjet.com';  														// Specify main and backup SMTP servers
	# $mail->Username = '4166e12386347a51ef33bfe47f144837';                 						// SMTP username
	# $mail->Password = '8a5fe92270876d831b759e6ee806b705';	// SMTP password
	# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
	# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
	# $mail->Port = 587;                                    										// TCP port to connect to
	# 
	# $mail->SMTPOptions = array(
	# 	'ssl' => array(
	# 		'verify_peer' => false,
	# 		'verify_peer_name' => false,
	# 		'allow_self_signed' => true
	# 	)
	# );


	# //$mail->SMTPDebug = 4;


	// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
	// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
	// $mail->Password = 'Bangk0k!';						// SMTP password
	
	$mail->Host = 'smtp.gmail.com'; 
	$mail->Username = 'mailbox@nsdb.com';
	$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
	
	
	$mail->SMTPSecure = 'tls';
	$mail->SMTPAuth = true;
	$mail->Port = 587;
	
	
	
	
	////////////////////////////
	/// SET MAIL VARS:
	
	/// DEFAULTS:
	$from_name = $from_name;
	$from_email_address = "support@intelitruth.com"; 
	
	
	/// WHITELABEL SEAMLESS
	if(stristr($_SERVER['HTTP_HOST'],"PREMIUUM"))
	{
	
		$from_name = "Premiuum (partner)";
		$from_email_address = "parnter.support@premiuum.net"; 
		
	}
	
	
	
	
	
	
	
	
	
	
	/// CONFIGURE MAIL:
	$mail->setFrom($from_email_address, $from_name);
	
	$mail->addAddress($to_emailaddress, $to_name);     // Add a recipient
		
	
	$mail->addReplyTo($reply_to_email_address,$from_name);
	
	//$mail->addCC('cc@example.com');
	
	$mail->addBCC("shea.writer@nsdb.com","Shea Writer");

	$mail->isHTML(true);                                  // Set email format to HTML
	
	$mail->Subject = $subject;
	
	$mail->Body    = $html_message;
	
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	
	
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}
}




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

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

	$headers .= "MIME-Version: 1.0\r\n";
	
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	# test("mail_me(): to",$to);
	# test("mail_me(): subject",$subject);
	# test("mail_me(): message",$message);
	# test("mail_me(): headers",$headers);
	# test("mail_me(): from_name",$from_name);
	# test("mail_me(): reply_to",$reply_to);
	# test("mail_me(): return_to",$return_to);
	
	global $master_config_gmailer_status;
	if($master_config_gmailer_status == "bangk@nsdb.com") {
		bangk_nsdb_gmailer($to,$subject,$html_message=$message);
	} else {
		//$mail_results = mail($to, $subject, $message, $headers, "-f ".$return_to);
		$mail_results = mail($to, $subject, $message, $headers);
		#test("mail_results",$mail_results);
	}
	
	#exit;
	
	
	//test("mail_me(): mail_results",$mail_results);
	
	
	
}

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


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



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





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 = "mx".$domain_name;
	$received_from	= "mx".$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'];
			//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);
			mail($to_address, $subject, $html_message, $headers);
			
			//quick_mailer($to_address,$subject,$html_message,"(SYSALERT)");
			
			
			
			### EMMMAIL N2 (CS):  ######################################################
			// $to_address = "shea.writer@nsdb.com";
			// $from_address = ""; // defaults to $template
			// $from_name = "";  // defaults to $template
			// $subject = "EMAIL ALERT: " . $file_name . " / " . $_SERVER["REMOTE_ADDR"];
			// $text_message = $body;
			// $html_message = $body;
			// $bounce_address = "";  // defaults to $template
			// $from_id = "";  // defaults to $template
			// $domain_name = "";  // defaults to $template
			// $ip_address = "";  // defaults to $master_config
			// EMMMAIL_CS($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $bounce_address, $from_id, $domain_name, $ip_address);
			#################################################################################################################################################
			
			
		}
	}
}


function amount012($amount,$currency_code) {

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

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

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


function getTransactionNetValues($transactionid) {

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



function amount012DB($transactionid) {

	//global $account;

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


function amount012DB2($amount,$transactionid) {

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

	global $account;

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





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


function DTR($transactionid,$dynamic_DTR) {

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

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

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

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



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



	global $logo_topright_override_imgsrc;
	

	logger3("emailpage()",1);

	global $master_config_admin_emailaddress;
	global $whitelabel_business_account_details_array;
	logger3("emailpage() whitelabel_business_account_details_array",$whitelabel_business_account_details_array);
	
	//// whitelabel from name
	$insert_email_from_name = $_SESSION['template']['company']['domain'];
	if($whitelabel_business_account_details_array['accountname']) $insert_email_from_name = $whitelabel_business_account_details_array['accountname'];
	logger3("emailpage(): insert_email_from_name",$insert_email_from_name);
	
	//// whitelabel from emailaddress
	$insert_email_from_email = $_SESSION['template']['company']['emailaddress_support'];
	if($whitelabel_business_account_details_array['emailaddress']) $insert_email_from_email = $whitelabel_business_account_details_array['emailaddress'];
	logger3("emailpage(): insert_email_from_email",$insert_email_from_email);
	
	//// whitelabel from logo
	$insert_email_from_logo = $_SESSION['template']['company']['logo_topleft'];
	logger3("emailpage(): whitelabel_business_account_details_array['url_to_whitelabel_banner_2048X475']",$whitelabel_business_account_details_array['url_to_whitelabel_banner_2048X475']);
	if($whitelabel_business_account_details_array['url_to_whitelabel_banner_2048X475']) $insert_email_from_logo = $whitelabel_business_account_details_array['url_to_whitelabel_banner_2048X475'];
	logger3("emailpage(): insert_email_from_logo",$insert_email_from_logo);
	
	//// whitelabel URL
	$insert_email_from_url = "https://".$_SESSION['template']['company']['domain'];
	if($whitelabel_business_account_details_array['url']) $insert_email_from_url = $whitelabel_business_account_details_array['url'];
	logger3("emailpage(): insert_email_from_url",$insert_email_from_url);
	


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

	$page = "
<html>
	
	<head>
		<title>" . $_SESSION['template']['company']['domain'] . " " . $_SESSION['template']['company']['slogan1'] . "</title>
		<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
		<META NAME=\"ROBOTS\" CONTENT=\"NONE\">
		<META NAME=\"GOOGLEBOT\" CONTENT=\"NOARCHIVE\">";
		
		
		if(!$hide_images) $page .= "<link rel='icon' href='//". $_SESSION['template']['company']['host_images'] ."/". $_SESSION['template']['company']['favicon'] . "'>";
		
		
		
		$page .= "
		
<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>
									
													<!-- 1. START TABLE III. (LOGO) -->
													<table cellpadding='" . $_SESSION['template']['TABLE_III']['cellpadding'] . "' cellspacing='" . $_SESSION['template']['TABLE_III']['cellspacing'] . "' bgcolor='" . $_SESSION['template']['TABLE_III']['bgcolor'] . "'  width='" . $_SESSION['template']['TABLE_III']['width'] . "' border='0' style='margin-bottom:auto;'>";
													
													
if(stristr($_SESSION['template']['company']['domain'],"v-match.network"))
{
    $page .= "<tr style='background-color:".$_SESSION['template']['company']['logo_bg'].";'>";
}
else {
    $page .= " <tr>";
}
$page .= "
			 											
			 												<td align='left' valign='top'>";
			 												

##############################################################
### START: UPPER LEFT LOGO 			 													
##############################################################

global $vSIGN_email_receipt_merchant_path_to_logo;
global $vSIGN_email_receipt_merchant_path_to_logo_height;
if(!empty($vSIGN_email_receipt_merchant_path_to_logo)) {
	
	if(empty($vSIGN_email_receipt_merchant_path_to_logo_height)) {
		$vSIGN_email_receipt_merchant_path_to_logo_height = "auto";
	}
	
	$page .= "<img src='" . $vSIGN_email_receipt_merchant_path_to_logo . "' style='minHeight:" . $vSIGN_email_receipt_merchant_path_to_logo_height . "; maxHeight:" . $vSIGN_email_receipt_merchant_path_to_logo_height . ";' border='0' height='$vSIGN_email_receipt_merchant_path_to_logo_height'>";
	
	
} else if(empty($_SESSION['template']['company']['logo_topleft'])) {
    //test("_SESSION['template']['company']['html_logo']",$_SESSION['template']['company']['html_logo']);
    
    $page .= "<!-- A -->";
    $page .= "<table><tr><td ". $set_logo_height .">". $_SESSION['template']['company']['html_logo'] ."</td></tr></table>";
   
    
    
} else {
    
    
    if(stristr($_SESSION['template']['company']['domain'],"v-match.network"))
    {
        $page .= "<a href='https://".$_SESSION['template']['company']['domain']."' target='".$_SESSION['template']['company']['domain']."' border='0'>";
    }
    
    // this is the logo that appears in the business registration email receupts.
    //test("",$_SESSION['voice_authorization_api']['business_account_details']['vSIGN']['gateway_authorization_logo']);
    
    if(is_array($_SESSION['voice_authorization_api']['business_account_details']))
    {
    	if($_SESSION['voice_authorization_api']['business_account_details']['vSIGN']['gateway_authorization_logo']) {
		    $tmp_email_receipt_logo = "https://images.v-wave.network/". $_SESSION['voice_authorization_api']['business_account_details']['vSIGN']['gateway_authorization_logo'];
    	} else {
		    $tmp_email_receipt_logo = image("url",$_SESSION['template']['company']['logo_topleft']);
    	}
    	$page .= "<img src='" . $tmp_email_receipt_logo . "' border='0'".$set_logo_height .">";
    	
    	if(stristr($_SESSION['template']['company']['domain'],"v-match.network"))
    	{
    	    $page .= "</a>";
    	}
    }
}


logger3(" MMM _SESSION['intelitruth']",$_SESSION['intelitruth']);

logger3(" MMM _SESSION['intelitruth']['whitelabel_business_account_details']",$_SESSION['intelitruth']['whitelabel_business_account_details']);



if($_SESSION['intelitruth']['administrator']['whitelabel_business_account_hash']) {

	$tmp_sql = "SELECT * 
				FROM accounts
				WHERE hash = '". $_SESSION['intelitruth']['administrator']['whitelabel_business_account_hash'] ."'
				;";
	
	logger3(" MMM tmp_sql",$tmp_sql);
	
	$_SESSION['intelitruth']['whitelabel_business_account_details'] = object_to_array_v2(readTHECASHIER($tmp_sql));
	
	logger3(" MMM _SESSION['intelitruth']['whitelabel_business_account_details']",$_SESSION['intelitruth']['whitelabel_business_account_details']);
	
}



 if(
 (stristr($_SESSION['session']['broadcast_email_to_network']['from_host'],"photo.")) ||
 (stristr($_SERVER['HTTP_HOST'],"photo.BANGK.com"))
 ) {
	    $tmp_email_receipt_logo = image("url",$_SESSION['template']['company']['logo_topleft']);
		$page .= "<nobr>";
		$page .= "<span style='color:#C43436; font-weight:bold; font-size:20px; vertical-align:14%;'>photo.</span>";
		$page .= "<a href='https://photo.".$_SESSION['template']['company']['domain']."' target='".$_SESSION['template']['company']['domain']."' border='0'>";
		$page .= "<img src='" . $tmp_email_receipt_logo . "' border='0'".$set_logo_height .">";
		$page .= "</a>";
		$page .= "</nobr>";
 
  ### HIDE IMAGES
 } else if($hide_images) {
	 //$tmp_email_receipt_logo = image("url",$_SESSION['template']['company']['logo_topleft']);
	 //logger3("tmp_email_receipt_logo",$tmp_email_receipt_logo);
	 $page .= "<a href='https://".$_SESSION['template']['company']['domain']."' target='".$_SESSION['template']['company']['domain']."' border='0'>";
	 $page .= "<span style='color:#000000; font-size:40px; font-family:arial-black,arial-bold,arial; font-weight:bold;'>". $_SESSION['template']['company']['name'] ."</span>";
	 $page .= "</a>";
	 
	 
	 
 ### Tube-to-Text.com
 } else if(stristr($_SESSION['template']['company']['host_images'],"Tube-to-Text")) {
	 $tmp_email_receipt_logo = "http://" . $_SESSION['template']['company']['host_images'] . "/". $_SESSION['template']['company']['logo_topleft'];
	 logger3("tmp_email_receipt_logo",$tmp_email_receipt_logo);
	 $page .= "<a href='http://".$_SESSION['template']['company']['domain']."' target='".$_SESSION['template']['company']['domain']."' border='0'>";
	 $page .= "<img src='" . $tmp_email_receipt_logo . "' border='0'".$set_logo_height ." height='40'>";
	 $page .= "</a>";
	 
	 
 ### Transcriber.wiki
 } else if(stristr($_SESSION['template']['company']['host_images'],"Transcriber.wiki")) {
	 $tmp_email_receipt_logo = "http://" . $_SESSION['template']['company']['host_images'] . "/". $_SESSION['template']['company']['logo_topleft'];
	 logger3("tmp_email_receipt_logo",$tmp_email_receipt_logo);
	 $page .= "<a href='http://".$_SESSION['template']['company']['domain']."' target='".$_SESSION['template']['company']['domain']."' border='0'>";
	 $page .= "<img src='" . $tmp_email_receipt_logo . "' border='0'".$set_logo_height ." height='40'>";
	 $page .= "</a>";

 ### INTELITRUTH WHITELABEL
 } else if($_SESSION['intelitruth']['whitelabel_business_account_details']['url_to_whitelabel_icon_500x500']) {
	 
	 $tmp_email_receipt_logo = $_SESSION['intelitruth']['whitelabel_business_account_details']['url_to_whitelabel_icon_500x500'];
	
	 /*
	if(!stristr($tmp_email_receipt_logo,"//")) {
		$tmp_email_receipt_logo = "//". $_SESSION['template']['company']['host_images'] . "/" . $_SESSION['template']['company']['logo_filename_email_top_left'];
	 }
	 */
	 
	 
	  
	 global $GLOBAL_SET_ENTERPRISE_LOGO;
	 logger3("2-GLOBAL_SET_ENTERPRISE_LOGO",$GLOBAL_SET_ENTERPRISE_LOGO);	
	 
	 global $GLOBAL_SET_ENTERPRISE_LOGO_MAILER;
	 logger3("2-GLOBAL_SET_ENTERPRISE_LOGO_MAILER",$GLOBAL_SET_ENTERPRISE_LOGO_MAILER);	
	 
	 if($GLOBAL_SET_ENTERPRISE_LOGO == 1) {
		 $tmp_email_receipt_logo = "https://". $_SESSION['template']['company']['host_images'] . "/" . $_SESSION['template']['company']['logo_filename_email_top_left'];
	 }
	 
	 logger3("1-tmp_email_receipt_logo",$tmp_email_receipt_logo);
	 //$page .= "<a href='https://". $_SESSION['template']['company']['domain'] ."' target='".$_SESSION['template']['company']['domain']."' border='0'>";
	 $page .= "<img src='" . $tmp_email_receipt_logo . "' border='0'".$set_logo_height ." height='40'>";
	 //$page .= "</a>";	 


} else if(
		(!$tmp_email_from_logo)
		&& (!$insert_email_from_logo)
) {
	
	
	$tmp_email_receipt_logo = image("url","https://". $_SESSION['template']['company']['host_images'] . "/". $_SESSION['template']['company']['logo_topright']);
	//test("tmp_email_receipt_logo",$tmp_email_receipt_logo);
	$page .= "<!-- A -->";
	$page .= "<a href='". $_SESSION['template']['company']['domain'] ."' target='". $_SESSION['template']['company']['domain'] ."' border='0'>";
	$page .= "<img src='" . $tmp_email_receipt_logo . "' border='0' height='40'>";
	$page .= "</a>";
	
	
	
 ### UNKNOWN DEFAULT
 } else if($tmp_email_receipt_logo) {
	 
	 $insert_email_from_logo = image("url",$tmp_email_receipt_logo);
	 //test("tmp_email_receipt_logo",$tmp_email_receipt_logo);
	 $page .= "<!-- B -->";
	 $page .= "<a href='".$insert_email_from_url."' target='".$insert_email_from_name."' border='0'>";
	 $page .= "<img src='" . $insert_email_from_logo . "' border='0'".$set_logo_height ." height='40'>";
	 $page .= "</a>";
	 
 
 
 
 
 
 ### CURRENT DEAULT
 } else if($insert_email_from_logo) {
	 
	 $insert_email_from_name = $_SESSION['template']['company']['name'];
	 
	 if(!stristr($insert_email_from_logo,"http")) {
		 
		 $insert_email_from_logo = "https://". $_SESSION['template']['company']['host_images'] . "/" . $insert_email_from_logo;
		 
	 }
	 
	 //test("4-insert_email_from_logo",$insert_email_from_logo);
	 
	 //$insert_email_from_logo = image("url",$tmp_email_receipt_logo);
	 //test("tmp_email_receipt_logo",$tmp_email_receipt_logo);
	 $page .= "<!-- C -->";
	 $page .= "<a href='https://". $_SESSION['template']['company']['host_www'] ."' target='". $insert_email_from_name ."' border='0'>";
	 $page .= "<img src='" . $insert_email_from_logo . "' border='0'". $set_logo_height ." height='40'>";
	 $page .= "</a>";
	 
 }

 
$page .= "</td>";

##############################################################
### END: UPPER-LEFT LOGO 			 													
##############################################################


															








##############################################################
### START: UPPER CENTER LOGO 			 													
##############################################################

$page .= "			 											
			 												<td align='middle' valign='top'>";
if(stristr($_SESSION['template']['company']['domain'],"v-match.network"))
{
    $page .= "<img src='" . image("url",$_SESSION['template']['company']['logo_topcenter']) . "' border='0'>";
}
$page .= "
			 												</td>";
			 												
			 												
##############################################################
### END: UPPER CENTER LOGO 			 													
##############################################################			 												
			 												




			 												
##############################################################
### START: UPPER RIGHT LOGO 			 													
##############################################################


		$page .= "
			<td align='right' valign='top'>";
			
				if($logo_topright_override_imgsrc) {
					
					
					$page .= $logo_topright_override_imgsrc;
					
					
				} else {
			 												
						//$tmp_pormotional_logo = $_SESSION['template']['company']['logo_topright'];
						//if(!stristr($_COOKIE['cookie_route'],"SHOW SECRETS")) $tmp_pormotional_logo = "exclusive_and_patented_y.png";
						//if(!stristr($_SESSION['route'],"SHOW SECRETS")) $tmp_pormotional_logo = "exclusive_and_patented_y.png";
						
						
						
						/// this sets the RIGHT LOGO for vSIGN when the merchant has a logo set
						# global $tmp_merchant_details;
						# 
						# if(
						# (!stristr($tmp_merchant_details->accountname,"vWAVE")) &&
						# (!stristr($tmp_merchant_details->accountname,"vSIGN")) &&
						# (!empty($vSIGN_email_receipt_merchant_path_to_logo))
						# ) {
						# 	$tmp_pormotional_logo = "powered_by_vSIGN.png";
						# 
						# } else if(!stristr($_SESSION['template']['company']['domain'],"video-conference.link")){
						# 	
						# 	$tmp_pormotional_logo = "powered_by_vWAVE.png";
						# 
						# } else {
						# 
						# 	$tmp_pormotional_logo = "one_pixel.gif";
						# 
						# }
						# 
						####################
						###// CURRENT DEFAULT:
						
						
						
						
						
						$tmp_pormotional_logo = $_SESSION['template']['company']['logo_topright'];
						//test("000_tmp_pormotional_logo",$tmp_pormotional_logo);
						
						
						
						
						 //$hide_images = "TRUE";
						
						
						
						
						
						####################
						####################
						
						//test("tmp_pormotional_logo",$tmp_pormotional_logo);
						
						if($_SESSION['transaction']['hash']) $add_properties = "&transactionid=".$_SESSION['transaction']['hash'];
						
						
						
						
						
						## $ADD_powered_by = "";
						## if($_SESSION['template']['company']['system_status'] == "OFFLINE") {
						## 	
						## 	$tmp_pormotional_logo = "ocular_logo_1000x200_T.png";
						## 	$ADD_powered_by = "powered by...";
						## 	
						## }
						
						
						
						
						
						
						
						
						//test("tmp_pormotional_logo",$tmp_pormotional_logo);
						
						
						
						
						
					
						if(
							(isset($tmp_pormotional_logo))
							&& (!stristr($_SESSION['template']['company']['domain'],"v-match.network"))
						) {
							
							//echo $ADD_powered_by;
							
							if(!$hide_images) $page .= "					
						
						
						
						
						
						<img src='";
						
						
						if(stristr($_SESSION['template']['company']['name'],"Tube-to-Text")) {
							
							$page .= "http://" . $_SESSION['template']['company']['host_images'] . "/" . $tmp_pormotional_logo;
							
						
						}
						
						
						
						if(
							($_SESSION['intelitruth']['whitelabel_business_account_details']['url_to_whitelabel_icon_500x500'])
							&& (stristr($_SESSION['intelitruth']['whitelabel_business_account_details']['url_to_whitelabel_icon_500x500'],"your_logo_here"))
						) {
							
							$tmp_pormotional_logo = $_SESSION['template']['company']['logo_topright'];
							//test("tmp_pormotional_logo",$tmp_pormotional_logo);
							
							$page .= image("url",$tmp_pormotional_logo);
						}
						
						
						
						
						
						
						
						
						
						
						$page .= "' border='0' style='height:22px;'>";
					
					}
				
				
				
				} // end logo_topright_override_url






$page .= "</td>";
			 												
			 												
			 												
			 												
##############################################################
### END: UPPER RIGHT LOGO 			 													
##############################################################



$page .= "

			 																																													 
													
														</tr>
													</table>
													<!-- END TABLE III. (LOGO) -->
											
												</center>
												
												<table style='width:100%; height:auto; margin-top:auto;'>
													<tr>
														<td style='
															line-height:22px; 
															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>
															
														</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>";


	global $master_config_email_domain;
	if($master_config_email_domain) {
	  $page = str_ireplace("bangk.com", $master_config_email_domain, $page);
	  $page = str_ireplace("https://", "http://", $page);
	}
	
	logger3("master_config_email_domain",$master_config_email_domain);
	logger3("page",$page);
	//exit;
	
	# # exit;
	# return $message;
	# exit;
	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>
									
													<!-- 2. START TABLE III. (LOGO) -->
													<table cellpadding='" . $_SESSION['template']['TABLE_III']['cellpadding'] . "' cellspacing='" . $_SESSION['template']['TABLE_III']['cellspacing'] . "' bgcolor='" . $_SESSION['template']['TABLE_III']['bgcolor'] . "'  width='" . $_SESSION['template']['TABLE_III']['width'] . "' border='0' style='margin-bottom:auto;'>				
														<tr>
			 											
			 												<td align='left' valign='top'>
																<img src='" . image("url",$_SESSION['template']['company']['logo_topleft']) . "' border='0'>
			 												</td>
			 											
			 												<td align='middle' valign='top'>
																<img src='" . image("url",$_SESSION['template']['company']['logo_topcenter']) . "' border='0'>
			 												</td>
			 											
			 												<td align='right' valign='top'>";
			 												
			 													//$tmp_pormotional_logo = $_SESSION['template']['company']['logo_topright'];
			 													//if(!stristr($_COOKIE['cookie_route'],"SHOW SECRETS")) $tmp_pormotional_logo = "exclusive_and_patented_y.png";
			 													//if(!stristr($_SESSION['route'],"SHOW SECRETS")) $tmp_pormotional_logo = "exclusive_and_patented_y.png";
			 													$tmp_pormotional_logo = "biometrically_secured_2.png";
			 													
			 													if(!empty($transaction_hash)) {
				 													$add_properties = "&transactionid=".$transaction_hash;
			 													} else if($_SESSION['transaction']['hash']) {
			 														$add_properties = "&transactionid=".$_SESSION['transaction']['hash'];
			 													}
			 										
			 													
		$page .= "					
																<img src='" . image("url",$tmp_pormotional_logo) . "' border='0'>
			 												</td>																																	 
													
														</tr>
													</table>
													<!-- END TABLE III. (LOGO) -->
											
												</center>
												
												<table style='width:100%; height:auto; margin-top:auto;'>
													<tr>
														<td>
															<span style='
															line-height:" . $_SESSION['template']['company']['email_line_height'] . "; 
															color:" . $_SESSION['template']['company']['email_text_color'] . "; 
															font-family:" . $_SESSION['template']['company']['email_text_face'] . "; 
															font-size:" . $_SESSION['template']['company']['email_text_size'] . ";
															font-weight:" . $_SESSION['template']['company']['email_text_weight'] . ";
															'>
															    <br>
															    " . $message . "<br>
															    <br>" . 
															    return_refund_footer() . "
															</span>
														</td>
													</tr>
												</table>
												
											</td>
										</tr>
									</table>";
									
									$add_to = "page";  // adds text to "page" variable
									$tight_footer_right = "<a href='https://" . $_SESSION['template']['company']['host_support'] . "'>24-Hour, Worldwide Customer Support</a>";
									include($_SESSION['template']['company']['file_path'] . "shared/footer_text.shared");
									
									$page .= "
									

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

	</body>
</html>";

	return $page;
	
}





function return_refund_footer($transactionid=null) {

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

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

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

}


###	NETWORK functionS:	###


function member($tmp_memberid) {
	
	if(empty($tmp_memberid)) return false;

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

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

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


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

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

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

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

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

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

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

}


function account($tmp_accountid) {
	
	if(empty($tmp_accountid)) return false;

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

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



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

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

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


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

	if(stristr($_SESSION['template']['company']['client'],"v-wave.network")) {
		$table_name = 'vSIGN';
                if(stristr($_SESSION['template']["company"]["text_name"],"vPASS")) {
                    $table_name = 'vPASS_preferences'; 
                }
		$tmp_sql = "SELECT * FROM ".$table_name." WHERE accountid = '".  $tmp_account['accountid']  ."';";
		$tmp_account['vSIGN'] = object2array(readTHECASHIER($tmp_sql));
		
	} else {
			
		$tmp_account['dynamic_processing_profile'] = get_dynamic_processing_profile();
		$tmp_account['DTR'] = $tmp_account['days_to_release'] = get_dynamic_DTR($tmp_account['accountid']);
		$tmp_account['DPF'] = $tmp_account['dynamic_processing_fee'] = get_dynamic_fee_for_this_account($tmp_account['accountid']);

		
	}


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


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

}



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

}



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

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


	


function IEW_template() {
	/// NEW:
	
	$domain_parts = array_reverse(explode(".",$_SERVER['HTTP_HOST']));
	//test("domain_parts",$domain_parts);
	//exit;
	$number_of_domain_parts = count($domain_parts);
	//test("number_of_domain_parts",$number_of_domain_parts);
	//exit;
	
	
	foreach($domain_parts AS $domain_key => $domain_part) {
		
		if($domain_key == 0) {
			$_SESSION['session']['domain_part'] = "";
			$_SESSION['session']['last_template_found_hash'] = "";
		}
		
		
		if($domain_key > 0) {
			$_SESSION['session']['domain_part'] = "." . $_SESSION['session']['domain_part'];
		}
		$_SESSION['session']['domain_part'] =  $domain_part . $_SESSION['session']['domain_part'];
		
		$tmp_sql = "SELECT hash
					FROM templates_companies
					WHERE domain = '". $_SESSION['session']['domain_part'] ."'
					";
		//test("tmp_sql",$tmp_sql);
		$last_template_found_hash = getTHECASHIER($tmp_sql);
		//test("last_template_found_hash",$last_template_found_hash);
		
		if($last_template_found_hash) {
			$_SESSION['session']['last_template_found_hash'] = $last_template_found_hash;
		}
	}
	
	
	if($_SESSION['session']['last_template_found_hash']) {
		$tmp_sql = "SELECT * 
					FROM templates_companies
					WHERE hash = '". $_SESSION['session']['last_template_found_hash'] . "'
					;";
		//test("tmp_sql",$tmp_sql);
		$templates_companies_private_label_array = object_to_array_v2(readTHECASHIER($tmp_sql));
	}
	
	//test("$templates_companies_private_label_array",$templates_companies_private_label_array);
	
	return $templates_companies_private_label_array;
}	
	
function template($domain_name,$wildcard=false) {

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

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

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

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

 

	

	
	



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


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


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



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


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

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

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

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


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

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





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

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

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


	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."; }
	
	
	

	# if($index_row == "0") {	$index_row = ""; }
	# if($index_row == "1") {	$index_row = "&nbsp;#1.&nbsp;"; }
	# if($index_row == "2") {	$index_row = "&nbsp;#2.&nbsp;"; }
	# if($index_row == "3") {	$index_row = "&nbsp;#3.&nbsp;"; }
	# if($index_row == "4") {	$index_row = "&nbsp;#4.&nbsp;"; }
	# if($index_row == "5") {	$index_row = "&nbsp;#5.&nbsp;"; }
	# if($index_row == "6") {	$index_row = "&nbsp;#6.&nbsp;"; }
	# if($index_row == "7") {	$index_row = "&nbsp;#7.&nbsp;"; }
	# if($index_row == "8") {	$index_row = "&nbsp;#8.&nbsp;"; }
	# if($index_row == "9") {	$index_row = "&nbsp;#9.&nbsp;"; }
	# if($index_row == "10") {	$index_row = "&nbsp;#10.&nbsp;"; }
	# if($index_row == "11") {	$index_row = "&nbsp;#11.&nbsp;"; }
	# if($index_row == "12") {	$index_row = "&nbsp;#12.&nbsp;"; }
	# if($index_row == "13") {	$index_row = "&nbsp;#13.&nbsp;"; }
	# if($index_row == "14") {	$index_row = "&nbsp;#14.&nbsp;"; }
	# if($index_row == "15") {	$index_row = "&nbsp;#15.&nbsp;"; }
	# if($index_row == "16") {	$index_row = "&nbsp;#16.&nbsp;"; }
	# if($index_row == "17") {	$index_row = "&nbsp;#17.&nbsp;"; }
	# if($index_row == "18") {	$index_row = "&nbsp;#18.&nbsp;"; }
	# if($index_row == "19") {	$index_row = "&nbsp;#19.&nbsp;"; }
	# if($index_row == "20") {	$index_row = "&nbsp;#20.&nbsp;"; }
	
	
	
	$numberme = array();
	$numberme[0] = $page_row;
	$numberme[1] = $index;
	$numberme[2] = $index_row;
	
	return $numberme;

}


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


function adjust_for_timezone($time,$offset) {

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

}


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

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

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

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

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

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

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

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

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


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

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

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






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

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


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

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


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


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

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

###



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


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


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



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

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

	return $display;
}


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

	return $display;
}


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



		
function balance($accountid,$service="") {
	
	
	logger3("balance(): accountid",$accountid);
	logger3("balance(): service",$service);
	
	
	
	//global $master_config_platform_emulation;
	global $master_config_platform_base_currency;
	
	logger3("balance(): master_config_platform_base_currency",$master_config_platform_base_currency);
	
	$tmp_balance = array();
	
	
	if(strlen($accountid) == "32") {
		$accountid = getTHECASHIER("SELECT accountid FROM accounts WHERE hash = '". $accountid ."';");
	}
	
	logger3("balance(): accountid",$accountid);
	
	
	$platform = echo_platform();
	logger3("balance(): platform",$platform);
	
	//if(!$platform) $platform = "BANGK.com";	
	//$tmp_account_details = account($accountid);
	//test("tmp_account_details",$tmp_account_details);
	
        //default value from session
        //$force_platform_balance = $_SESSION['template']['company']['domain'];

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

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

												AND platform = '". $platform ."'

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

		/// NOW, get the balance values again (now that they exist):
		$tmp_sql = "SELECT * FROM balances 
					WHERE 
					accountid = '" . $accountid . "' 
					
					AND platform = '". $platform ."'
					
					AND currency_iso3 = '". $master_config_platform_base_currency ."';";
		
												
		logger3("balance(): tmp_sql",$tmp_sql);
	
		$tmp_balance = object2array(readTHECASHIER($tmp_sql));
		logger3("balance(): tmp_balance",$tmp_balance);										
	}
	
	
	######################################
	### START: PROPAY DIRECT OVERRIDE>>
	$propay_override = true;
	logger3("propay_override()",$propay_override);
	if($propay_override) {
		
		if(!$master_config_root_path) global $master_config_root_path;
		require_once($master_config_root_path . "shared/TSYS_functions.shared");
		
;
		logger3("certStr",$certStr);
		logger3("TSYS_gateway_status",$TSYS_gateway_status);
		
		$tmp_sql = "SELECT TSYS_merchant_account_id FROM accounts WHERE accountid = '". $accountid ."';";
		logger3("propay_override(): tmp_sql",$tmp_sql);
		$TSYS_merchant_id = getTHECASHIER($tmp_sql);
		logger3("propay_override(): TSYS_merchant_id",$TSYS_merchant_id);
		
		$mycertStr = ""; // default
		if($certStr) $mycertStr = $certStr;
		
		$optionalCertStr = "";
		if($mycertStr) $optionalCertStr = $mycertStr;
		
		$merchant_account_id = $TSYS_merchant_id;
		logger3("propay_override(): merchant_account_id",$merchant_account_id);
		
		
		
		$propay_account_balance = TSYS_ProPay_Account_Balance($merchant_account_id,$optionalCertStr=$mycertStr);
		logger3("propay_override(): propay_account_balance",$propay_account_balance);	
		$tmp_balance['account_balance'] = $tmp_balance['balance']['account_balance'] = $propay_account_balance;
		logger3("propay_override(): tmp_balance['account_balance']",$tmp_balance['account_balance']);	
	}
	### END: PROPAY DIRECT OVERRIDE<<
	
	
	### ### START ???
	### //$account_dynamic_schedule = get_dynamic_DTR($accountid);
	### $datetime_rolling_schedule = datetime(strtotime("-30 days"));
	### 
	### 
	### $tmp_sql = "SELECT SUM(transaction_net_value) FROM transactions 
	###   		WHERE 
	###   		accountid = '" . $accountid . "' 
	### 
	###   		AND platform = '". echo_platform() ."' 
	### 
	###   		AND currency_0_iso3 = '". $master_config_platform_base_currency ."' 
	###   		AND description = 'INCOMING' 
	###   		AND updated_datetime > '" . $datetime_rolling_schedule . "';";
	### $tmp_approved = getTHECASHIER($tmp_sql);
	### //logger3("tmp_sql",$tmp_sql);
	### //test("tmp_approved",$tmp_approved);
	### 
	### $tmp_sql = "SELECT SUM(fee_recipient_value) FROM transactions WHERE accountid LIKE '" . $accountid . "' 
	###   		AND description = 'Incoming' 
	###   		AND updated_datetime > '" . $datetime_rolling_schedule . "';";
	### $tmp_fees = getTHECASHIER($tmp_sql);
	### 
	### 
	### $tmp_balance['approved'] = $tmp_balance['balance']['approved'] = currency_format($tmp_approved - $tmp_fees);
	### END ???
	
	
	$tmp_balance['balance']['sponsor_balance'] = $tmp_balance['sponsor'] = $tmp_balance['balance']['sponsor'] = currency_format($tmp_balance['sponsor_balance']);
	
	logger3("balance(): tmp_balance['account_balance']",$tmp_balance['account_balance']);
	
	$tmp_balance['balance']['account_balance'] = $tmp_balance['account'] = $tmp_balance['balance']['account'] = currency_format($tmp_balance['account_balance']);
	
	logger3("balance(): tmp_balance['balance']['account_balance']",$tmp_balance['balance']['account_balance']);
		
	//test("_SESSION['template']['company']['name']",$_SESSION['template']['company']['name']);
	//test("_SESSION['account']['business_category']",$_SESSION['account']['business_category']);
	### MAKE IT SHOW vSIGN GATEWAY BALANCE AS DEFAULT
	
	if(empty($_SESSION['account']['business_subcategory'])) {
		$tmp_sql = "SELECT business_subcategory FROM accounts WHERE accountid = '". $accountid ."';";
		$business_subcategory = getTHECASHIER($tmp_sql);
	} else {
		$business_subcategory = $_SESSION['account']['business_subcategory'];
	}
	logger3("balance(): business_subcategory",$business_subcategory);
	
	// if(
	// (stristr($_SESSION['template']['company']['name'],"vSIGN")) &&
	// (stristr($business_subcategory,"GATEWAY"))
	// ) {
	// 	
	// 	
	// 	$tmp_balance['account_balance'] = $tmp_balance['balance']['account_balance'] = $tmp_balance['account'] = $tmp_balance['balance']['account'] = currency_format($tmp_balance['vSIGN_gateway']);
	// 	
	// 	
	// }
	
	//test("tmp_balance",$tmp_balance);
	//test("tmp_balance",$tmp_balance);
	
	$tmp_balance['balance']['available'] = currency_format($tmp_balance['available']);
	
	logger3("balance(): tmp_balance['balance']['available']",$tmp_balance['balance']['available']);
	
	$tmp_balance['balance']['balanceid'] = $tmp_balance['balanceid'];
	logger3("balance(): tmp_balance['balance']['balanceid']",$tmp_balance['balance']['balanceid']);
	
	logger3("balance(): tmp_balance",$tmp_balance);
	return $tmp_balance;
}


function simple_balance($accountid) {
	
	if(empty(trim($accountid))) return FALSE;
	
	//if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = $_SESSION['account']['currency_0_iso3'];
		
	//if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = $_SESSION['template']['company']['currency1'];
	
	if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = "EUR";
	
	$tmp_sql = "SELECT account_balance 
				FROM balances 
				WHERE accountid LIKE '" . $accountid . "'
				AND currency_iso3 = '". $_XXXXX_currency_iso3 ."' 
				;";
	$tmp_results = getTHECASHIER($tmp_sql);
	logger3("simple_balance(): tmp_sql",$tmp_sql);
	logger3("simple_balance(): tmp_results",$tmp_results);
	
	
	if(empty($tmp_results)) {
		
		
		//if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = $_SESSION['account']['currency_0_iso3'];
		
		//if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = $_SESSION['template']['company']['currency1'];
		
		if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = "EUR";
		
		
		$tmp_sql = "SELECT account_balance 
					FROM balances 
					WHERE accountid LIKE '" . addslashes($accountid) . "'
					AND currency_iso3 = '". addslashes($_XXXXX_currency_iso3) ."' 
					;";
		logger3("simple_balance(): tmp_sql",$tmp_sql);
		$tmp_results = getTHECASHIER($tmp_sql);
		logger3("simple_balance(): tmp_results",$tmp_results);
		
		
	}
	
	
	
	if((!$tmp_results) || ($tmp_results == 0) || ($tmp_results == "0") || ($tmp_results == NULL) || ($tmp_results == "NULL")) {
		$tmp_results = "0.00";
	}
	
	return currency_format($tmp_results);
}


function simple_blingk_reseller_balance($accountid) {
	
	//$AND_PLATEFORM = "AND platform = '". echo_platform() ."'";
	
	
	//if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = $_SESSION['account']['currency_0_iso3'];
		
	//if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = $_SESSION['template']['company']['currency1'];
		

	$_XXXXX_currency_iso3 = "EUR";
	
	$tmp_sql = "SELECT blingk_reseller_balance 
				FROM balances 
				WHERE accountid LIKE '" . $accountid . "'
				AND currency_iso3 = '". $_XXXXX_currency_iso3 ."' 
				$AND_PLATEFORM 
				;";
	logger3("simple_blingk_reseller_balance(): tmp_sql",$tmp_sql);
	
	$tmp_results = getTHECASHIER($tmp_sql);
	
	logger3("simple_blingk_reseller_balance(): tmp_results",$tmp_results);
	
	if(
		(!$tmp_results) 
		|| ($tmp_results == 0) 
		|| ($tmp_results == "0") 
		|| ($tmp_results == NULL) 
		|| ($tmp_results == "NULL")
	) {
		$tmp_results = "0.00";
	}
	
	return $tmp_results;
}





function simple_blingk_credit($accountid) {
	
	if(empty(trim($accountid))) return FALSE;
	
	
	//if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = $_SESSION['account']['currency_0_iso3'];
		
	//if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = $_SESSION['template']['company']['currency1'];
		

	$_XXXXX_currency_iso3 = "EUR";
	
	
	
	$tmp_sql = "SELECT blingk_credit 
				FROM balances  
				WHERE accountid LIKE '" . $accountid . "'
				AND currency_iso3 = '". $_XXXXX_currency_iso3 ."' 
				;";
	$tmp_results = getTHECASHIER($tmp_sql);
	logger3("tmp_sql",$tmp_sql);
	logger3("tmp_results",$tmp_results);
	
	
	
	if(empty($tmp_results)) {
		
		
		//if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = $_SESSION['account']['currency_0_iso3'];
		
		//if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = $_SESSION['template']['company']['currency1'];
		
		if(empty($_XXXXX_currency_iso3)) $_XXXXX_currency_iso3 = "EUR";
		
		
		$tmp_sql = "SELECT blingk_credit 
					FROM balances 
					WHERE 
					AND currency_iso3 = '". addslashes($_XXXXX_currency_iso3) ."' 
					AND accountid LIKE '" . addslashes($accountid) . "'
					;";
		logger3("simple_balance(): tmp_sql",$tmp_sql);
		$tmp_results = getTHECASHIER($tmp_sql);
		logger3("simple_balance(): tmp_results",$tmp_results);
		
	}
	
	
	if((!$tmp_results) || ($tmp_results == 0) || ($tmp_results == "0") || ($tmp_results == NULL) || ($tmp_results == "NULL")) {
		$tmp_results = "0.00";
	}
	return currency_format($tmp_results);
}


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



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


#######



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




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

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

	
	
	if( 
	(stristr($method,"assign")) || 
	(stristr($method,"sticky")) ||
	(stristr($method,"GO")) 
	) {
		
		echo "<SCRIPT LANGUAGE='JAVASCRIPT' TYPE='TEXT/JAVASCRIPT'>";
		echo "window.location.assign('". $location_page. "');";
		echo "</SCRIPT>";
		return;
	}
	
	
	
	///test("FUNC: location_page",$location_page);
	
	if(strtolower($method) == "javascript") {
		//test("method == javascript == TRUE",NULL,NULL);
		if(!empty($artificial_delay)) {

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

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

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



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


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

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

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

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

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


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


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

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

	return $display_tabs;
}



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


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





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

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




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

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


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

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

	
	return $fee;
}








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

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

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

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






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

	$Total = 0;

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

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

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

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

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


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


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



function card_details($card_number) {

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


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

	}

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

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



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






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

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

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



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



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

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

		$i = $i + 1;									
	}
	

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

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




		$i = $i + 1;									
	}
}




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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

function update_authorized_ip_address($memberid) {

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



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

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

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

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

			

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

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

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

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

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

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

		}
		#
		# 2004.02.07 - looks ok until this point.
	

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


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

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

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

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

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

	

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

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


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

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

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

				

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

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

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

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

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

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

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

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

} # end update_banned();



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

function get_account_status($accountid) {

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

function get_member_status($memberid) {

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






function transaction_totals($account_number) {

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

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

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

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

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



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


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

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

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





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

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

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


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


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



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

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

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

	return $totals;

}



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

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

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

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


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

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

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

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


function limits($deposit_value,$wallet_number) {

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

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

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

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





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




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

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

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

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




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

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


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

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




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

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

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

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

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

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

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



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

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

	$ch = curl_init();

	curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie_file); 

	curl_setopt ($ch, CURLOPT_URL, $url );

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

	curl_setopt ($ch, CURLOPT_HEADER, 1);

	curl_setopt ($ch, CURLOPT_ENCODING, 0);

	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

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

	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 

	curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); 

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

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

}

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

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


function postDATA($send_url,$send_data,$asynchronous = false) {
	
	$send_session = curl_init();
	# echo "send_session: $send_session<br>";
	
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_NOPROGRESS,1);
	curl_setopt($send_session, CURLOPT_COOKIESESSION,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	#curl_setopt($send_session, CURLOPT_REFERRER,$HTTP_HOST);
	curl_setopt($send_session, CURLOPT_POSTFIELDS,$send_data);
	curl_setopt($send_session, CURLOPT_SSL_VERIFYPEER, FALSE);
        
        if($asynchronous){
            curl_setopt($send_session, CURLOPT_FRESH_CONNECT, true);
            curl_setopt($send_session, CURLOPT_TIMEOUT,1);
            curl_setopt($send_session, CURLOPT_NOBODY, true); 
        }
    
    curl_setopt($send_session,CURLOPT_URL, $send_url);
        
	$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 curl_multiple($url_array) {
	
	
	$url_array = object_to_array_v2($url_array);



    $mh = curl_multi_init();

    $master_counter = 0;


    ##############################################################################
    # prepare requests / handles:

	foreach($url_array as $key => $full_url) {
        
        
        
        $ch[$master_counter] = curl_init();
        //logger3("ch[$vp]: ", $ch[$master_counter]);
        #set headers:
        curl_setopt($ch[$master_counter], CURLOPT_HEADER, 0);

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

        # dunno what this does:
        curl_setopt($ch[$master_counter], CURLOPT_RETURNTRANSFER, 1);

        #curl_setopt($ch, CURLOPT_VERBOSE, 1);
        # set path to server
        curl_setopt($ch[$master_counter], CURLOPT_URL, $full_url);

        #set parameter values:
        //curl_setopt($ch[$master_counter], CURLOPT_POSTFIELDS, $parameters);

        # set multi handle 
        curl_multi_add_handle($mh, $ch[$master_counter]);

        #update voiceid
        $master_counter++;
    }


    ##############################################################################
    # execute:

    $running = 1;
    while ($running > 0) {
        //logger3("running...", $running);
        curl_multi_exec($mh, $running);
    }


    ##############################################################################
    # get responses:
    logger3("### RAW (PER LOOKUP) RESULTS...", $a);

    $master_counter = 0;
    foreach($url_array as $key => $full_url) {


        $response[$key] = curl_multi_getcontent($ch[$master_counter]);
        
        # remove handle
        curl_multi_remove_handle($mh, $ch[$master_counter]);

        # update voicefileid
        $master_counter++;
    }
    # update filename
    //$fn++;
    //}
    ##############################################################################
    # all done / close session:
    curl_multi_close($mh);
    
    return $response;
}








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

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


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


## START:

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

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

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

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

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

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

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

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

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

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



function minimizeState($state) {
	
	$full_state = trim($state);

	
	if((ucwords(strtolower($full_state)) == "Alabama") || (strtoupper($full_state) == "AL"))  return "AL";
	if((ucwords(strtolower($full_state)) == "Alaska") || (strtoupper($full_state) == "AK"))  return "AK";
	if((ucwords(strtolower($full_state)) == "Arizona") || (strtoupper($full_state) == "AZ"))  return "AZ";
	if((ucwords(strtolower($full_state)) == "Arkansas") || (strtoupper($full_state) == "AR"))  return "AR";
	if((ucwords(strtolower($full_state)) == "California") || (strtoupper($full_state) == "CA"))  return "CA";
	if((ucwords(strtolower($full_state)) == "Colorado") || (strtoupper($full_state) == "CO"))  return "CO";
	if((ucwords(strtolower($full_state)) == "Connecticut") || (strtoupper($full_state) == "CT"))  return "CT";
	if((ucwords(strtolower($full_state)) == "Delaware") || (strtoupper($full_state) == "DE"))  return "DE";
	if((ucwords(strtolower($full_state)) == "District Of Columbia") || (strtoupper($full_state) == "DC"))  return "DC";
	if((ucwords(strtolower($full_state)) == "Dist Of Columbia") || (strtoupper($full_state) == "DC"))  return "DC";
	if((ucwords(strtolower($full_state)) == "Florida") || (strtoupper($full_state) == "FL"))  return "FL";
	if((ucwords(strtolower($full_state)) == "Georgia") || (strtoupper($full_state) == "GA"))  return "GA";
	if((ucwords(strtolower($full_state)) == "Hawaii") || (strtoupper($full_state) == "HI"))  return "HI";
	if((ucwords(strtolower($full_state)) == "Idaho") || (strtoupper($full_state) == "ID"))  return "ID";
	if((ucwords(strtolower($full_state)) == "Illinois") || (strtoupper($full_state) == "IL"))  return "IL";
	if((ucwords(strtolower($full_state)) == "Indiana") || (strtoupper($full_state) == "IN"))  return "IN";
	if((ucwords(strtolower($full_state)) == "Iowa") || (strtoupper($full_state) == "IA"))  return "IA";
	if((ucwords(strtolower($full_state)) == "Kansas") || (strtoupper($full_state) == "KS"))  return "KS";
	if((ucwords(strtolower($full_state)) == "Kentucky") || (strtoupper($full_state) == "KY"))  return "KY";
	if((ucwords(strtolower($full_state)) == "Louisiana") || (strtoupper($full_state) == "LA"))  return "LA";
	if((ucwords(strtolower($full_state)) == "Maine") || (strtoupper($full_state) == "ME"))  return "ME";
	if((ucwords(strtolower($full_state)) == "Maryland") || (strtoupper($full_state) == "MD"))  return "MD";
	if((ucwords(strtolower($full_state)) == "Massachusetts") || (strtoupper($full_state) == "MA"))  return "MA";
	if((ucwords(strtolower($full_state)) == "Michigan") || (strtoupper($full_state) == "MI"))  return "MI";
	if((ucwords(strtolower($full_state)) == "Minnesota") || (strtoupper($full_state) == "MN"))  return "MN";
	if((ucwords(strtolower($full_state)) == "Mississippi") || (strtoupper($full_state) == "MS"))  return "MS";
	if((ucwords(strtolower($full_state)) == "Missouri") || (strtoupper($full_state) == "MO"))  return "MO";
	if((ucwords(strtolower($full_state)) == "Montana") || (strtoupper($full_state) == "MT"))  return "MT";
	if((ucwords(strtolower($full_state)) == "Nebraska") || (strtoupper($full_state) == "NE"))  return "NE";
	if((ucwords(strtolower($full_state)) == "Nevada") || (strtoupper($full_state) == "NV"))  return "NV";
	if((ucwords(strtolower($full_state)) == "New Hampshire") || (strtoupper($full_state) == "NH"))  return "NH";
	if((ucwords(strtolower($full_state)) == "New Jersey") || (strtoupper($full_state) == "NJ"))  return "NJ";
	if((ucwords(strtolower($full_state)) == "New Mexico") || (strtoupper($full_state) == "NM"))  return "NM";
	if((ucwords(strtolower($full_state)) == "New York") || (strtoupper($full_state) == "NY"))  return "NY";
	if((ucwords(strtolower($full_state)) == "North Carolina") || (strtoupper($full_state) == "NC"))  return "NC";
	if((ucwords(strtolower($full_state)) == "North Dakota") || (strtoupper($full_state) == "ND"))  return "ND";
	if((ucwords(strtolower($full_state)) == "Ohio") || (strtoupper($full_state) == "OH"))  return "OH";
	if((ucwords(strtolower($full_state)) == "Oklahoma") || (strtoupper($full_state) == "OK"))  return "OK";
	if((ucwords(strtolower($full_state)) == "Oregon") || (strtoupper($full_state) == "OR"))  return "OR";
	if((ucwords(strtolower($full_state)) == "Pennsylvania") || (strtoupper($full_state) == "PA"))  return "PA";
	if((ucwords(strtolower($full_state)) == "Rhode Island") || (strtoupper($full_state) == "RI"))  return "RI";
	if((ucwords(strtolower($full_state)) == "South Carolina") || (strtoupper($full_state) == "SC"))  return "SC";
	if((ucwords(strtolower($full_state)) == "South Dakota") || (strtoupper($full_state) == "SD"))  return "SD";
	if((ucwords(strtolower($full_state)) == "Tennessee") || (strtoupper($full_state) == "TN"))  return "TN";
	if((ucwords(strtolower($full_state)) == "Texas") || (strtoupper($full_state) == "TX"))  return "TX";
	if((ucwords(strtolower($full_state)) == "Utah") || (strtoupper($full_state) == "UT"))  return "UT";
	if((ucwords(strtolower($full_state)) == "Vermont") || (strtoupper($full_state) == "VT"))  return "VT";
	if((ucwords(strtolower($full_state)) == "Virginia") || (strtoupper($full_state) == "VA"))  return "VA";
	if((ucwords(strtolower($full_state)) == "Washington") || (strtoupper($full_state) == "WA"))  return "WA";
	if((ucwords(strtolower($full_state)) == "Washington DC") || (strtoupper($full_state) == "DC"))  return "DC";
	if((ucwords(strtolower($full_state)) == "Washington Dc") || (strtoupper($full_state) == "DC"))  return "DC";
	if((ucwords(strtolower($full_state)) == "Wash Dc") || (strtoupper($full_state) == "DC"))  return "DC";
	if((ucwords(strtolower($full_state)) == "West Virginia") || (strtoupper($full_state) == "WV"))  return "WV";
	if((ucwords(strtolower($full_state)) == "Wisconsin") || (strtoupper($full_state) == "WI"))  return "WI";
	if((ucwords(strtolower($full_state)) == "Wyoming") || (strtoupper($full_state) == "WY"))  return "WY";
	
	### CANADA:
	if(ucwords(strtolower($full_state)) == "Alberta") return "AB";	
	if(ucwords(strtolower($full_state)) == "British Columbia") return "BC";	
	if(ucwords(strtolower($full_state)) == "Manitoba") return "MB"; 
	if(ucwords(strtolower($full_state)) == "New Brunswick") return "NB";	
	if(ucwords(strtolower($full_state)) == "New Foundland") return "NF";	
	if(ucwords(strtolower($full_state)) == "Northwest Territories") return "NT"; 
	if(ucwords(strtolower($full_state)) == "Nova Scotia") return "NS";
	if(ucwords(strtolower($full_state)) == "Nunavut") return "NT";
	if(ucwords(strtolower($full_state)) == "Ontario") return "ON";
	if(ucwords(strtolower($full_state)) == "Prince Edward Island") return "PE";
	if(ucwords(strtolower($full_state)) == "Quebec") return "QC"; 
	if(ucwords(strtolower($full_state)) == "Saskatchewan") return "SK";
	if(ucwords(strtolower($full_state)) == "Yukon") return "YT";
	
	
	$international_state_iso2 = "";
	$tmp_sql = "SELECT Code FROM Regions WHERE Region = '". $full_state ."' OR Code = '". $full_state ."';";
	//test("tmp_sql",$tmp_sql);
	$international_state_iso2 = getTHECASHIER($tmp_sql,"geobytes");
	//test("international_state_iso2",$international_state_iso2);
	if($international_state_iso2) return $international_state_iso2;
	
	
	
	
	

		
	### NON-US/CANADA
	return "";

}



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="") {
	
	global $function_test;
	
	//echo "001<br>";
	
	if($function_test != "FALSE") {
		
		//echo "002<br>";
		
		//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_async($kurl_url, $kurl_parameters) {
	

	$ch = curl_init();
 
	curl_setopt($ch, CURLOPT_URL, $kurl_url . "?" . $kurl_parameters);
	curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
	curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
 
	curl_exec($ch);
	curl_close($ch);

}

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

	# prepare
	$ch = curl_init();

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

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

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

	# return
	return $response;
}

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

function geobytes_parser($html) {

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


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

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

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

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

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

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

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

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

        $time_zone = '';
        $tz_distance = 0;

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

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

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

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

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


function geobytes($ip) {
	
	if(stristr($_SERVER['REMOTE_ADDR'],"tube-to-text.com")) return false; 
	if(stristr($_SERVER['REMOTE_ADDR'],"Transcriber.wiki")) return false; 
	
	//don't lookup if already:
	if($_SESSION['session']['geo']) return $_SESSION['session']['geo'];  
	
	/// IP 2 LOCATION is better:
	
	
	return ip2location($ip);
	exit;
	
	
	
	
	
	
	
	
	
	
	
	
	
	### CONFIRM VALID IP:
	if(validate_public_ip($ip) == FALSE) {
		return FALSE;
	} 
	

	
	if( 
	(!$ip) ||
	($ip == "127.0.0.1") || 
	(strstr("localhost",$ip)) 
	) {
		//$ip = trim(postDATA("http://what-is-my-ip.net/?text",NULL));// kurl("what-is-my-ip.net","?text",NULL);
		//test("ip",$ip);
		//$ip = "74.81.189.1";
		$ip = "129.78.32.24"; ///AUS
	}
	
	//test("1. ip",$ip);
	//test("ip",$ip);
	
	$geobytes_method = "local";  // curl or local
	//test("geobytes_method",$geobytes_method);	

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

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

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

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

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

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

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

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

}

function ip2location($ipaddress=null) {
	
	
	$use_ipdata = TRUE;
	
	if($use_ipdata == TRUE) {
		//test("ipaddress",$ipaddress);
		$ip_geo_data = file_get_contents("https://api.ipdata.co/". $ipaddress);
		$ip_geo_data = json_decode($ip_geo_data);
		$ip_geo_data = object_to_array_v2($ip_geo_data);
		
		$ip_geo_data['iso2'] = $ip_geo_data['country_code'];
		$ip_geo_data['iso3'] = geo_data($ip_geo_data['country_code'],"iso2","iso3");
		$ip_geo_data['timezone'] = $ip_geo_data['time_zone']; 
		//$ip_geo_data[''] = _XXXXXX_;
		
		
		if($ip_geo_data['city']) {
			return $ip_geo_data;
			///done.
		} else {
			/// keep going... use legacy system
		}
			
	}
	
	
	/// don't do it again if it's already set:
	//if($_SESSION['session']['geo']['ip']) return $_SESSION['session']['geo'];    
	
	
	if(
		empty($ipaddress) ||
		($ipaddress == "127.0.0.1") ||
		($ipaddress == "127.1.1.0") ||
		($ipaddress == "0.0.0.0")
	) {
		$tmp_results['known'] = 'true';
		$tmp_results['iso2'] = "AU";
		$tmp_results['iso3'] = "AUS";
		$tmp_results['timezone'] = "+10:00";
		$tmp_results['city'] = "Orange";
		$tmp_results['region'] = "New South Wales";
		return $tmp_results;
	}
	
	
	$tmp = array();    
	
	
	
        
	$number_to_lookup = ip2locationCONVERTER($ipaddress);
	//test("number_to_lookup",$number_to_lookup);
	
	$tmp_db = "ip2location";
	$tmp_sql = "SELECT * FROM ip2location_db11 WHERE 
				ip_from <= '".$number_to_lookup."'
				AND ip_to >= '".$number_to_lookup."';";
        
	//test("tmp_sql",$tmp_sql);
	
	$location_details = readTHECASHIER($tmp_sql,$tmp_db);
	//test("location_details",$location_details);
	
	if(empty($location_details)){
	    $location_details = false; //geobytes($ipaddress);
	} else{
	    $location_details = object2array($location_details);
	    $tmp['known'] = 'true';
	    $tmp['locationcode'] = '';
	    $tmp['fips104'] = $location_details['country_code'];
	    $tmp['iso2'] = $location_details['country_code'];
	    $tmp['iso3'] = geo_data($tmp['iso2'], 'iso2','iso3');
	    $tmp['ison'] = '';
	    $tmp['internet'] = $location_details['country_code'];
	    $tmp['countryid'] = '';
	    
	    if(!empty($location_details['country_name'])) {
	    	$tmp['country'] = $location_details['country_name'];
	    	$tmp['country_name'] = $location_details['country_name'];
	    } else {
	    	$tmp['country'] = geo_data($tmp['iso2'], 'iso2','name');
	    	$tmp['country_name'] = geo_data($tmp['iso2'], 'iso2','name');
	    }
	    $tmp['regionid'] = '';
	    $tmp['region'] = $tmp['region_name'] = $location_details['region_name'];
	    $tmp['regioncode'] = '';
	    $tmp['adm1code'] = '';
	    $tmp['cityid'] = '';
	    $tmp['city'] = $tmp['city_name'] = $location_details['city_name'];
	    $tmp['zip_code'] = $tmp['postal_code'] = $location_details['zip_code'];
	    $tmp['latitude'] = $location_details['latitude'];
	    $tmp['longitude'] = $location_details['longitude'];
	    $tmp['timezone'] = $location_details['time_zone'];
	    $tmp['certainty'] = '';
	    $tmp['ip'] = $ipaddress;
	    $tmp['ip_from'] = $location_details['ip_from'];
	    $tmp['ip_to'] = $location_details['ip_to'];
	    
	    if(empty($tmp['iso3'])) $tmp['known'] = 'false';
	
	    $location_details = $tmp;
	}
                
	return $location_details;	
}

function display_location_1($ip) {

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







function display_location_2($ip) {

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




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


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


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


function clean_authorization_number($authorization_number) {


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



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

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


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

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

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

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



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

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


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

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


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

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

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





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


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

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

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

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

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


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


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

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

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

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








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


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

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

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





function biometric_registration_vMATCH_UPLOADED($vMATCH_audio_id,$voice_file_type="BASE") {

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


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

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

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

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

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



function biometric_registration_vMATCH_RECORDED($vMATCH_audio_id,$voice_file_type="BASE") {

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


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

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

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

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

                }

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

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

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

	$biometric_status = "";

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

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

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

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


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

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

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

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


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

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

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

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


function vPASS_biometric_registration_combination($voicefileids_array) {

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


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



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

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

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

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

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

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



function biometric_registration_combination($voicefileids_array) {

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


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



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

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

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

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

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

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







function biometric_vMATCH($base_vMATCH_audio_id,$comparison_vMATCH_audio_id,$siv_tolerance="") {

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

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

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

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

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

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

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

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



function biometric_vMATCH_voiceprintid($base_voiceprintid,$comparison_vMATCH_audio_id,$siv_tolerance="") {

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

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

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

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

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

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

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


function vPASS_For_Internet_biometric_registration_combination($voicefileids_array) {

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


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


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



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

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



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

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

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

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



function transaction($transactionid=null) {

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

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


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



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

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


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

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


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

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

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



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

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

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

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

	}
}

function bonus_percentage($command) {

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

	return $tmp_bonus_payment_percentage;
}




function faq_personalizer($text_to_personalize) {

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

	return $text_to_personalize;
}


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


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



function disguise_emailaddress($emailaddress) {

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


function disguise_emailaddress_text($emailaddress) {

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


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




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






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

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

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


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

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

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

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

function country_to_currency($country_code) {


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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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


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

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

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


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

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

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

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


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

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

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



function hash_MD5($timestamp) {

	### NOTE: MD5 hash = 32 characters

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

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

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


function hash_SHA1() {

	### NOTE: SHA1 hash = 40 characters

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

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

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



function extract_hash() {

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


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


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


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


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

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

function get_the_three_transactions($transactionid) {
	
	
	/// find the transactionid if hash
	if(strlen($transactionid) >= 32) {
		$tmp_sql = "SELECT transactionid FROM transactions WHERE hash = '". $transactionid ."';";
		logger3("tmp_sql",$tmp_sql);
		$transactionid = getTHECASHIER($tmp_sql);
		logger3("transactionid",$transactionid);
	}
	
	/// find the depisit transactionid if other
	$tmp_sql = "SELECT description FROM transactions WHERE transactionid = '". $transactionid ."';";
	logger3("tmp_sql",$tmp_sql);
	$transaction_description = getTHECASHIER($tmp_sql);
	logger3("transaction_description",$transaction_description);
	
	/// find the transaction_group_hash
	$tmp_sql = "SELECT transaction_group_hash FROM transactions WHERE transactionid = '". $transactionid ."';";
	logger3("tmp_sql",$tmp_sql);
	$transaction_group_hash = getTHECASHIER($tmp_sql);
	logger3("transaction_group_hash",$transaction_group_hash);

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

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

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


function pretty_member_name_v2($member_hash) {
	
	$tmp_member_details = "";
	
	$tmp_sql = "SELECT *
				FROM members
				WHERE hash = '". $member_hash ."'
				;";
	//test("tmp_sql",$tmp_sql);
	
	$tmp_member_details = object_to_array_v2(readTHECASHIER($tmp_sql));
	
	$tmp_member_final = "";
	
	if($tmp_member_details['firstname']) {
		$tmp_member_final = $tmp_member_details['firstname'];
	}
	
	if($tmp_member_details['middlename']) {
		
		if($tmp_member_final) {
			$tmp_member_final = $tmp_member_final . " " . $tmp_member_details['middlename'];
		} else {
			$tmp_member_final = $tmp_member_details['middlename'];
		}
	}
	
	if($tmp_member_details['lastname']) {
		
		if($tmp_member_final) {
			$tmp_member_final = $tmp_member_final . " " . $tmp_member_details['lastname'];
		} else {
			$tmp_member_final = $tmp_member_details['lastname'];
		}
	}
	
	return $tmp_member_final;
}




function full_name_pretty($first_name="",$middle_name="",$last_name="",$nick_name="") {
	
	
	$tmp_member_final = "";
	
	if($first_name) {
		$tmp_member_final = ucwords(strtolower(trim($first_name)));
	}
	
	if($nick_name) {
		
		if($tmp_member_final) {
			$tmp_member_final = $tmp_member_final . ' "' . strtolower($nick_name) . '"';
		} else {
			$tmp_member_final = '"' . strtolower($nick_name) . '"';
		}
	}
	
	if($middle_name) {
		
		if($tmp_member_final) {
			$tmp_member_final = $tmp_member_final . " " . ucwords(strtolower(trim($middle_name)));
		} else {
			$tmp_member_final = ucwords(strtolower(trim($middle_name)));
		}
	}
	
	if($last_name) {
		
		if($tmp_member_final) {
			$tmp_member_final = $tmp_member_final . " " . ucwords(strtolower(trim($last_name)));
		} else {
			$tmp_member_final = ucwords(strtolower(trim($last_name)));
		}
	}
	
	return $tmp_member_final;
}








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


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

	
	return $tmp_permissions_extracted;
}




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

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

	return $results;
}


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

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

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


function generatePassword($length) {

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

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

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

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

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

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


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


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

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


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

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

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

	return $_SESSION['maxmind'];
}

function session_last_page() {

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

}


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

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

function currency_symbol($currency_iso3) {

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

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

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

    return $ub;
}

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

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

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


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


function display_available_balance() {

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

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


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


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

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

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





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



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


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

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

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

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

}


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

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

}



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

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

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

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

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

	return $payload_string;
}



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

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

}

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


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


function firstdataGetNewBatchNumber() {

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

function firstdataGetCurrentClientRefTransactionID_ORIGINAL_DB() {

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

function firstdataGetNewClientRefTransactionID_ORIGINAL_DB() {

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



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

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

function firstdataGetNewClientRefTransactionID() {

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

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

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



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

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

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

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

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

}


function display_LOAD($display_account_disposit_LOAD,$transaction_details) {

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




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

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


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



function random_string($desired_random_string_length,$choose_from_string) {
	return strtoupper(substr(str_shuffle(str_repeat($choose_from_string, $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:

	$host_email_account = "bangk.net";
	if($_SESSION['template']['company']['host_email_account']) $host_email_account = strtolower($_SESSION['template']['company']['host_email_account']);


	$tmp_changed = datetime();
	$tmp_del = "0";
	$tmp_standard = "1";
	$tmp_name = $_SESSION['account']['accountname'];
	$tmp_organization = "";
	$tmp_email = $clean_account_name."@".$host_email_account;
	$tmp_reply_to = $clean_account_name."@".$host_email_account;
	
	$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="",$DID_to_check="") {

    ### 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."';";
    //test("tmp_sql",$tmp_sql);
    $extenion_array = arrayTHECASHIER($tmp_sql);
    //test("extenion_array",$extenion_array);
    
    
    ### LIMIT TO 10,000
    $number_of_extensions = count($extenion_array);
    //test("number_of_extensions",$number_of_extensions);
    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 = "shea.writer@nsdb.com"; // $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:
	
	$record_exists = getTHECASHIER("SELECT extension FROM business_lines WHERE account_hash = '". $tmp_account_details['hash'] ."';");
	
	if($record_exists) {
		
		return false;
		# $tmp_sql = "UPDATE business_lines SET 
		# business_line_id='". $_XXXX_ ."',
		# account_hash='". $_XXXX_ ."',
		# DID_number='". $_XXXX_ ."',
		# extension='". $_XXXX_ ."'
		# WHERE account_hash = '". $_XXXX_ ."'
		# ";
	
	} else {
		
		
		$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."');
		";
		//test("tmp_sql",$tmp_sql);
		
		$results = insertTHECASHIER($tmp_sql);
		//test("results",$results);
	
		if($results == TRUE) {
			return $new_extension_number;
		} else {
			return FALSE;
		}		
	}
}


function get_business_lines($accountid) {
	
	$tmp_sql = "SELECT extension FROM business_lines WHERE accountid LIKE '". $accountid ."';";
	//test("tmp_sql",$tmp_sql);
	$extension = getTHECASHIER($tmp_sql);
	//test("extension",$extension);
	
	if(empty($extension)) {
		business_line_extension_maker($accountid,$DID_to_check="");
		$tmp_sql = "SELECT extension FROM business_lines WHERE accountid LIKE '". $accountid ."';";
		//test("2tmp_sql",$tmp_sql);
		$extension = getTHECASHIER($tmp_sql);
		//test("2extension",$extension);		
	}
	
	
	$business_lines['usa']['number'] = "1 646 655 0714";
	$business_lines['gbr']['number'] = "44 20 3608 7473";
	$business_lines['aus']['number'] = "61 2 8103 4138";
	$business_lines['usa_toll_free']['number'] = "1 888 765 0950 ";
	$business_lines['extension'] = $extension;
	return $business_lines;
}


function get_email_account_details($accountid=null) {

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


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

	//global $_SESSION;

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

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


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

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

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

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

}



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

function echo_platform() {

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

	//global $_SESSION;
	
	if(!empty($master_config_platform_emulation)) {
	    $platform_to_use = $master_config_platform_emulation;           
	} else {
		logger3("echo_platform(): _SESSION['template']['company']",$_SESSION['template']['company']);
		$platform_to_use = $_SESSION['template']['company']['name'];
	}
	
	///PAYYAP legacy patch:
	if(stristr($_SESSION['template']['company']['name'],"PAYYAP.network")) {
		$_SESSION['template']['company'] = "";
		$tmp_sql = "SELECT * FROM templates_companies WHERE templateid = '127';";
		$_SESSION['template']['company'] = object2array(readTHECASHIER($tmp_sql));
	}
	
	
	logger3("echo_platform(): platform_to_use",$platform_to_use);
	return $platform_to_use;
}

	
function get_active_system_email_account($accountid) {

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

}



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

    imap_close($mbox);
    return $count;
}

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

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




### BLINGK

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





function bangk_email_user_maker($accountid="",$account_name="") {

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

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

	if($tmp_account['business_type'] == "PERSONAL") {
		
		return $clean_account_name;
	
	} else { // business
		
		if(stristr($_SESSION['template']['company']['name'],"zoomin")) {
		
			return $clean_account_name;
		
		} else {
			
			return $clean_account_name . "-" . strtolower($tmp_account_type);
		}
	}
	

}





function add_postfix_email_account($personal_name,$username,$host,$password) {
	
	add_postfix_email_domain_if_not_exist($host);
	
	$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 add_postfix_email_domain_if_not_exist($domain) {
	
	$tmp_sql = "SELECT domain FROM `domain` WHERE domain='$domain'";	
	//test('tmp_sql', $tmp_sql);
	$is_domain_exist = getTHECASHIER($tmp_sql);
	//test('is_domain_exist', $is_domain_exist);
	if($is_domain_exist) return;
			
	$postfix_domain = $domain;
	$postfix_domain_description = $domain;
	$postfix_domain_aliases = 0;
	$postfix_domain_mailboxes = 0;
	$postfix_domain_maxquota = "1000";
	$postfix_domain_quota = 0;
	$postfix_domain_transport = 'virtual';
	$postfix_domain_backupmx = 0;
	$postfix_domain_created = datetime();
	$postfix_domain_modified = datetime();
	$postfix_domain_active = "1";
		
	
	$tmp_sql = "INSERT INTO `domain`(
	    			`domain`, 
	    			`description`, 
	    			`aliases`, 
	    			`mailboxes`, 
	    			`maxquota`, 
	    			`quota`, 
	    			`transport`,
	    			`backupmx`, 
	    			`created`, 
	    			`modified`, 
	    			`active`
	    		) VALUES (
	    			'".addslashes($postfix_domain)."',
	    			'".addslashes($postfix_domain_description)."',
	    			'".$postfix_domain_aliases."',
	    			'".$postfix_domain_mailboxes."',	    			
	    			'".$postfix_domain_maxquota."',
	    			'".$postfix_domain_quota."',
	    			'".$postfix_domain_transport."',
	    			'".$postfix_domain_backupmx."',
	    			'".$postfix_domain_created."',
	    			'".$postfix_domain_modified."',
	    			'".$postfix_domain_active."'
	    		);";
	 //test("tmp_sql",$tmp_sql);
	 return insertTHECASHIER($tmp_sql,$database_to_use="postfixadmin");

}


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



function host_prefix_maker($desired_random_string_length) {
	return strtolower(substr(str_shuffle(str_repeat("abcdefhkmnprtuvwxy34678", $desired_random_string_length)), 0, $desired_random_string_length));
}




function what_bangknet_host_to_use($accountid) {

	$tmp_username = bangk_email_user_maker($accountid);

	
	$mail_address_status = "";
	while(empty($mail_address_status)) {
		
	
		$host_prefix = host_prefix_maker($prefix_length=3); // needs attention -- going to get slow. needs a better logi structure.
		logger3("host_prefix",$host_prefix);
		
		$host_email_account = ".bangk.net";
		
		if($_SESSION['template']['company']['host_email_account']) $host_email_account = "." . strtolower($_SESSION['template']['company']['host_email_account']);
		
		
		$tmp_host = $host_prefix . $host_email_account;
		
		$tmp_sql = "SELECT email_account_id FROM email_accounts WHERE username = '".$tmp_username."' AND host = '".$tmp_host."';";
		logger3("tmp_sql",$tmp_sql);
		
		$exists = getTHECASHIER($tmp_sql);
		logger3("exists",$exists);
		
		if(empty($exists)) $mail_address_status = "accepted";
	}
	
	# if(!empty($exists)) {
	# 	$tmp_host = "97e.bangk.net";
	# }
	
	logger3("$tmp_host",$tmp_host);
	return $tmp_host;
}


function update_bangknet_email_account($accountid) {

	// update acounts->emailaddress seperate because an account can be associated to a bangk.net account &&&&& a non-bangk.net account.
		
	## GET ORIGINAL EMAIL ACCOUNt DETAILS:
	$tmp_sql = "SELECT * FROM email_accounts WHERE accountid = '". $accountid ."';";
	logger3("tmp_sql",$tmp_sql);
	$original_account_details = readTHECASHIER($tmp_sql);
	logger3("original_account_details",$original_account_details);
	
	### GENERAL
	$tmp_datetime = datetime();
	$account_details = account($accountid);
	$datetime_updated = datetime();
	$clean_account_name = bangk_email_user_maker($accountid);
	
	// don't do anything if old and new usernames match:
	if(
	(strtolower($original_account_details->username)) == (strtolower($clean_account_name)) 
	) {
		return "done.";
	}
	
	
	$host_name = what_bangknet_host_to_use($accountid);


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

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


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-master/Services/Twilio.php");
	 
	// set your AccountSid and AuthToken from www.twilio.com/user/account
	$AccountSid = "AC6759779db19651223a700c633e613021";
	$AuthToken = "20a52a3b8dccdbc33d4a7df45b5368bf";
	  
	$client = new Services_Twilio($AccountSid, $AuthToken);
	
	//logger3("client",$client);
	 
	 
	 
	 if(
	 	((substr($contacts_array['contacts_phone'],0,1)) == "+")
	 	&& ($sms_message)
	 ) {
		
		$final_number_string = $contacts_array['contacts_phone'];
		 
	 } else {
		 
		 $final_number_string = "+". $country_code . $mobile_number;
	 }
	  
	$sms = $client->account->messages->sendMessage(
	 "+18884075084", // From this number
	 "+".$country_code.$mobile_number,
	 $sms_message);
	 
	//logger3("sms",$sms);
	##########################################################
	
	
	##########################################################
	### nexmo (good for SMS)

	// $send_url = "https://rest.nexmo.com/sms/json";
	// $send_data .= "";
	// $send_data .= "api_key=9528d5c9&api_secret=cbd9cf7b309be543&";
	// $send_data .= "from=12028585575";
	// $send_data .= "&to=".$country_code.$mobile_number;
	// $send_data .= "&text=".$sms_message;
	// postDATA($send_url,$send_data,$asynchronous = false);


	##########################################################
	
}


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

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

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


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




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


    ####################################################
    ### START: PMD (paymentdepot)
    ####################################################
    if(stristr($translog_details['acquirer'],"ARETO")) {
        
            
        # $translog_details['transactionid_from_gateway']
        # $translog_details['amount']
        # $translog_details['credit_card_number']
        # $translog_details['expiration_month']
        # $translog_details['expiration_year']
        require_once($master_config_root_path . "shared/process_refund_ARETO.shared"); 
        
        
		    
        logger3('ARETO_refund', $result);	    	    		
        ### FINAL RETURN SETTING:
        if(
        ($areto_response_translated['c-result']['c-container']['internalorderid']) &&
        (!empty($areto_response_translated['c-result']['c-container']['internalorderid']))
        ) {
                $return = "COMPLETED";
        } else {
                $return = "FAILED";
        }     
    }
    ####################################################
    ### END: PMD (paymentdepot)
    ####################################################




    return $return;
}



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


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

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


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


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

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

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

}


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

	# test("1name_of_country_field",$name_of_country_field); 
	# 
	# test("2session_value",$session_value);
	# 
	# test("3css_class",$css_class);
	# 
	# test("4id_to_update",$id_to_update);
	# 
	# test("5editable_form",$editable_form);
	
	
	if(strlen($session_value) == 3) {
		$country_iso3 = $session_value;
	} else {
		$country_name = strtoupper($session_value);
	}
	
	if(
		(!$country_iso3) &&
		(!$country_name)
	) {
		//$country_iso3 = $_SESSION['account']['country_iso3'];
	}
		
	//test("country_name",$country_name);


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


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

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

	$html_output .= "<option value='AUS'>Australia</option>";
	$html_output .= "<option value='CAN'>Canada</option>";
	$html_output .= "<option value='CHN'>China</option>";
	$html_output .= "<option value='DEU'>Germany</option>";
	$html_output .= "<option value='HKG'>Hong Kong</option>";
	$html_output .= "<option value='GBR'>Great Britain</option>";
	$html_output .= "<option value='IRE'>Ireland</option>";
	$html_output .= "<option value='ISR'>Israel</option>";
	$html_output .= "<option value='IND'>India</option>";
	$html_output .= "<option value='KEN'>Kenya</option>";
	$html_output .= "<option value='SGP'>Singapore</option>";
	$html_output .= "<option value='SAU'>Saudi Arabia</option>";
	$html_output .= "<option value='ZAF'>South Africa</option>";
	$html_output .= "<option value='MYS'>Malaysia</option>";
	$html_output .= "<option value='THA'>Thailand</option>";
	$html_output .= "<option value='USA'>United States</option>";
	$html_output .= "<option value='' disabled>--- ALL:</option>";
	
	$tmp_sql = "SELECT geodataid FROM geo_data WHERE calling_code != '' AND  calling_code IS NOT NULL;";
	$geodataid_array = arrayTHECASHIER($tmp_sql);
	//test("geodataid_array",$geodataid_array);
	foreach($geodataid_array as $key => $geodataid) {
		$tmp_sql = "SELECT * FROM geo_data WHERE geodataid LIKE '".$geodataid."';";
		$geodata_row_details = readTHECASHIER($tmp_sql);
		$html_output .= "<option value='" . $geodata_row_details->iso3 . "'>" . $geodata_row_details->printable_name . "</option>";
	
	}
	$html_output .= "</select>";
	$html_output .= "</div>";
	return $html_output;

}


function outputSelectCountryWIZARD_disabled($name_of_country_field="",$session_value="",$css_class="",$id_to_update="") {

	# test("name_of_country_field",$name_of_country_field);
	# 
	# test("session_value",$session_value);
	# 
	# test("css_class",$css_class);
	# 
	# test("id_to_update",$id_to_update);
	# 
	# test("editable_form",$editable_form);
	
	$editable_form = "disabled";
	
	test("editable_form",$editable_form);
	
	if(strlen($session_value) == 3) {
		$country_iso3 = $session_value;
	} else {
		$country_name = strtoupper($session_value);
	}
	
	if(
		(!$country_iso3) &&
		(!$country_name)
	) {
		//$country_iso3 = $_SESSION['account']['country_iso3'];
	}
		
	//test("country_name",$country_name);


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


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

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

	$html_output .= "<option value='AUS'>Australia</option>";
	$html_output .= "<option value='CAN'>Canada</option>";
	$html_output .= "<option value='CHN'>China</option>";
	$html_output .= "<option value='DEU'>Germany</option>";
	$html_output .= "<option value='HKG'>Hong Kong</option>";
	$html_output .= "<option value='GBR'>Great Britain</option>";
	$html_output .= "<option value='IRE'>Ireland</option>";
	$html_output .= "<option value='ISR'>Israel</option>";
	$html_output .= "<option value='IND'>India</option>";
	$html_output .= "<option value='KEN'>Kenya</option>";
	$html_output .= "<option value='SGP'>Singapore</option>";
	$html_output .= "<option value='SAU'>Saudi Arabia</option>";
	$html_output .= "<option value='ZAF'>South Africa</option>";
	$html_output .= "<option value='MYS'>Malaysia</option>";
	$html_output .= "<option value='THA'>Thailand</option>";
	$html_output .= "<option value='USA'>United States</option>";
	$html_output .= "<option value='' disabled>--- ALL:</option>";
	
	$tmp_sql = "SELECT geodataid FROM geo_data WHERE calling_code != '' AND  calling_code IS NOT NULL;";
	$geodataid_array = arrayTHECASHIER($tmp_sql);
	//test("geodataid_array",$geodataid_array);
	foreach($geodataid_array as $key => $geodataid) {
		$tmp_sql = "SELECT * FROM geo_data WHERE geodataid LIKE '".$geodataid."';";
		$geodata_row_details = readTHECASHIER($tmp_sql);
		$html_output .= "<option value='" . $geodata_row_details->iso3 . "'>" . $geodata_row_details->printable_name . "</option>";
	
	}
	$html_output .= "</select>";
	$html_output .= "</div>";
	return $html_output;

}




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

	//test("session_value",$session_value);
	
	//test("1. id_to_update",$id_to_update);
	
	if(strlen($session_value) == 3) {
		$country_iso3 = $session_value;
	} else {
		$country_name = strtoupper($session_value);
	}
	
	if(
		(!$country_iso3) &&
		(!$country_name)
	) {
		//$country_iso3 = $_SESSION['account']['country_iso3'];
	}
		
	//test("country_name",$country_name);


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


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

	$display_selected = "";
	if(!$session_value) { 
		
		$display_selected = "selected";
		$html_output .= "<option value='' disabled ". $display_selected .">Please select one...</option>";
	
	} else {
		
		$display_selected = "selected";
		
		if($country_iso3) {
			
			$html_output .= "<option value='" . $country_iso3 . "' ". $display_selected .">( +" . geo_data($country_iso3,"iso3","calling_code") . " ) " . geo_data($country_iso3,"iso3","printable_name") . "</option>";
		
		} else {
			$html_output .= "<option value='" . geo_data($country_name,"name","iso3") . "'>(" . geo_data($country_name,"name","country_code") . ") " . $country_name . "</option>";
		
		}
		
	}
	
	$html_output .= "<option value='' disabled></option>";

	$html_output .= "<option value='USA'>( +" . geo_data("USA","iso3","calling_code") . " ) United States</option>";
	$html_output .= "<option value='CAN'>( +" . geo_data("CAN",'iso3','calling_code') . " ) Canada</option>";
	
	$html_output .= "<option value='AUS'>( +" . geo_data("AUS",'iso3','calling_code') . " ) Australia</option>";
	
	$html_output .= "<option value='CHN'>( +" . geo_data("CHN","iso3","calling_code") . " ) China</option>";
	$html_output .= "<option value='DEU'>( +" . geo_data("DEU","iso3","calling_code") . " ) Germany</option>";
	$html_output .= "<option value='HKG'>( +" . geo_data("HKG","iso3","calling_code") . " ) Hong Kong</option>";
	$html_output .= "<option value='GBR'>( +" . geo_data("GBR","iso3","calling_code") . " ) Great Britain</option>";
	$html_output .= "<option value='IRE'>( +" . geo_data("GBR","iso3","calling_code") . " ) Ireland</option>";
	$html_output .= "<option value='ISR'>( +" . geo_data("ISR","iso3","calling_code") . " ) Israel</option>";
	$html_output .= "<option value='IND'>( +" . geo_data("IND","iso3","calling_code") . " ) India</option>";
	$html_output .= "<option value='KEN'>( +" . geo_data("KEN","iso3","calling_code") . " ) Kenya</option>";
	$html_output .= "<option value='SGP'>( +" . geo_data("SGP","iso3","calling_code") . " ) Singapore</option>";
	$html_output .= "<option value='SAU'>( +" . geo_data("SAU","iso3","calling_code") . " ) Saudi Arabia</option>";
	$html_output .= "<option value='ZAF'>( +" . geo_data("ZAF","iso3","calling_code") . " ) South Africa</option>";
	$html_output .= "<option value='MYS'>( +" . geo_data("MYS","iso3","calling_code") . " ) Malaysia</option>";
	$html_output .= "<option value='THA'>( +" . geo_data("THA","iso3","calling_code") . " ) Thailand</option>";
	
	$html_output .= "<option value='' disabled>--- ALL:</option>";
	
	$tmp_sql = "SELECT geodataid FROM geo_data WHERE calling_code != '' AND  calling_code IS NOT NULL;";
	$geodataid_array = arrayTHECASHIER($tmp_sql);
	//test("geodataid_array",$geodataid_array);
	foreach($geodataid_array as $key => $geodataid) {
		$tmp_sql = "SELECT * FROM geo_data WHERE geodataid LIKE '".$geodataid."';";
		$geodata_row_details = readTHECASHIER($tmp_sql);
		$html_output .= "<option value='" . $geodata_row_details->iso3 . "'>( +" . geo_data($geodata_row_details->iso3,"iso3","calling_code") ." ) " . $geodata_row_details->printable_name . "</option>";
	
	}
	$html_output .= "</select>";
	$html_output .= "</div>";
	return $html_output;

}




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

function outputSelectCountryAVT($name_of_field,$session_value=null,$css_class=null) {
        
	if(strlen($session_value) == 3) {
		$country_iso3 = $session_value;
	} else {
		$country_name = strtoupper($session_value);
	}
	
	
	//test("country_name",$country_name);


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


	$html_output = "<span class='".$css_class."'>";
	$html_output .= "<select id='".$name_of_field."' name='".$name_of_field."' onChange='onChangeCountryAVT(this);'>";

	
	if(empty($session_value)) { 
		$html_output .= "<option value=''>Click here to select the COUNTRY to call...</option>";
	} else {
		if($country_iso3) {
			$html_output .= "<option value='" . $country_iso3 . "'>" . geo_data($country_iso3,"iso3","printable_name") . "</option>";
		} else {
			$html_output .= "<option value='" . geo_data($country_name,"name","iso3") . "'>" . $country_name . "</option>";
		}
		
	}
	
	$html_output .= "<option value=''></option>";
	$html_output .= "<option value='AUS'>Australia</option>";
	$html_output .= "<option value='CAN'>Canada</option>";
	$html_output .= "<option value='GBR'>Great Britain</option>";
	$html_output .= "<option value='IRL'>Ireland</option>";
	$html_output .= "<option value='NZD'>New Zealand</option>";
	$html_output .= "<option value='USA'>United States</option>";
	$html_output .= "<option value=''></option>";

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

}





function outputSelectDOB($session_value_year=null,$session_value_month=null,$session_value_day=null,$css_class=null,$session_to_update='',$update_innerHTML='',$editable_form='') {

  $html_output = "";
  $html_output .= "</nobr>";
  if(empty($css_class)) $css_class = "default_select_style";
  $html_output .= "<span class='".$css_class."'>";
  
  
  if(!empty($update_innerHTML)) $add_update_innerHTML = "displayUpdatedBirthdate(this,'". $update_innerHTML ."_birth_year');";
  if(!empty($session_to_update)) $add_session_parameter = "updateSESSION(this,'". $session_to_update ."_birth_year');";
  $html_output .= "<select id='birth_year' name='birth_year' onChange=\"validateSelectDOB(this); $add_session_parameter $add_update_innerHTML\" onFocus=\"validateSelectDOB(this);\" ". $editable_form ." />";
  $add_session_parameter = "";
  $id_to_update = "";
  
  if(isset($session_value_year)) { 
    $html_output .= "<option value='" . $session_value_year . "'>" . $session_value_year . "</option>
    <option value=''></option>";
  } 
  $html_output .= "
    <option value=''>Year:</option>
    <option value='1900'>1900</option>
    <option value='1901'>1901</option>
    <option value='1902'>1902</option>
    <option value='1903'>1903</option>
    <option value='1904'>1904</option>
    <option value='1905'>1905</option>
    <option value='1906'>1906</option>
    <option value='1907'>1907</option>
    <option value='1908'>1908</option>
    <option value='1909'>1909</option>
    <option value='1910'>1910</option>
    <option value='1911'>1911</option>
    <option value='1912'>1912</option>
    <option value='1913'>1913</option>
    <option value='1914'>1914</option>
    <option value='1915'>1915</option>
    <option value='1916'>1916</option>
    <option value='1917'>1917</option>
    <option value='1918'>1918</option>
    <option value='1919'>1919</option>
    <option value='1920'>1920</option>
    <option value='1921'>1921</option>
    <option value='1922'>1922</option>
    <option value='1923'>1923</option>
    <option value='1924'>1924</option>
    <option value='1925'>1925</option>
    <option value='1926'>1926</option>
    <option value='1927'>1927</option>
    <option value='1928'>1928</option>
    <option value='1929'>1929</option>
    <option value='1930'>1930</option>
    <option value='1931'>1931</option>
    <option value='1932'>1932</option>
    <option value='1933'>1933</option>
    <option value='1934'>1934</option>
    <option value='1935'>1935</option>
    <option value='1936'>1936</option>
    <option value='1937'>1937</option>
    <option value='1938'>1938</option>
    <option value='1939'>1939</option>
    <option value='1940'>1940</option>
    <option value='1941'>1941</option>
    <option value='1942'>1942</option>
    <option value='1943'>1943</option>
    <option value='1944'>1944</option>
    <option value='1945'>1945</option>
    <option value='1946'>1946</option>
    <option value='1947'>1947</option>
    <option value='1948'>1948</option>
    <option value='1949'>1949</option>
    <option value='1950'>1950</option>
    <option value='1951'>1951</option>
    <option value='1952'>1952</option>
    <option value='1953'>1953</option>
    <option value='1954'>1954</option>
    <option value='1955'>1955</option>
    <option value='1956'>1956</option>
    <option value='1957'>1957</option>
    <option value='1958'>1958</option>
    <option value='1959'>1959</option>
    <option value='1960'>1960</option>
    <option value='1961'>1961</option>
    <option value='1962'>1962</option>
    <option value='1963'>1963</option>
    <option value='1964'>1964</option>
    <option value='1965'>1965</option>
    <option value='1966'>1966</option>
    <option value='1967'>1967</option>
    <option value='1968'>1968</option>
    <option value='1969'>1969</option>
    <option value='1970'>1970</option>
    <option value='1971'>1971</option>
    <option value='1972'>1972</option>
    <option value='1973'>1973</option>
    <option value='1974'>1974</option>
    <option value='1975'>1975</option>
    <option value='1976'>1976</option>
    <option value='1977'>1977</option>
    <option value='1978'>1978</option>
    <option value='1979'>1979</option>
    <option value='1980'>1980</option>
    <option value='1981'>1981</option>
    <option value='1982'>1982</option>
    <option value='1983'>1983</option>
    <option value='1984'>1984</option>
    <option value='1985'>1985</option>
    <option value='1986'>1986</option>
    <option value='1987'>1987</option>
    <option value='1988'>1988</option>
    <option value='1989'>1989</option>
    <option value='1990'>1990</option>
    <option value='1991'>1991</option>
    <option value='1992'>1992</option>
    <option value='1993'>1993</option>
    <option value='1994'>1994</option>
    <option value='1995'>1995</option>
    <option value='1996'>1996</option>
    <option value='1997'>1997</option>
    <option value='1998'>1998</option>
    <option value='1999'>1999</option>
    <option value='2000'>2000</option>
    </select>&nbsp;";
  
  // birth_month
  if(!empty($update_innerHTML)) $add_update_innerHTML = "displayUpdatedBirthdate(this,'". $update_innerHTML ."_birth_month');";
  if(!empty($session_to_update)) $add_session_parameter = "updateSESSION(this,'". $session_to_update ."_birth_month');";
  $html_output .= "<select id='birth_month' name='birth_month' onChange=\"validateSelectDOB(this); $add_session_parameter $add_update_innerHTML\" ". $editable_form ." />";
  $add_update_innerHTML = "";
  $add_session_parameter = "";
  
  if(isset($session_value_month)) { 
    $html_output .= "<option value='" . $session_value_month . "'>" . $session_value_month . "</option>
    <option value=''></option>";
  } 
  $html_output .= "
    <option value=''>Month:</option>
    <option value='01'>01 (Jan)</option>
    <option value='02'>02 (Feb)</option>
    <option value='03'>03 (Mar)</option>
    <option value='04'>04 (Apr)</option>
    <option value='05'>05 (May)</option>
    <option value='06'>06 (Jun)</option>
    <option value='07'>07 (Jul)</option>
    <option value='08'>08 (Aug)</option>
    <option value='09'>09 (Sep)</option>
    <option value='10'>10 (Oct)</option>
    <option value='11'>11 (Nov)</option>
    <option value='12'>12 (Dec)</option>
    </select>&nbsp;"; 
  
  // birth_day
   if(!empty($update_innerHTML)) $add_update_innerHTML = "displayUpdatedBirthdate(this,'". $update_innerHTML ."_birth_day');";
  if(!empty($session_to_update)) $add_session_parameter = "updateSESSION(this,'". $session_to_update ."_birth_day');";
  $html_output .= "<select id='birth_day' name='birth_day' onChange=\"validateSelectDOB(this); $add_session_parameter $add_update_innerHTML\" ". $editable_form ." />";
  $add_update_innerHTML = "";
  $add_session_parameter = "";
  
  
  
  if(isset($session_value_day)) { 
    $html_output .= "<option value='" . $session_value_day . "'>" . $session_value_day . "</option>
    <option value=''></option>";
  } 
  $html_output .= "
    <option value=''>Day:</option>
    <option value='01'>01</option>
    <option value='02'>02</option>
    <option value='03'>03</option>
    <option value='04'>04</option>
    <option value='05'>05</option>
    <option value='06'>06</option>
    <option value='07'>07</option>
    <option value='08'>08</option>
    <option value='09'>09</option>
    <option value='10'>10</option>
    <option value='11'>11</option>
    <option value='12'>12</option>
    <option value='13'>13</option>
    <option value='14'>14</option>
    <option value='15'>15</option>
    <option value='16'>16</option>
    <option value='17'>17</option>
    <option value='18'>18</option>
    <option value='19'>19</option>
    <option value='20'>20</option>
    <option value='21'>21</option>
    <option value='22'>22</option>
    <option value='23'>23</option>
    <option value='24'>24</option>
    <option value='25'>25</option>
    <option value='26'>26</option>
    <option value='27'>27</option>
    <option value='28'>28</option>
    <option value='29'>29</option>
    <option value='30'>30</option>
    <option value='31'>(31)</option>
    </select>";
  $html_output .= "</span>";
  $html_output .= "</nobr>";
  ///test("html_output",$html_output);
  return $html_output;
  
}

## DATE OF INCORPORATION
function outputSelectDOI($session_value_year=null,$session_value_month=null,$session_value_day=null,$css_class=null) {


  if(empty($css_class)) $css_class = "default_select_style";
  $html_output = "<span class='".$css_class."'>";
  $html_output .= "<select id='birth_year' name='birth_year' onFocus='validateSelectDOB(this);' onChange='validateSelectDOB(this);'>";
  
  if(!empty($session_value_year)) { 
    $html_output .= "<option value='" . $session_value_year . "'>" . $session_value_year . "</option>
    <option value=''></option>";
  }
  $year = date("Y");
  $html_output .= "<option value=''>Year:</option>";
  
  while($year >= "1900") {
	  $html_output .= "<option value='$year'>$year</option>";
	  $year = $year - "1";
  }
  
  $html_output .= "</select>";
  $html_output .= "&nbsp;";
  
  // birth_month
  $html_output .= "<select id='birth_month' name='birth_month' onChange='validateSelectDOB(this);'>";
    
  if(!empty($session_value_month)) { 
    $html_output .= "<option value='" . $session_value_month . "'>" . $session_value_month . "</option>
    <option value=''></option>";
  } 
  $html_output .= "
    <option value=''>Month:</option>
    <option value='01'>01 (Jan)</option>
    <option value='02'>02 (Feb)</option>
    <option value='03'>03 (Mar)</option>
    <option value='04'>04 (Apr)</option>
    <option value='05'>05 (May)</option>
    <option value='06'>06 (Jun)</option>
    <option value='07'>07 (Jul)</option>
    <option value='08'>08 (Aug)</option>
    <option value='09'>09 (Sep)</option>
    <option value='10'>10 (Oct)</option>
    <option value='11'>11 (Nov)</option>
    <option value='12'>12 (Dec)</option>
    </select>&nbsp;"; 
  
  $html_output .= "<select id='birth_day' name='birth_day' onChange='validateSelectDOB(this);'>";
  
  if(!empty($session_value_day)) { 
    $html_output .= "<option value='" . $session_value_day . "'>" . $session_value_day . "</option>
    <option value=''></option>";
  } 
  $html_output .= "
    <option value=''>Day:</option>
    <option value='01'>01</option>
    <option value='02'>02</option>
    <option value='03'>03</option>
    <option value='04'>04</option>
    <option value='05'>05</option>
    <option value='06'>06</option>
    <option value='07'>07</option>
    <option value='08'>08</option>
    <option value='09'>09</option>
    <option value='10'>10</option>
    <option value='11'>11</option>
    <option value='12'>12</option>
    <option value='13'>13</option>
    <option value='14'>14</option>
    <option value='15'>15</option>
    <option value='16'>16</option>
    <option value='17'>17</option>
    <option value='18'>18</option>
    <option value='19'>19</option>
    <option value='20'>20</option>
    <option value='21'>21</option>
    <option value='22'>22</option>
    <option value='23'>23</option>
    <option value='24'>24</option>
    <option value='25'>25</option>
    <option value='26'>26</option>
    <option value='27'>27</option>
    <option value='28'>28</option>
    <option value='29'>29</option>
    <option value='30'>30</option>
    <option value='31'>(31)</option>
    </select>";
  $html_output .= "</span>";
  
  return $html_output;
  
}



function outputSelectCallingCode($name_of_field,$session_value=null,$css_class=null) {

	if(strlen($session_value) == 3) {
		$country_iso3 = $session_value;
	}
	
	
	//test("country_name",$country_name);


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


	$html_output = "<span class='".$css_class."'>";
	$html_output .= "<select id='".$name_of_field."' name='".$name_of_field."' onChange='onChangeCountryCode(this);'>";

	
	if(empty($session_value)) { 
		$html_output .= "<option value=''>Select Calling Code...</option>";
	} else {
		$html_output .= "<option value='" . $session_value . "'>+" . $session_value . "</option>";
	}
	
	$html_output .= "<option value=''></option>";

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

}









function translog($translogid) {
	$tmp_sql = "SELECT * FROM translog WHERE translogid = '".$translogid."';";
	return object2array(readTHECASHIER($tmp_sql));
}


function get_dynamic_fee_for_this_account($business_accountid) {
	
	if(empty($business_accountid)) $business_accountid = $_SESSION['account']['accountid'];
	
	//test("_SESSION['account']['accountid']",$_SESSION['account']['accountid']);
	
	//$rating = get_merchant_rating($business_accountid);
	
	//test("rating",$rating);
	
	//$fee = get_dynamic_fee($rating['satisfied']/100,$acount_sponsor_accountid='',$business_accountid);
	
	//test("fee",$fee);
	
	global $master_config_transaction_fee_PAYYAP_flat;
	global $master_config_transaction_fee_PAYYAP_percentage;
	
	$fee_array['flat'] = $master_config_transaction_fee_PAYYAP_flat;
	$fee_array['percentage'] = $master_config_transaction_fee_PAYYAP_percentage;
	
	return $fee_array;
}

function get_dynamic_fee($rating,$acount_sponsor_accountid='',$business_accountid='') {


	if(!empty($business_accountid)) {
		
		//test("a",$business_accountid);
		$tmp_sql = "SELECT gateway_profile FROM accounts WHERE accountid = '". $business_accountid ."';";
		$gateway_profile = getTHECASHIER($tmp_sql);
		//test("tmp_sql",$tmp_sql);
		//test("b",$gateway_profile);

	} else {
		
		
		//test("2",0);
		$sponsor_accountid = getTHECASHIER("SELECT sponsor_accountid FROM accounts WHERE accountid = '". $accountid ."';");
		//test("sponsor_accountid",$sponsor_accountid);
		
		/// check the payme business
		if(!empty($acount_sponsor_accountid)) {
			
			$gateway_profile = getTHECASHIER("SELECT associated_gateway FROM affiliates WHERE hash = '". $acount_sponsor_accountid ."';");
			//test("1: gateway_profile",$gateway_profile);
		
		} else if(
		(empty($acount_sponsor_accountid)) &&
		(is_array($_SESSION['payme'])) 
		){
			//test("_SESSION['payme']",$_SESSION['payme']);
			$gateway_profile = getTHECASHIER("SELECT associated_gateway FROM affiliates WHERE hash = '". $_SESSION['payme']['business']['account']['sponsor_accountid'] ."';");
			//test("2: gateway_profile",$gateway_profile);
		
		/// check the 
		} else 	if(
		(empty($acount_sponor_accountid)) &&
		(!stristr($_SERVER['SCRIPT_URI'],".admin")) &&
		(is_array($_SESSION['account'])) 
		){
			//test("_SERVER['REQUEST_URI']",$_SERVER['REQUEST_URI']);
			//test("_SERVER['SCRIPT_URI']",$_SERVER['SCRIPT_URI']);
			$gateway_profile = getTHECASHIER("SELECT associated_gateway FROM affiliates WHERE hash = '". $_SESSION['account']['sponsor_accountid'] ."';");
			//test("3: gateway_profile",$gateway_profile);
		
		}
		
		
	}




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

	
	
	return "0.0950";
	

	#### if(stristr($gateway_profile,"ECP")) {
	#### 	if($rating < 0.90) return 0.250;
	#### 	if($rating < 0.91) return 0.189;
	#### 	if($rating < 0.92) return 0.179;
	#### 	if($rating < 0.93) return 0.169;
	#### 	if($rating < 0.94) return 0.159;
	#### 	if($rating < 0.95) return 0.149;
	#### 	if($rating < 0.96) return 0.139;
	#### 	if($rating < 0.97) return 0.129;
	#### 	if($rating < 0.08) return 0.129;
	#### 	if($rating < 0.99) return 0.129;
	#### 	if($rating <= 01.00) return 0.129;
	#### }
	#### 
	### DEFAULT:
	### if($rating < 0.90) return 0.250;
	### if($rating < 0.91) return 0.189;
	### if($rating < 0.92) return 0.179;
	### if($rating < 0.93) return 0.169;
	### if($rating < 0.94) return 0.159;
	### if($rating < 0.95) return 0.149;
	### if($rating < 0.96) return 0.139;
	### if($rating < 0.97) return 0.129;
	### if($rating < 0.08) return 0.119;
	### if($rating < 0.99) return 0.109;
	### if($rating <= 01.00) return 0.099;	
}

function get_dynamic_DTR($accountid='',$rating='') {
	
	
	return 30; // days

	//test("get_dynamic_DTR(): accountid",$accountid);
	//test("get_dynamic_DTR(): rating",$rating);
	
	if(!empty($accountid)) {

		//test("0. rating",$$rating);
		
		if(empty($rating)) {
			$rating_details = get_merchant_rating($accountid);
			//test("get_dynamic_DTR($accountid): rating_details",$rating_details);
			$rating = $rating_details['decimal'];
		}
		
		
		### GATEWAY EXCEPTIONS:
		/// ECP:
		$sponsor_accountid = getTHECASHIER("SELECT sponsor_accountid FROM accounts WHERE accountid = '". $accountid ."';");
		$gateway_profile = getTHECASHIER("SELECT associated_gateway FROM affiliates WHERE hash = '". $sponsor_accountid ."';");
		//if(stristr($sponsor_accountid,"b7e9aac09c099d4bfe5cfc85917df9e3")) return 20;	
		if(empty($gateway_profile))  {
			$gateway_profile = getTHECASHIER("SELECT gateway_profile FROM accounts WHERE accountid = '". $accountid ."';");
		}

		### ARETO PROFILE
		if(
		(stristr($gateway_profile,"NEW")) ||
		(stristr($gateway_profile,"ARETO"))
		) {
			
			
		}
		
		
		

		### ECP PROFILE
		if(
		(stristr($gateway_profile,"NEW")) ||
		(stristr($gateway_profile,"ECP"))
		) {
			
			if($rating < 0.90) return 90; // days
			if($rating < 0.91) return 60;
			if($rating < 0.92) return 55;
			if($rating < 0.93) return 50;
			if($rating < 0.94) return 45;
			if($rating < 0.95) return 40;
			if($rating < 0.96) return 35;
			if($rating < 0.97) return 30;
			if($rating < 0.08) return 30;
			if($rating < 0.99) return 30;
			if($rating <= 01.00) return 30;
		}
		
		### DEFAULT PROFILE	
		if($rating < 0.90) return 90; // days
		if($rating < 0.91) return 60;
		if($rating < 0.92) return 55;
		if($rating < 0.93) return 50;
		if($rating < 0.94) return 45;
		if($rating < 0.95) return 40;
		if($rating < 0.96) return 35;
		if($rating < 0.97) return 30;
		if($rating < 0.08) return 25;
		if($rating < 0.99) return 20;
		if($rating <= 01.00) return 15;
		
		
		
		
		### GET MERCHANT RATING
		//$rating_details = get_merchant_rating($accountid);
		//$rating = $rating_details['decimal'];
	
	} else {
		
		return "";
	}
	
}


function translate_gateway_profile_to_gateway($gateway_profile) {
	
	global $master_config_default_gateway;
	if($gateway_profile == "NEW") return $master_config_default_gateway;
	if($gateway_profile == "PROVEN") return $master_config_default_gateway;
	
}


function get_merchant_rating($business_accountid,$start_date='',$limit_date='',$display_logging='') {
	$accountid = $business_accountid;
	$version = "2";
	$personal_or_business = getTHECASHIER("SELECT accounttype WHERE accountid = '". $accountid ."';");
	if(stristr($personal_or_business,"PERSONAL")) return FALSE;

	//logger3("get_merchant_rating(business_accountid=$business_accountid): ",$x);
		

	if(empty($display_logging)) $display_logging = ""; // for algorithm testing
	if(empty($limit_days_ago)) $limit_days_ago = "30";

	### get most recent transaction to establish startdate
	$tmp_sql = "SELECT requested_datetime FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	ORDER BY updated_datetime DESC
	LIMIT 1";
	//logger3("tmp_sql",$tmp_sql);
	$most_recent_transaction_datetime = getTHECASHIER($tmp_sql);
	
	$account_details = object2array(readTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';"));
	
	
	//logger3("dynamic_processing_profile($accountid)",$dynamic_processing_profile);
	
	### if(stristr($dynamic_processing_profile['profile_name'],"PMD")) {
	### 
	### 	global $master_config_gateway_PMD_startdate;
	### 	//logger3("master_config_gateway_PMD_startdate",$master_config_gateway_PMD_startdate);
	### 	
	### 	if($most_recent_transaction_datetime > $master_config_gateway_PMD_startdate) {
	### 		$forget_about_old_chargebacks_for_businesses_moving_forward = "AND requested_datetime > '". $master_config_gateway_PMD_startdate ."'";
	### 	}
	### 
	### } else {
	### 	
	### 	$forget_about_old_chargebacks_for_businesses_moving_forward = "";
	### 
	### }
	
	//logger3("$accountid: forget_about_old_chargebacks_for_businesses_moving_forward",$forget_about_old_chargebacks_for_businesses_moving_forward);
	
	$account_details = object2array(readTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';"));
	
	logger3("account_details['status_payments']",$account_details['status_payments']);
	
	if(stristr($account_details['status_payments'],"ON")) {
	    //global $master_config_gateway_ECP_startdate
	    global $master_config_gateway_ECP_startdate;
	    global $master_config_gateway_PMD_startdate;

	    $dynamic_processing_profile = get_dynamic_processing_profile($accountid);
	    
	    logger3("dynamic_processing_profile['profile_name'] ",$dynamic_processing_profile['profile_name']);
	    
	
	    $account_gateway_startdate = "master_config_gateway_". $dynamic_processing_profile['profile_name'] ."_startdate";
	    
	    logger3("account_gateway_startdate",$account_gateway_startdate);
	    
	    logger3("$ account_gateway_startdate",$$account_gateway_startdate);
	    
	    $forget_about_old_chargebacks_for_businesses_moving_forward = "AND requested_datetime > '". $$account_gateway_startdate ."'";
	
	} else {
	    
	    $forget_about_old_chargebacks_for_businesses_moving_forward = "";
	}
	
	

	
	
	/// make the PMD exception for new/old clients:
	    	//logger3("most_recent_transaction_datetime",$most_recent_transaction_datetime);
	
	if(empty($start_date)) $start_date = $most_recent_transaction_datetime;
	//test("1start_date",$start_date);
	
	if(!empty($start_date)) {
		
		
		$limit_date = date("Y-m-d H:i:s",strtotime($start_date . " -$limit_days_ago days"));
		//test("1limit_date",$limit_date);
	}
	
	if(empty($start_date)) $start_date = date("Y-m-d H:i:s",time());
	//test("2start_date",$start_date);
	
	if(empty($limit_date)) $limit_date = date("Y-m-d H:i:s",strtotime("-$limit_days_ago days"));
	//test("2limit_date",$limit_date);
	
	//logger3("limit_date",$limit_date);
	### $datetime_limit_days = strtotime("-". $limit_days ." days");
	### logger3("datetime_limit_days",$datetime_limit_days);
	### $datetime_limit_days = date("Y-m-d H:i:s",$datetime_limit_days);
	### logger3("datetime_limit_days",$datetime_limit_days);
	### 
	### 
	### ### SET INCOMING:
	### if(empty($start_date)) $start_date = date("Y-m-d H:i:s",time());
	
	
	//exit;
	
	
	
	## GRACE PERIOD:
	$grace_days = "0";
	$datetime_grace = strtotime("-". $grace_days ." days");
	//logger3("datetime_limit_days",$datetime_limit_days);
	$datetime_grace = date("Y-m-d H:i:s",$datetime_grace);
	//logger3("datetime_limit_days",$datetime_limit_days);


	
	// clear previous loop vars:
	$VOLUME_discount_added = "";
	//logger3("accountid",$accountid);
	$accountid = $business_accountid;

	### TRANSACTION SUM
	// $tmp_sql = "SELECT SUM(transaction_gross_value) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT SUM(transaction_gross_value) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	logger3("tmp_sql",$tmp_sql);
	
	$total_volume_for_business = getTHECASHIER($tmp_sql);
	logger3("total_volume_for_business",$total_volume_for_business);
	
	### TRANSACTION COUNT
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	logger3("tmp_sql",$tmp_sql);
	
	$total_transactions_for_business = getTHECASHIER($tmp_sql);
	logger3("total_transactions_for_business",$total_transactions_for_business);

	    
	### CHARGEBACKS FOR BUSINESS:
	### $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	### WHERE accountid = '". $accountid ."'
	### AND description = 'INCOMING' 
	### AND (status='CHARGEBACK' OR return_reason LIKE '%CHARGEBACK%')
	### AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	### AND requested_datetime >= '". $datetime_limit_days ."'
	### ;";
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND (status = 'CHARGEBACK' OR return_reason LIKE '%BANK-ISSUED CHARGEBACK%')
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status = 'CHARGEBACK' OR return_reason LIKE '%BANK-ISSUED CHARGEBACK%')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	//test("tmp_sql",$tmp_sql);
	$total_CHARGEBACK_for_business = getTHECASHIER($tmp_sql);
	//test("total_CHARGEBACK_for_business",$total_CHARGEBACK_for_business);
	//$total_CHARGEBACK_for_business = $total_CHARGEBACK_for_business + 0;
	
	### REFUNDED FOR BUSINESS:
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND status='REFUNDED'
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND status='REFUNDED'
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	//logger3("tmp_sql",$tmp_sql);
	$total_REFUNDED_for_business = getTHECASHIER($tmp_sql);
	
	
	### REVERSED FOR BUSINESS:
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE platform = 'BANGK.com'
	// AND accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND (status = 'REVERSED' AND return_reason NOT LIKE '%BANK-ISSUED CHARGEBACK%')
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE platform = 'BANGK.com'
	AND accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status = 'REVERSED' AND return_reason NOT LIKE '%BANK-ISSUED CHARGEBACK%')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	//logger3("tmp_sql",$tmp_sql);
	$total_REVERSED_for_business = getTHECASHIER($tmp_sql);
	//logger3("total_REVERSED_for_business",$total_REVERSED_for_business);


	### CANCELED FOR BUSINESS:
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE platform = 'BANGK.com'
	// AND accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND (status LIKE 'CANCELED')
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE platform = 'BANGK.com'
	AND accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status LIKE 'CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	//logger3("tmp_sql",$tmp_sql);
	$total_CANCELED_for_business = getTHECASHIER($tmp_sql);
	//logger3("$accountid total_CANCELED_for_business",$total_CANCELED_for_business);

	
	    
	// ### CANCELED FOR BUSINESS:
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND status='CANCELED'
	// AND return_reason NOT LIKE '%CHARGEBACK%'
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND requested_datetime >= '". $datetime_limit_days ."'
	// ;";
	// //logger3("tmp_sql",$tmp_sql);
	// $total_CANCELED_for_business = getTHECASHIER($tmp_sql);
	
	
	
	$total_everthing = $total_CANCELED_for_business + $total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CHARGEBACK_for_business;
	
	if(stristr($display_logging,"YES")) echo "total everything: $total_everthing vs. total transactions: $total_transactions_for_business = ". number_format($total_everthing/$total_transactions_for_business*100) ."%";
	
	if(stristr($display_logging,"YES")) {
	    $tmp_account_details = account($accountid);
	} else {
	    $tmp_account_details['accountname'] = getTHECASHIER("SELECT accountname FROM accounts WHERE accountid = '". $accountid ."';");
	}
	    	
	    	
	    	//$display_logging = "YES";
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "<hr>";
	if(stristr($display_logging,"YES")) echo "<b>BUSINESS NAME</b>: ". "<u><b>".$tmp_account_details['accountname']."</b></u> (". $tmp_account_details['accountid'] .")";
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "TOTAL TRANSACTIONS: ". $total_transactions_for_business;
	if(stristr($display_logging,"YES")) echo "<br>";
	$percentage_of_network_volume = $total_transactions_for_business / $total_transactions_for_network;
	$percentage_of_network_volume_ii = number_format(100*$percentage_of_network_volume,1);
	if(stristr($display_logging,"YES")) echo "% of B! TRANSACTIONS: <b>". $percentage_of_network_volume_ii."%</b>";
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# CHARGEBACK: ". number_format($total_CHARGEBACK_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# REFUNDED: ". number_format($total_REFUNDED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# REVERSED: ". number_format($total_REVERSED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# CANCELED: ". number_format($total_CANCELED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	
	
	## CB%
	$pCHAREBACK = $total_CHARGEBACK_for_business / $total_transactions_for_business;
	$pCHAREBACK_ii = number_format(100*$total_CHARGEBACK_for_business / $total_transactions_for_business,1);
	
	$chargeback_color = "#009900";
	if($pCHAREBACK_ii > "3.0") $chargeback_color = "#CC0000";
	
	if(stristr($display_logging,"YES")) echo "<span style='color:". $chargeback_color. ";'><b><u>CHARGEBACK RATE</u>: ". $pCHAREBACK_ii."% </b></span>";
	if(stristr($display_logging,"YES")) echo "<br>";
	## RF%
	$pREFUNDED = ($total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CANCELED_for_business) / $total_transactions_for_business;
	$pREFUNDED_ii = number_format(100*($total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CANCELED_for_business) / $total_transactions_for_business,1);
	
	$refund_color = "#009900";
	if($pREFUNDED_ii > "3.0") $refund_color = "#CC0000";
	
	if(stristr($display_logging,"YES")) echo "<span style='color:". $refund_color . ";'><b><u>REFUND RATE</u>: ". $pREFUNDED_ii."% </b></span>";
	if(stristr($display_logging,"YES")) echo "<br>";
	
	
	### APPLY DISCOUNTS:
	$final_REVERSED_for_business = $total_REVERSED_for_business;
	$final_CANCELED_for_business = $total_CANCELED_for_business;
	$final_REFUNDED_for_business = $total_REFUNDED_for_business;
	$final_CHARGEBACK_for_business = $total_CHARGEBACK_for_business;
	# this merges customer cancels and administrative reversals into 1.
	# $final_REVERSED_for_business = $final_REVERSED_for_business + $final_CANCELED_for_business;
	
	### VOLUME_multiplier
	// if($total_transactions_for_business <= "30") {
	// 	logger3("1A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	// 	$VOLUME_multiplier = 1.30;
	// 	$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_multiplier;
	// 	$final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_multiplier;
	// 	$final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_multiplier;
	// 	logger3("1B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	// }
	
	### VOLUME_discount
	// LESS TO MORE:
	
	//test("total_transactions_for_business",$total_transactions_for_business);

	if($total_transactions_for_business <= "2") {
	    $VOLUME_discount_added = "YES";
	    //test("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.10;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount; // make mot effect cancels
	    //test("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
	} else if($total_transactions_for_business <= "4") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.20;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    
	} else if($total_transactions_for_business <= "6") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.30;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount0;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    
	} else if($total_transactions_for_business <= "8") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.40;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
	} else if($total_transactions_for_business <= "10") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.50;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	   
	         
	} else if($total_transactions_for_business <= "12") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.60;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
	} else if($total_transactions_for_business <= "15") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.70;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
      
	} else if($total_transactions_for_business <= "30") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.80;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
	} else if($total_transactions_for_business <= "60") {
	    $VOLUME_discount_added = "YES";
	    //test("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.90;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
	
	
	
	} else if($total_transactions_for_business < "100") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 1.0;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	}
	
	
	

	
	
	//$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_discount;
	
	### CHARGEBACK_discount
	//logger3("total_CHARGEBACK_for_business",$total_CHARGEBACK_for_business);
	$raw_chargeback_rate = $final_CHARGEBACK_for_business / $total_transactions_for_business;
	$chargeback_threshhold = "0.05";
	
	if($raw_chargeback_rate <= $chargeback_threshhold) {
	    $CHARGEBACK_discount = 0.66;
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $CHARGEBACK_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	}
	
	
	### CHARGEBACK_multiplier
	//logger3("raw_chargeback_rate",$raw_chargeback_rate);
	//logger3("VOLUME_discount_added",$VOLUME_discount_added);
	if(
	(empty($VOLUME_discount_added)) &&
	($raw_chargeback_rate > $chargeback_threshhold)
	) {
	
	    //logger3("3A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $CHARGEBACK_multiplier = 5;
	    
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_multiplier;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_multiplier;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_multiplier;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $CHARGEBACK_multiplier;
	    //logger3("3B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	}
	
	// ### 60 DAY GRACE
	// if(strtotime($tmp_account_details['created']) < strtotime($datetime_grace)) {
	// 	$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_multiplier;
	// 	$final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_multiplier;
	// 	$final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_multiplier;
	// 	
	// }
	
	// test("9. $accountid final_CANCELED_for_business",$final_CANCELED_for_business);
	// test("9. $accountid final_REVERSED_for_business",$final_REVERSED_for_business);
	// test("9. $accountid final_REFUNDED_for_business",$final_REFUNDED_for_business);
	// test("9. $accountid final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	// test("9. $accountid total_transactions_for_business",$total_transactions_for_business);
	
	# $SUB_final_merchant_rating = ($final_CANCELED_for_business + $final_REVERSED_for_business + $final_REFUNDED_for_business + $final_CHARGEBACK_for_business) / $total_transactions_for_business;
	# logger3("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	
	### 2014.05: removed "refunded" -- company policy to NOT have refunds effect the rating in any way.
	$SUB_final_merchant_rating = ($final_CANCELED_for_business + $final_REVERSED_for_business + $final_CHARGEBACK_for_business) / $total_transactions_for_business;
	# test("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	
	
	
	### CHECK REFUND RATE:
	### $SUB_true_refund_rate = ($total_CANCELED_for_business + $total_REVERSED_for_business) / $total_transactions_for_business;
	### //logger3("888. SUB_true_refund_rate",$SUB_true_refund_rate);
	### 
	### $SUB_true_refund_rating = number_format(100*(1 - $SUB_true_refund_rate),1);
	### //logger3("888. SUB_true_refund_rating",$SUB_true_refund_rating);
	### $SUB_true_refund_fee = get_dynamic_fee($SUB_true_refund_rating/100);
	### //logger3("888. SUB_true_refund_fee",$SUB_true_refund_fee);
	### 
	### $SUB_final_refund_rate = ($final_CANCELED_for_business + $final_REVERSED_for_business) / $total_transactions_for_business;
	### //logger3("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	### 
	### $SUB_final_refund_rating = number_format(100*(1 - $SUB_final_refund_rate),1);
	### //logger3("888. SUB_final_refund_rating",$SUB_final_refund_rating);
	### $SUB_final_refund_fee = get_dynamic_fee($SUB_final_refund_rating/100);
	### //logger3("888. SUB_finale_refund_fee",$SUB_final_refund_fee);
	

	$final_merchant_rating = number_format(100*(1 - $SUB_final_merchant_rating),1);
	
	//logger3("999. final_merchant_rating",$final_merchant_rating);
	
	$rating_color = "#CC0000";
	if($final_merchant_rating >= "90.00") $rating_color = "#009900";
	//echo "<span style='color:". $rating_color . ";'><b>B! MERCHANT RATING: ". $final_merchant_rating . "% </b></span>";
	//echo "<br>";
	
	$results['merchant_accountid'] = $accountid;
	$results['merchant_name'] = $tmp_account_details['accountname'];
	$results['decimal'] = 1 - number_format($SUB_final_merchant_rating,6);
	$results['percentage'] = $results['satisfied'] = $final_merchant_rating;
	$results['refunded'] = number_format(100 - $final_merchant_rating,1);
	//$results['refund_percentage'] = number_format(100 - $final_merchant_rating,1);
	$results['volume'] = $total_volume_for_business;
	
	$results['total_transactions_count'] = $total_transactions_for_business;
	$results['total_chargebacks_count'] = $total_CHARGEBACK_for_business;
	
	//logger3("ZZZ. accountid $accountid results",$results);
	return $results;
		
}

function get_merchant_rating_2($business_accountid,$start_date='',$limit_date='',$display_logging='') {
	$accountid = $business_accountid;
	$version = "2";
	$personal_or_business = getTHECASHIER("SELECT accounttype WHERE accountid = '". $accountid ."';");
	if(stristr($personal_or_business,"PERSONAL")) return FALSE;

	//logger3("get_merchant_rating(business_accountid=$business_accountid): ",$x);
		

	if(empty($display_logging)) $display_logging = ""; // for algorithm testing
	if(empty($limit_days_ago)) $limit_days_ago = "30";

	### get most recent transaction to establish startdate
	$tmp_sql = "SELECT updated_datetime FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	ORDER BY updated_datetime DESC
	LIMIT 1";
	//logger3("tmp_sql",$tmp_sql);
	$most_recent_transaction_datetime = getTHECASHIER($tmp_sql);
	
	$account_details = object2array(readTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';"));
	
	
	//logger3("dynamic_processing_profile($accountid)",$dynamic_processing_profile);
	
	### if(stristr($dynamic_processing_profile['profile_name'],"PMD")) {
	### 
	### 	global $master_config_gateway_PMD_startdate;
	### 	//logger3("master_config_gateway_PMD_startdate",$master_config_gateway_PMD_startdate);
	### 	
	### 	if($most_recent_transaction_datetime > $master_config_gateway_PMD_startdate) {
	### 		$forget_about_old_chargebacks_for_businesses_moving_forward = "AND requested_datetime > '". $master_config_gateway_PMD_startdate ."'";
	### 	}
	### 
	### } else {
	### 	
	### 	$forget_about_old_chargebacks_for_businesses_moving_forward = "";
	### 
	### }
	
	//logger3("$accountid: forget_about_old_chargebacks_for_businesses_moving_forward",$forget_about_old_chargebacks_for_businesses_moving_forward);
	
	$account_details = object2array(readTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';"));
	
	logger3("account_details['status_payments']",$account_details['status_payments']);
	
	if(stristr($account_details['status_payments'],"ON")) {
	    //global $master_config_gateway_ECP_startdate
	    global $master_config_gateway_ECP_startdate;
	    global $master_config_gateway_PMD_startdate;

	    $dynamic_processing_profile = get_dynamic_processing_profile($accountid);
	    
	    logger3("dynamic_processing_profile['profile_name'] ",$dynamic_processing_profile['profile_name']);
	    
	
	    $account_gateway_startdate = "master_config_gateway_". $dynamic_processing_profile['profile_name'] ."_startdate";
	    
	    logger3("account_gateway_startdate",$account_gateway_startdate);
	    
	    logger3("$ account_gateway_startdate",$$account_gateway_startdate);
	    
	    $forget_about_old_chargebacks_for_businesses_moving_forward = "AND requested_datetime > '". $$account_gateway_startdate ."'";
	
	} else {
	    
	    $forget_about_old_chargebacks_for_businesses_moving_forward = "";
	}
	
	

	
	
	/// make the PMD exception for new/old clients:
	    	//logger3("most_recent_transaction_datetime",$most_recent_transaction_datetime);
	
	if(empty($start_date)) $start_date = $most_recent_transaction_datetime;
	if(empty($start_date)) $start_date = date("Y-m-d H:i:s",time());
	//logger3("start_date",$start_date);
	if(empty($limit_date)) $limit_date = date("Y-m-d H:i:s",strtotime("-$limit_days_ago days"));
	//logger3("limit_date",$limit_date);
	### $datetime_limit_days = strtotime("-". $limit_days ." days");
	### logger3("datetime_limit_days",$datetime_limit_days);
	### $datetime_limit_days = date("Y-m-d H:i:s",$datetime_limit_days);
	### logger3("datetime_limit_days",$datetime_limit_days);
	### 
	### 
	### ### SET INCOMING:
	### if(empty($start_date)) $start_date = date("Y-m-d H:i:s",time());
	
	
	//exit;
	
	
	
	## GRACE PERIOD:
	$grace_days = "0";
	$datetime_grace = strtotime("-". $grace_days ." days");
	//logger3("datetime_limit_days",$datetime_limit_days);
	$datetime_grace = date("Y-m-d H:i:s",$datetime_grace);
	//logger3("datetime_limit_days",$datetime_limit_days);


	
	// clear previous loop vars:
	$VOLUME_discount_added = "";
	//logger3("accountid",$accountid);
	$accountid = $business_accountid;

	### TRANSACTION SUM
	$tmp_sql = "SELECT SUM(transaction_gross_value) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	logger3("tmp_sql",$tmp_sql);
	
	$total_volume_for_business = getTHECASHIER($tmp_sql);
	logger3("total_volume_for_business",$total_volume_for_business);
	
	### TRANSACTION COUNT
	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	logger3("tmp_sql",$tmp_sql);
	
	$total_transactions_for_business = getTHECASHIER($tmp_sql);
	logger3("total_transactions_for_business",$total_transactions_for_business);

	    
	### CHARGEBACKS FOR BUSINESS:
	### $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	### WHERE accountid = '". $accountid ."'
	### AND description = 'INCOMING' 
	### AND (status='CHARGEBACK' OR return_reason LIKE '%CHARGEBACK%')
	### AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	### AND requested_datetime >= '". $datetime_limit_days ."'
	### ;";
	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='CHARGEBACK')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	//logger3("tmp_sql",$tmp_sql);
	$total_CHARGEBACK_for_business = getTHECASHIER($tmp_sql);
	//logger3("total_CHARGEBACK_for_business",$total_CHARGEBACK_for_business);
	//$total_CHARGEBACK_for_business = $total_CHARGEBACK_for_business + 0;
	
	### REFUNDED FOR BUSINESS:
	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND status='REFUNDED'
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	//logger3("tmp_sql",$tmp_sql);
	$total_REFUNDED_for_business = getTHECASHIER($tmp_sql);
	
	
	### REVERSED FOR BUSINESS:
	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE platform = 'BANGK.com'
	AND accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status LIKE 'REVERSED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	//logger3("tmp_sql",$tmp_sql);
	$total_REVERSED_for_business = getTHECASHIER($tmp_sql);
	//logger3("total_REVERSED_for_business",$total_REVERSED_for_business);


	### CANCELED FOR BUSINESS:
	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE platform = 'BANGK.com'
	AND accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status LIKE 'CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	//logger3("tmp_sql",$tmp_sql);
	$total_CANCELED_for_business = getTHECASHIER($tmp_sql);
	//logger3("$accountid total_CANCELED_for_business",$total_CANCELED_for_business);

	
	    
	// ### CANCELED FOR BUSINESS:
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND status='CANCELED'
	// AND return_reason NOT LIKE '%CHARGEBACK%'
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND requested_datetime >= '". $datetime_limit_days ."'
	// ;";
	// //logger3("tmp_sql",$tmp_sql);
	// $total_CANCELED_for_business = getTHECASHIER($tmp_sql);
	
	
	
	$total_everthing = $total_CANCELED_for_business + $total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CHARGEBACK_for_business;
	
	if(stristr($display_logging,"YES")) echo "total everything: $total_everthing vs. total transactions: $total_transactions_for_business = ". number_format($total_everthing/$total_transactions_for_business*100) ."%";
	
	if(stristr($display_logging,"YES")) {
	    $tmp_account_details = account($accountid);
	} else {
	    $tmp_account_details['accountname'] = getTHECASHIER("SELECT accountname FROM accounts WHERE accountid = '". $accountid ."';");
	}
	    	
	    	
	    	
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "<hr>";
	if(stristr($display_logging,"YES")) echo "<b>BUSINESS NAME</b>: ". "<u><b>".$tmp_account_details['accountname']."</b></u> (". $tmp_account_details['accountid'] .")";
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "TOTAL TRANSACTIONS: ". $total_transactions_for_business;
	if(stristr($display_logging,"YES")) echo "<br>";
	$percentage_of_network_volume = $total_transactions_for_business / $total_transactions_for_network;
	$percentage_of_network_volume_ii = number_format(100*$percentage_of_network_volume,1);
	if(stristr($display_logging,"YES")) echo "% of B! TRANSACTIONS: <b>". $percentage_of_network_volume_ii."%</b>";
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# CHARGEBACK: ". number_format($total_CHARGEBACK_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# REFUNDED: ". number_format($total_REFUNDED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# REVERSED: ". number_format($total_REVERSED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# CANCELED: ". number_format($total_CANCELED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	
	
	## CB%
	$pCHAREBACK = $total_CHARGEBACK_for_business / $total_transactions_for_business;
	$pCHAREBACK_ii = number_format(100*$total_CHARGEBACK_for_business / $total_transactions_for_business,1);
	
	$chargeback_color = "#009900";
	if($pCHAREBACK_ii > "3.0") $chargeback_color = "#CC0000";
	
	if(stristr($display_logging,"YES")) echo "<span style='color:". $chargeback_color. ";'><b><u>CHARGEBACK RATE</u>: ". $pCHAREBACK_ii."% </b></span>";
	if(stristr($display_logging,"YES")) echo "<br>";
	## RF%
	$pREFUNDED = ($total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CANCELED_for_business) / $total_transactions_for_business;
	$pREFUNDED_ii = number_format(100*($total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CANCELED_for_business) / $total_transactions_for_business,1);
	
	$refund_color = "#009900";
	if($pREFUNDED_ii > "3.0") $refund_color = "#CC0000";
	
	if(stristr($display_logging,"YES")) echo "<span style='color:". $refund_color . ";'><b><u>REFUND RATE</u>: ". $pREFUNDED_ii."% </b></span>";
	if(stristr($display_logging,"YES")) echo "<br>";
	
	
	### APPLY DISCOUNTS:
	$final_REVERSED_for_business = $total_REVERSED_for_business;
	$final_CANCELED_for_business = $total_CANCELED_for_business;
	$final_REFUNDED_for_business = $total_REFUNDED_for_business;
	$final_CHARGEBACK_for_business = $total_CHARGEBACK_for_business;
	# this merges customer cancels and administrative reversals into 1.
	# $final_REVERSED_for_business = $final_REVERSED_for_business + $final_CANCELED_for_business;
	
	### VOLUME_multiplier
	// if($total_transactions_for_business <= "30") {
	// 	logger3("1A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	// 	$VOLUME_multiplier = 1.30;
	// 	$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_multiplier;
	// 	$final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_multiplier;
	// 	$final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_multiplier;
	// 	logger3("1B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	// }
	
	### VOLUME_discount
	// LESS TO MORE:
	
	//test("total_transactions_for_business",$total_transactions_for_business);

	### if($total_transactions_for_business <= "2") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.15;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount; // make mot effect cancels
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
	### } else if($total_transactions_for_business <= "4") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.25;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.25;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.25;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     
	### } else if($total_transactions_for_business <= "6") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.25;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.25;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.25;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     
	### } else if($total_transactions_for_business <= "8") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.25;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.35;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.35;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
	### } else if($total_transactions_for_business <= "10") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.25;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.45;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.45;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###    
	###          
	### } else if($total_transactions_for_business <= "12") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.50;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.55;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.55;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
	### } else if($total_transactions_for_business <= "15") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.50;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.65;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.65;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
    ###   
	### } else if($total_transactions_for_business <= "30") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.50;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.75;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.75;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
	### } else if($total_transactions_for_business <= "60") {
	###     $VOLUME_discount_added = "YES";
	###     //test("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.50;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.90;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.90;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
	### 
	### 
	### 
	### } else if($total_transactions_for_business < "100") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.80;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 1.0;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 1.0;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### }
	
	
	

	
	
	//$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_discount;
	
	### ### CHARGEBACK_discount
	### //logger3("total_CHARGEBACK_for_business",$total_CHARGEBACK_for_business);
	### $raw_chargeback_rate = $final_CHARGEBACK_for_business / $total_transactions_for_business;
	### $chargeback_threshhold = "0.05";
	### 
	### if($raw_chargeback_rate <= $chargeback_threshhold) {
	###     $CHARGEBACK_discount = 0.66;
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_discount;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * $CHARGEBACK_discount;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### }
	
	
	### ### CHARGEBACK_multiplier
	### //logger3("raw_chargeback_rate",$raw_chargeback_rate);
	### //logger3("VOLUME_discount_added",$VOLUME_discount_added);
	### if(
	### (empty($VOLUME_discount_added)) &&
	### ($raw_chargeback_rate > $chargeback_threshhold)
	### ) {
	### 
	###     //logger3("3A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $CHARGEBACK_multiplier = 5;
	###     
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_multiplier;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_multiplier;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_multiplier;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * $CHARGEBACK_multiplier;
	###     //logger3("3B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### }
	
	// ### 60 DAY GRACE
	// if(strtotime($tmp_account_details['created']) < strtotime($datetime_grace)) {
	// 	$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_multiplier;
	// 	$final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_multiplier;
	// 	$final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_multiplier;
	// 	
	// }
	
	logger3("9. $accountid final_CANCELED_for_business",$final_CANCELED_for_business);
	logger3("9. $accountid final_REVERSED_for_business",$final_REVERSED_for_business);
	logger3("9. $accountid final_REFUNDED_for_business",$final_REFUNDED_for_business);
	logger3("9. $accountid final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	logger3("9. $accountid total_transactions_for_business",$total_transactions_for_business);
	
	# $SUB_final_merchant_rating = ($final_CANCELED_for_business + $final_REVERSED_for_business + $final_REFUNDED_for_business + $final_CHARGEBACK_for_business) / $total_transactions_for_business;
	# logger3("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	
	### 2014.05: removed "refunded" -- company policy to NOT have refunds effect the rating in any way.
	$SUB_final_merchant_rating = ($final_CANCELED_for_business + $final_REVERSED_for_business + $final_CHARGEBACK_for_business) / $total_transactions_for_business;
	logger3("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	
	
	
	### CHECK REFUND RATE:
	### $SUB_true_refund_rate = ($total_CANCELED_for_business + $total_REVERSED_for_business) / $total_transactions_for_business;
	### //logger3("888. SUB_true_refund_rate",$SUB_true_refund_rate);
	### 
	### $SUB_true_refund_rating = number_format(100*(1 - $SUB_true_refund_rate),1);
	### //logger3("888. SUB_true_refund_rating",$SUB_true_refund_rating);
	### $SUB_true_refund_fee = get_dynamic_fee($SUB_true_refund_rating/100);
	### //logger3("888. SUB_true_refund_fee",$SUB_true_refund_fee);
	### 
	### $SUB_final_refund_rate = ($final_CANCELED_for_business + $final_REVERSED_for_business) / $total_transactions_for_business;
	### //logger3("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	### 
	### $SUB_final_refund_rating = number_format(100*(1 - $SUB_final_refund_rate),1);
	### //logger3("888. SUB_final_refund_rating",$SUB_final_refund_rating);
	### $SUB_final_refund_fee = get_dynamic_fee($SUB_final_refund_rating/100);
	### //logger3("888. SUB_finale_refund_fee",$SUB_final_refund_fee);
	

	$final_merchant_rating = number_format(100*(1 - $SUB_final_merchant_rating),1);
	
	//logger3("999. final_merchant_rating",$final_merchant_rating);
	
	$rating_color = "#CC0000";
	if($final_merchant_rating >= "90.00") $rating_color = "#009900";
	//echo "<span style='color:". $rating_color . ";'><b>B! MERCHANT RATING: ". $final_merchant_rating . "% </b></span>";
	//echo "<br>";
	
	$results['merchant_accountid'] = $accountid;
	$results['merchant_name'] = $tmp_account_details['accountname'];
	$results['decimal'] = 1 - number_format($SUB_final_merchant_rating,6);
	$results['percentage'] = $results['satisfied'] = $final_merchant_rating;
	$results['refunded'] = number_format(100 - $final_merchant_rating,1);
	//$results['refund_percentage'] = number_format(100 - $final_merchant_rating,1);
	$results['volume'] = $total_volume_for_business;
	
	$results['total_transactions_count'] = $total_transactions_for_business;
	$results['total_chargebacks_count'] = $total_CHARGEBACK_for_business;
	
	//logger3("ZZZ. accountid $accountid results",$results);
	return $results;
		
}



function format_phone_number($phone_number) {

	if(empty($phone_number)) return FALSE;
	
	$tmp_return = explode("/",$phone_number);
	
	logger3("format_phone_number(): tmp_return",$tmp_return);
	
	if(empty($tmp_return[1])) {
		$return['calling_code'] = "";
		$return['local_number'] = $phone_number;	
	} else {
		
		$return['calling_code'] = $tmp_return[0];
		$return['local_number'] = $tmp_return[1];
	}
	
	logger3("format_phone_number(): return",$return);
	
	$split_local_number = str_split($return['local_number']);
	
	if($split_local_number[0] == "0") {
		$return['local_number'] = substr($return['local_number'],1);
	
	} else if(
		($split_local_number[0] == "1") 
		&& 
		(
			(!$return['calling_code'])
			|| ($return['calling_code'] == "1")
		)
	) {
	
		$return['calling_code'] = "1";
		$return['local_number'] = substr($return['local_number'],1);
		
	} else {
		$return['local_number'] = $tmp_return[1];
	}
	
	$return[0] = $return['calling_code'];
	$return[1] = $return['local_number'];
	$return[2] = $return['phone_number'] = "+". $return['calling_code'] . $return['local_number'];

	
	return $return;
}

function luhn_check($number) {

  // Strip any non-digits (useful for credit card numbers with spaces and hyphens)
  $number=preg_replace('/\D/', '', $number);

  // Set the string length and parity
  $number_length=strlen($number);
  $parity=$number_length % 2;

  // Loop through each digit and do the maths
  $total=0;
  for ($i=0; $i<$number_length; $i++) {
    $digit=$number[$i];
    // Multiply alternate digits by two
    if ($i % 2 == $parity) {
      $digit*=2;
      // If the sum is two digits, add them together (in effect)
      if ($digit > 9) {
        $digit-=9;
      }
    }
    // Total up the digits
    $total+=$digit;
  }

  // If the total mod 10 equals 0, the number is valid
  return ($total % 10 == 0) ? TRUE : FALSE;

}


function get_business_type_extensions() {
	
	$results = "";
	$results = array();
	$tmp_sql = "SELECT extensionid FROM business_type_extensions;";
	$extensionid_array = arrayTHECASHIER($tmp_sql);
	//test("extensionid_array",$extensionid_array);
	
	foreach($extensionid_array as $key => $extensionid) {
		$tmp_sql = "SELECT * FROM business_type_extensions WHERE extensionid = '".$extensionid."';";
		$results[$key] = object2array(readTHECASHIER($tmp_sql));
	}
	return $results;
}




function getPendingIdentityClaims($accountid=null) {

	if(!empty($accountid)) $possible_accountid_specification = "AND accountid = '". $accountid ."';";

	### RESET COUNTER PER FUNCTION:
	$results = "";
	$results['pending_counter'] = "";
	$x = 0;
	$y = 0;



	########################################################
	### PERSONAL IDENTITY
	########################################################
	
	
	# $tmp_sql = "SELECT a.*
	# FROM ids_personal a
	# INNER JOIN
	# (
	# SELECT *, MAX(datetime_created) maxDateCreated
	# FROM ids_personal
	# WHERE 
	# (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
	# AND 
	# (proof_of_residence_filename = '' OR proof_of_residence_filename IS NULL)
	# AND
	# (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	# GROUP BY memberid
	# ) b ON 
	# a.memberid = b.memberid AND
    # a.datetime_created = b.maxDateCreated
	# ;
	# ";
	# logger3("tmp_sql",$tmp_sql);
	
	// $tmp_sql = "SELECT * FROM ids_personal
	// 			WHERE (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
	// 			AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
	// 			ORDER BY datetime_updated ASC
	// 			;";
	


	$tmp_sql = "SELECT * FROM (
				SELECT * FROM ids_personal
				WHERE (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
				AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
				ORDER BY datetime_updated DESC
				) AS t
				GROUP BY t.memberid
				ORDER BY datetime_updated ASC";
	//test("tmp_sql",$tmp_sql);
	
	
	
	$results['pending_personal_identity'] = object2array(readarrayTHECASHIER($tmp_sql));
	//test("results['pending_personal_identity']",$results['pending_personal_identity']);
	//exit;
	
	$results['pending_counter'] = $results['pending_counter'] + count(array_keys($results['pending_personal_identity']));
	
	//$x = 0;
	foreach($results['pending_personal_identity'] as $key => $id) {
		$results['array'][$y] = $results['pending_personal_identity'][$key];
		if(!empty($results['array'][$y])) $y++;
		
	}
	
	
	
	########################################################
	### PERSONAL LOCATION
	########################################################
	
	
	# $tmp_sql = "SELECT a.*
	# FROM ids_personal a
	# INNER JOIN
	# (
	# SELECT *, MAX(datetime_created) maxDateCreated
	# FROM ids_personal
	# WHERE 
	# (photo_id_filename = '' OR photo_id_filename IS NULL)
	# AND 
	# (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
	# AND
	# (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	# GROUP BY memberid
	# ) b ON 
	# a.memberid = b.memberid AND
    # a.datetime_created = b.maxDateCreated
	# ;
	# ";

	// $tmp_sql = "SELECT * FROM ids_personal
	// 			WHERE (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
	// 			AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
	// 			ORDER BY datetime_updated ASC
	// 			;";
	

	
	$tmp_sql = "SELECT * FROM (
				SELECT * FROM ids_personal
				WHERE (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
				AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
				ORDER BY datetime_updated DESC
				) AS t
				GROUP BY t.memberid
				ORDER BY datetime_updated ASC";
				
	//test("tmp_sql",$tmp_sql);
	
	$results['pending_personal_location'] = object2array(readarrayTHECASHIER($tmp_sql));
	//test("results['pending_personal_location']",$results['pending_personal_location']);
	
	$results['pending_counter'] = $results['pending_counter'] + count(array_keys($results['pending_personal_location']));

	//$x = 0;
	foreach($results['pending_personal_location'] as $key => $id) {
		$results['array'][$y] = $results['pending_personal_location'][$key];
		if(!empty($results['array'][$y])) $y++;
	}
	
	
	########################################################
	### BUSINESS IDENTITY
	########################################################
	# $tmp_sql = "SELECT a.*
	# FROM ids_business a
	# INNER JOIN
	# (
	# SELECT *, MAX(datetime_created) maxDateCreated
	# FROM ids_business
	# WHERE 
	# 
	# (
	# (
	# (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
	# AND 
	# (proof_of_business_location_filename = '' OR proof_of_business_location_filename IS NULL)
	# )
	# OR business_legal_extension = 'PDB'
	# )
	# AND
	# (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	# GROUP BY memberid
	# ) b ON 
	# a.memberid = b.memberid AND
    # a.datetime_created = b.maxDateCreated
	# ;
	# ";
	//test("tmp_sql",$tmp_sql);

	// $tmp_sql = "SELECT * FROM ids_business
	// 			WHERE (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
	// 			AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
	// 			ORDER BY datetime_updated ASC
	// 			;";
	
	$tmp_sql = "SELECT * FROM (
				SELECT * FROM ids_business
				WHERE (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
				AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
				
				AND business_legal_extension NOT LIKE '%DBA'
				AND business_legal_extension != 'GROUP'
				
				ORDER BY datetime_updated DESC
				) AS t
				GROUP BY t.memberid
				ORDER BY datetime_updated ASC";
	
	//test("tmp_sql",$tmp_sql);
	
	
	$results['pending_business_identity'] = object2array(readarrayTHECASHIER($tmp_sql));
	
	$results['pending_counter'] = $results['pending_counter'] + count(array_keys($results['pending_business_identity']));
	
	
	//test("results['pending_business_identity']",$results['pending_business_identity']);
	
	## CHECK TO MAKE SURE PERSONAL IDS ARE VERIFIED BEFORE PDB's CAN BE COUNTED-IN
	# $x = 0;
	# $force_show = 1;
	# 
	# if(!empty($force_show)) {
	# 	$new_pending_business_identity_array = "";
	# 	foreach($results['pending_business_identity'] as $key => $business_id_details) {
	# 		
	# 		//test("business_id_details",$business_id_details);
	# 		
	# 		//$tmp_claim_details = object2array(readTHECASHIER("SELECT * FROM ids_business WHERE idid = '". $business_id_details['idid'] ."';"));
	# 		$member_owener_details = member($business_id_details['memberid']);
	# 		//test("member_owener_details['verified']",$member_owener_details['verified']);
	# 		
	# 		if(
	# 		(!empty($member_owener_details['verified']['identity']['hash'])) &&
	# 		(!empty($member_owener_details['verified']['location']['hash']))
	# 		) {
	# 		   //test("member_owener_details['verified']['location']['hash']",$member_owener_details['verified']['location']['hash']);
	# 		   
	# 		   $new_pending_business_identity_array[$x] = $tmp_claim_details;
	# 		   if(!empty($results['array'][$x])) $x++;
	# 		}
	# 		
	# 		//$new_pending_business_identity_array[$x] = $tmp_claim_details;
	# 		//if(!empty($results['array'][$x])) $x++;
	# 	}
	# 	
	# 	$results['pending_business_identity'] = "";
	# 	$results['pending_business_identity'] = $new_pending_business_identity_array;
	# }
	# 
	# $results['pending_counter'] = $results['pending_counter'] + count($results['pending_business_identity']);
	# 
	# //test("results['pending_business_identity']",$results['pending_business_identity']);
	
	
	
	
	
	foreach($results['pending_business_identity'] as $key => $id) {
		$results['array'][$y] = $results['pending_business_identity'][$key];
		if(!empty($results['array'][$y])) $y++;
	}
	
	
	########################################################
	### BUSINESS LOCATION
	########################################################
	# $tmp_sql = "SELECT a.*
	# FROM ids_business a
	# INNER JOIN
	# (
	# SELECT *, MAX(datetime_created) maxDateCreated
	# FROM ids_business
	# WHERE 
	# (business_certificate_filename = '' OR business_certificate_filename IS NULL)
	# AND 
	# (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
	# AND
	# (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	# GROUP BY memberid
	# ) b ON 
	# a.memberid = b.memberid AND
    # a.datetime_created = b.maxDateCreated
	# ;
	# ";
	
	
	// $tmp_sql = "SELECT * FROM ids_business
	// 			WHERE (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
	// 			AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
	// 			AND (business_legal_extension NOT LIKE '%DBA%' AND business_legal_extension != 'GROUP') 
	// 			ORDER BY datetime_updated ASC
	// 			;";

	// $tmp_sql = "SELECT * FROM (
	// 			SELECT * FROM ids_business
	// 			WHERE (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
	// 			AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
	// 
	// 			AND business_legal_extension NOT LIKE '%DBA'
	// 			AND business_legal_extension != 'GROUP'
	// 			
	// 			ORDER BY datetime_updated DESC
	// 			) AS t
	// 			GROUP BY t.memberid
	// 			ORDER BY datetime_updated ASC";
$tmp_sql = "SELECT * FROM (
				SELECT * FROM ids_business
				WHERE (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
				AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
				
				AND business_legal_extension != 'PDB'
				AND business_legal_extension != 'CDBA'
				AND business_legal_extension != 'GROUP'
				
				ORDER BY datetime_updated DESC
				) AS t
				GROUP BY t.memberid
				ORDER BY datetime_updated ASC";
				
	//test("tmp_sql",$tmp_sql);
	
	$results['pending_business_location'] = object2array(readarrayTHECASHIER($tmp_sql));
	
	//test("results['pending_business_location']",$results['pending_business_location']);
	
	//if(empty($force_show)) {
	$results['pending_counter'] = $results['pending_counter'] + count(array_keys($results['pending_business_location']));



	foreach($results['pending_business_location'] as $key => $id) {
		$results['array'][$y] = $results['pending_business_location'][$key];
		if(!empty($results['array'][$y])) $y++;
	}
	
	
	### POSSIBLE PDB CLAIM
	// $tmp_sql = "SELECT a.*
	// FROM ids_business a
	// INNER JOIN
	// (
	// SELECT *, MAX(datetime_created) maxDateCreated
	// FROM ids_business
	// WHERE 
	// (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
	// AND 
	// (proof_of_business_location_filename = '' OR proof_of_business_location_filename IS NULL)
	// AND
	// (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	// GROUP BY memberid
	// ) b ON 
	// a.memberid = b.memberid AND
    // a.datetime_created = b.maxDateCreated
	// ;
	// ";
	// $tmp_sql = "SELECT * FROM ids_business
	//     		WHERE (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	//     		AND business_legal_extension = 'PDB'
	//     		";
	//     		
	// //test("tmp_sql",$tmp_sql);
	// $results['pending_business_identity'] = object2array(readarrayTHECASHIER($tmp_sql));
	// $results['pending_counter'] = $results['pending_counter'] + count($results['pending_business_identity']);
	// //test("results",$results);
	// 
	// foreach($results['pending_business_identity'] as $key => $id) {
	//     $results['array'][$x] = $results['pending_business_identity'][$key];
	//     $x++;
	// }
	
	
	
	
	
	
	//test("results['array']",$results['array']);
	
	$results['pending_counter'] = $results['pending_counter'];
	if($results['pending_counter'] < 1) $results['pending_counter'] = "0";
	
	return $results;
	
}


function get_cdba_parent($accountid) {

	
	$verified_business_details = "";
	
	//$account_details = account($accountid);
	$account_details = object2array(readTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';"));
	
	## VERIFIED:
	
	# $tmp_sql = "SELECT * FROM ids_business 
	# WHERE
	# accountid = '". $account_details['accountid'] ."'
	# AND business_name = '". $account_details['accountname'] ."' 
	# AND business_legal_extension = '".$account_details['business_type']."' 
	# AND status = 'VERIFIED'
	# ORDER BY datetime_created DESC;
	# ";

	$tmp_sql = "SELECT * FROM ids_business 
	WHERE
	accountid = '". $account_details['accountid'] ."'
	AND business_legal_extension = '".$account_details['business_type']."' 
	AND status = 'VERIFIED'
	ORDER BY datetime_created DESC;
	";
	logger3("tmp_sql",$tmp_sql);
	
	$verified_business_details = readTHECASHIER($tmp_sql);
	logger3("verified_business_id",$verified_business_id);
	
	
	if(empty($verified_business_details)) {
	
	
		### PENDING:
		//$tmp_sql = "SELECT * FROM ids_business 
		//WHERE
		//accountid = '".$account_details['accountid']."'
		//AND business_name = '".$account_details['accountname']."' 
		//AND business_legal_extension = '".$account_details['business_type']."' 
		//AND (status = 'SUBMITTED' OR status LIKE '%HOLD%')
		//ORDER BY datetime_created DESC;
		//";

		$tmp_sql = "SELECT * FROM ids_business 
		WHERE
		accountid = '".$account_details['accountid']."'
		AND business_legal_extension = '".$account_details['business_type']."' 
		AND (status = 'SUBMITTED' OR status LIKE '%HOLD%')
		ORDER BY datetime_created DESC;
		";
		logger3("tmp_sql",$tmp_sql);
		
		$verified_business_details = readTHECASHIER($tmp_sql);
		logger3("verified_business_details",$verified_business_details);
	}
	
	return $verified_business_details->parent_account_hash;

}


function get_list_of_valid_bank_account_claims() {
	
	$tmp_sql = "SELECT * FROM wallets 
				WHERE type = 'SWIFT' 
				AND (status = 'SUBMITTED' OR status LIKE '%HOLD%')
				ORDER BY datetime_updated ASC
				;";
	//test("tmp_sql",$tmp_sql);
	$walletid_array = object2array(arrayTHECASHIER($tmp_sql));
	//test("walletid_array",$walletid_array);
	$wallet_array_details = readarrayTHECASHIER($tmp_sql);
	//test("wallet_array_details",$wallet_array_details);
	
	
	$valid_counter = 0;
	foreach($wallet_array_details as $key => $row) {
	
		// $tmp_sql = "SELECT * FROM wallets WHERE walletid = '".$walletid."';";
		// //test("tmp_sql",$tmp_sql);
		// $wallet_details = object2array(readTHECASHIER($tmp_sql));
		// //test("wallet_details",$wallet_details);
		
		
		//$parent_account_details = object2array(readTHECASHIER("SELECT * FROM account WHERE hash = '". $row['banking_account_owner_account_hash'] ."';"));
		// account($row['banking_account_owner_account_hash']);
		//test("parent_account_details",$parent_account_details);
		
		
		//$parent_member_details = member($row['memberid']);
		//test("parent_member_details",$parent_account_details);
		
		
		
		$business_type = getTHECASHIER("SELECT business_type FROM accounts WHERE accountid = '". $row['accountid'] ."';");
		//test("business_type",$business_type);
		//if($row['accountid'] == 5889) test("business_type",$business_type);
		
		$ids_personal = get_ids_personal($memberid=$row['memberid'],$accountid='');
		//test("ids_personal",$ids_personal);
		//if($row['accountid'] == 5889) test("ids_personal",$ids_personal);
		
		if(!stristr($business_type,"PDB")) {
			$ids_business = get_ids_business($memberid='',$accountid=$row['accountid']);
		} else {
			$ids_business = $ids_personal;
		}
		//test("ids_business",$ids_business);
		//if($row['accountid'] == 5889) test("ids_business",$ids_business);
		
		if(
		
		(stristr($ids_personal['current']['identity']['status'],"VERIFIED")) &&
		(stristr($ids_personal['current']['location']['status'],"VERIFIED")) &&
		
		(stristr($ids_business['current']['identity']['status'],"VERIFIED")) &&
		(stristr($ids_business['current']['location']['status'],"VERIFIED"))
		
		) {
			
			$valid_claim_array[$valid_counter] = $row;
			$valid_counter++;
		
		}
	}
	
	$return['count'] = $valid_counter;
	$return['array_details'] = $valid_claim_array;
	//test("return['array_details']",$return['array_details']);
	return $return;
}




function get_account_DTR($accountid) {
	
	
	if(empty($accountid)) $accountid = $_SESSION['account']['accountid'];
	if(empty($accountid)) return FALSE;
	## 
	## $tmp_sql = "SELECT * FROM accounts WHERE accountid = '". $accountid ."';";
	## $tmp_acocunt_details = object2array(readTHECASHIER($tmp_sql));
	## 
	## //test("tmp_acocunt_details",$tmp_acocunt_details);
	## 
	## /// ECP
	## if(
	## (stristr($tmp_acocunt_details['sponsor_accountid'],"b7e9aac09c099d4bfe5cfc85917df9e3")) ||
	## (stristr($tmp_acocunt_details['fee_and_schedule_profile']['cc_gateway'],"ECP"))
	## ) {
	## 	
	## 	return "20";
	## 
	## } else {
	## 	
	## 	return "30";	
	## 	
	## }
	
	return get_dynamic_DTR($accountid);
	
	
	
	
}

function get_list_of_withdrawal_requests($show='') {
	
	# $results = "";
	# $results = array();
	# 
	# $tmp_sql = "SELECT transactionid FROM transactions WHERE description = 'WITHDRAWAL' AND (status = 'APPROVED' OR status LIKE '%HOLD%') ORDER BY updated_datetime ASC;";
	# //test("tmp_sql",$tmp_sql);
	# 
	# $pending_withdrawal_transactionid_array = arrayTHECASHIER($tmp_sql);
	# //test("pending_withdrawal_transactionid_array",$pending_withdrawal_transactionid_array);
	# 
	# $x = 0;
	# foreach($pending_withdrawal_transactionid_array as $key => $transactionid) {
	# 	
	# 	$verified_walletid = "";
	# 	$transaction_details = transaction($transactionid);
	# 	
	# 	
	# 	$tmp_sql = "SELECT walletid FROM wallets 
	# 	WHERE 
	# 	walletid = '".$transaction_details['walletid']."'
	# 	AND status = 'VERIFIED'
	# 	;";
	# 	//test("tmp_sql",$tmp_sql);
	# 	$verified_walletid = getTHECASHIER($tmp_sql);
	# 	//test("verified_walletid",$verified_walletid);
	# 	
	# 	if(!empty($verified_walletid)) { // DISPLAY A FINAL TOTAL VALUE TO CASHOUT
	# 	
	# 		$results['transactionid_array'][$x] = $transactionid;
	# 	
	# 		//$results[$x] = $transaction_details;
	# 		$results['gross_total'] = currency_format($results['gross_total'] + $transaction_details['transaction_gross_value']);
	# 		$x++;
	# 		
	# 	}
	# 	
	# 	
	# }
	# 
	# if(count($results) > 0) {
	# 	$results['count'] = count($results)-1; // subtract one for gross total of actual records.
	# } else {
	# 	$results['count'] = "0";
	# }
	# 
	# return $results;
	
	
	

	if($show == "gsp") { // shows pending withdrawals form GSP meltdown
		$tmp_sql = "SELECT * FROM transactions 
				WHERE description = 'WITHDRAWAL'
				AND (status = 'APPROVED' OR status LIKE '%HOLD%')
				AND requested_datetime > '2014-03-10 01:00:00'
				ORDER BY updated_datetime ASC;";
	} else {
		$tmp_sql = "SELECT * FROM transactions 
				WHERE description = 'WITHDRAWAL'
				AND (status = 'APPROVED' OR status LIKE '%HOLD%')
				AND requested_datetime > '2014-03-10 01:00:00'
				AND requested_datetime NOT LIKE '%2014-05-20%'
				ORDER BY updated_datetime ASC;";
	}

	//test("tmp_sql",$tmp_sql);
	$transaction_list_array = readarrayTHECASHIER($tmp_sql);
	
	
	//test("transaction_list_array",$transaction_list_array); 
	//exit;
	
	//$get_list_of_withdrawal_requests = get_list_of_withdrawal_requests();
	//$transactionids_array =  $get_list_of_withdrawal_requests$transactionids_array;
	

	$results = "";
	$results = array();
	$results['sum_total'] = "0.00";
	
	
	$x = 0;
	foreach($transaction_list_array as $key => $transaction_details) {
		

		//test("transaction_details",$transaction_details);
		//exit;
		
		
			
		//$transaction_details = transaction($trasnactionid);

		//test("transaction_details ($key)",$transaction_details);
		//test("transaction_details['transaction_gross_value']",$transaction_details['transaction_gross_value']);
		
		//test("transaction_details['accountid']",$transaction_details['accountid']);
		
		$ids_business_details = get_ids_business($memberid='',$accountid=$transaction_details['accountid']); // ($transaction_details['accountid']);
		//test("ids_business_details",$ids_business_details);
		//exit;
		
		
		//test("account_details",$account_details);
		//test("account_details['verified']",$account_details['verified']);
		
		//$parent_details = get_parent_details($transaction_details['accountid']);
		//test("parent_details",$parent_details);
		
		$ids_personal_details = get_ids_personal($memberid=$transaction_details['memberid'],$accountid='');
		//test("ids_personal_details",$ids_personal_details);
		//exit;
		
		# 
		# $tmp_sql = "SELECT walletid FROM wallets WHERE memberid = '".$transaction_details['memberid']."' AND accountid = '".$transaction_details['accountid']."' AND status = 'VERIFIED' AND type = 'SWIFT';";
		# #test("tmp_sql",$tmp_sql);
		# $walletid = getTHECASHIER($tmp_sql);
		# 
		# $walletid = $transaction_details['walletid'];
		
		
		// walletid = "";
		// $tmp_sql = "SELECT * FROM wallets 
		// 			WHERE walletid = '".$transaction_details['walletid']."'
		// 			AND status = 'VERIFIED'
		// ;";
		// //test("tmp_sql",$tmp_sql);
		// $wallet_details = readTHECASHIER($tmp_sql);
		// //test("wallet_details",$wallet_details);
		
		$wallet_details = wallet($transaction_details['walletid']);
		//test("wallet_details",$wallet_details);
				
		// if(stristr($verified_wallet_details['status'],"VERIFIED")) {
		// 
		// 	$walletid = $verified_wallet_details['hash'];
		// 	
		// } else {
		//     
		//     // $tmp_sql = "SELECT hash FROM wallets
		//     // WHERE accountid = '". $account_details['accountid'] ."'
		//     // AND type = 'SWIFT'
		//     // AND status = 'VERIFIED'
		//     // ORDER BY datetime_updated DESC
		//     // LIMIT 1
		//     // ;";
		//    /// / test("tmp_sql",$tmp_sql);
		//     // $walletid = getTHECASHIER($tmp_sql);
		//    /// / test("walletid",$walletid);
		//    
		//    
		//    $verified_wallet_details = get_bank_account($account_details['accountid']);
		//    //test("verified_wallet_details",$verified_wallet_details);
		//    
		//    $walletid = $verified_wallet_details['verified']['hash'];
		//     
		// }
		
		
			
		//test("walletid",$walletid);
		//test("member_details['verified']['identity']['hash']",$member_details['verified']['identity']['hash']);
		//test("member_details['verified']['location']['hash']",$member_details['verified']['location']['hash']);
		//test("acocunt_details['verified']['identity']['hash']",$account_details['verified']['identity']['hash']);
		//test("account_details['verified']['location']['hash']",$account_details['verified']['location']['hash']);
		
		
		if($show != "gsp") {
		
			if(
			(stristr($ids_personal_details['current']['identity']['status'],"VERIFIED")) &&
			(stristr($ids_personal_details['current']['location']['status'],"VERIFIED")) &&
			
			(stristr($ids_business_details['current']['identity']['status'],"VERIFIED")) &&
			(stristr($ids_business_details['current']['location']['status'],"VERIFIED")) &&
			
			(stristr($wallet_details['status'],"VERIFIED"))
			
			) { 
				//test("tmp_sql",$walletid);
				//test("yay!",$trasnactionid);
				
				//test("$x : transaction_details",$transaction_details);
				
				//$transaction_details = transaction($trasnactionid);
				$clean_transaction_list_array[$x] = $transaction_details;
				$results['sum_total'] = currency_format($results['sum_total'] + $transaction_details['transaction_net_value']);
				$transaction_details = "";
				$x++;	
				
				
			}
		} else {
			
			$clean_transaction_list_array[$x] = $transaction_details;
			$results['sum_total'] = currency_format($results['sum_total'] + $transaction_details['transaction_net_value']);
			$transaction_details = "";
			$x++;	
				
		}
		
		
	}

	//exit; // foreach();
	
	
	
	
	$results['count']  = count($clean_transaction_list_array);
	if(empty($results['count'])) $results['count'] = "0";
	$results['clean_transaction_list_array'] = $clean_transaction_list_array;
	
	/// legacy
	$results['gross_total'] = $results['sum_total']; 
	//$results['transactionid_array'] = $results['transactionids'];
	
	
	//exit;
	
	//test("results",$results);
	
	return $results;
	
	
}





function wallet($wallet_id) {

	if(strlen($wallet_id) > 30) {
	
		$tmp_sql = "SELECT * FROM wallets WHERE hash LIKE '". $wallet_id ."';";
	
	} else {
	
		$tmp_sql = "SELECT * FROM wallets WHERE walletid = '".$wallet_id."';";
	
	}

	$wallet_details = object2array(readTHECASHIER($tmp_sql));

	return $wallet_details;

}




function getFeeScheduleProfileDetails($profile_name) {
	$tmp_sql = "SELECT * FROM fee_and_schedule_profiles WHERE profile_name = '".$profile_name."';";
	return object2array(readTHECASHIER($tmp_sql));
}


function getActiveSWIFT($accountid='',$memberid='') {
	
	if( !empty($memberid) && !empty($accountid) ) {
		$tmp_sql = "SELECT * FROM wallets WHERE accountid = '". $accountid ."' AND memberid = '".$memberid."' AND type = 'SWIFT' AND (status = 'VERIFIED' OR status = 'SUBMITTED' OR status LIKE '%HOLD%') ORDER BY datetime_updated DESC LIMIT 1;";
	} else if( !empty($accountid) ) {
		$tmp_sql = "SELECT * FROM wallets WHERE accountid = '". $accountid ."' AND type = 'SWIFT' AND (status = 'VERIFIED' OR status = 'SUBMITTED' OR status LIKE '%HOLD%') ORDER BY datetime_updated DESC LIMIT 1;";
	} else {
		return FALSE;
	}
	
	
	
	//test("tmp_sql",$tmp_sql);
	$swift_details = object2array(readTHECASHIER($tmp_sql));
	
	$swift_details['account_number_LAST4_digits'] = substr($swift_details['banking_account_number'],4);
	
	return $swift_details;
	
}


function get_personal_identity($accountid='',$memberid='') {

	//if(empty($accountid)) $_SESSION['member']['memberid']
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	
	### CHECK VIA ACCOUNT LOOK-UP:
	
	$tmp_sql = "SELECT accountid FROM accounts 
				WHERE creator_memberid = '". $_SESSION['member']['memberid'] . "' 
				AND accounttype = 'PERSONAL'
				;";
	if(empty($accountid)) $accountid = getTHECASHIER($tmp_sql);
	
	//test("accountid",$accountid);
	
	$tmp_sql = "SELECT * FROM ids_personal 
				WHERE accountid = '". $accountid . "' 
				AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
				AND (status = 'SUBMITTED' OR status = 'VERIFIED' or status LIKE '%HOLD%')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['current'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['current']",$results['current']);

	$tmp_sql = "SELECT * FROM ids_personal 
				WHERE accountid = '". $accountid . "' 
				AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['status_details'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['status_details']",$results['status_details']);
	
	### THEN CHECK MEMBER DIRECTLY:
	
	if(empty($results['current'])) {
		
		
		
		
		$tmp_sql = "SELECT * FROM ids_personal 
					WHERE memberid = '". $memberid . "' 
					AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
					AND (status = 'SUBMITTED' OR status = 'VERIFIED' or status LIKE '%HOLD%')
					ORDER BY datetime_updated DESC
					LIMIT 1
					;";
		//test("tmp_sql",$tmp_sql);
		$results['current'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['current']",$results['current']);


		$tmp_sql = "SELECT * FROM ids_personal 
		    		WHERE accountid = '". $accountid . "' 
		    		AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
		    		ORDER BY datetime_updated DESC
		    		LIMIT 1
		    		;";
		//test("tmp_sql",$tmp_sql);
		$results['status_details'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['status_details']",$results['status_details']);
	
	}
	
	
	### CHECK VIA ACCOUNT LOOK-UP:
	$tmp_sql = "SELECT * FROM ids_personal
				WHERE accountid = '". $accountid . "' 
				AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
				AND (status = 'VERIFIED')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['verified'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['verified']",$results['verified']);

	### THEN CHECK MEMBER DIRECTLY:
	
	if(empty($results['verified'])) {
	
		### CHECK VIA ACCOUNT LOOK-UP:
		$tmp_sql = "SELECT * FROM ids_personal
					WHERE memberid = '". $memberid . "' 
					AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
					AND (status = 'VERIFIED')
					ORDER BY datetime_updated DESC
					LIMIT 1
					;";
		//test("tmp_sql",$tmp_sql);
		$results['verified'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['verified']",$results['verified']);
	
	}
	
	//test("get_personal_identity() results",$results);
	return $results;
	
}

function get_personal_location($accountid='',$memberid='') {

	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];

	$tmp_sql = "SELECT accountid FROM accounts 
				WHERE creator_memberid = '". $_SESSION['member']['memberid'] . "' 
				AND accounttype = 'PERSONAL'
				;";
	if(empty($accountid)) $accountid = getTHECASHIER($tmp_sql);
	
	//$tmp_account_details = account($accountid);
	//$tmp_member_details = member($tmp_account_details['creator_memberid']);
	
	############################################
	### CURRENT: 
	############################################
	
	$tmp_sql = "SELECT * FROM ids_personal 
				WHERE accountid = '". $accountid . "' 
				AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['current'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['current']",$results['current']);
	
	
	$tmp_sql = "SELECT * FROM ids_personal 
				WHERE accountid = '". $accountid . "' 
				AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['status_details'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['status_details']",$results['status_details']);
	
	
	### THEN CHECK MEMBER DIRECTLY:
	
	if(empty($results['current'])) {
	
	
		$tmp_sql = "SELECT * FROM ids_personal 
					WHERE memberid = '". $memberid . "' 
					AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
					ORDER BY datetime_updated DESC
					LIMIT 1
					;";
		//test("tmp_sql",$tmp_sql);
		$results['current'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['current']",$results['current']);

		$tmp_sql = "SELECT * FROM ids_personal 
		    		WHERE memberid = '". $memberid . "' 
		    		AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
		    		ORDER BY datetime_updated DESC
		    		LIMIT 1
		    		;";
		//test("tmp_sql",$tmp_sql);
		$results['status_details'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['status_details']",$results['status_details']);
	
	}
	
	
	
	# ############################################
	# ### VERIFIED:
	# ############################################  (i think we do not use verified any more)
	# 
	# $tmp_sql = "SELECT * FROM ids_personal 
	# 			WHERE accountid = '". $accountid . "' 
	# 			AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
	# 			AND (status = 'VERIFIED')
	# 			ORDER BY datetime_updated DESC
	# 			LIMIT 1
	# 			;";
	# //test("tmp_sql",$tmp_sql);
	# $results['verified'] = object2array(readTHECASHIER($tmp_sql));
	# //test("results['verified']",$results['verified']);

	### THEN CHECK MEMBER DIRECTLY:
	
	if(empty($results['verified'])) {
	
		$tmp_sql = "SELECT * FROM ids_personal 
					WHERE memberid = '". $memberid . "' 
					AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
					AND (status = 'VERIFIED')
					ORDER BY datetime_updated DESC
					LIMIT 1
					;";
		//test("tmp_sql",$tmp_sql);
		$results['verified'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['verified']",$results['verified']);
	
	}
	
	//test("get_personal_location(): results",$results);
	return $results;
	
	
}


function get_business_identity($accountid='',$memberid='') {
	
	if(empty($accountid)) $accountid = $_SESSION['account']['accountid'];
	//test("accountid",$accountid);
	$tmp_account_details = account($accountid);
	
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	//test("memberid",$memberid);
	$tmp_member_details = member($memberid);
	

	
	$tmp_sql = "SELECT * FROM ids_business 
				WHERE accountid = '". $accountid . "' 
				AND (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['current'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['current']",$results['current']);
	
	$tmp_sql = "SELECT * FROM ids_business
				WHERE accountid = '". $accountid . "' 
				AND (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
				AND (status = 'VERIFIED')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['verified'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['verified']",$results['verified']);
	
	
	//test("results['current']['business_legal_extension']",$esults['current']['business_legal_extension']);
	
	//test("_SESSION['account']",$_SESSION['account']);
	### IF IT"S A DBA/GROUP = check the member
	if(
	(stristr($tmp_account_details['business_type'],"DBA")) ||
	(stristr($tmp_account_details['business_type'],"GROUP"))
	) {


		### VERIFIED IDENTITY (i think we do not use verified identity any more)
		# $tmp_sql = "SELECT * FROM ids_business
		# WHERE accountid = '". $accountid . "' 
		# AND (business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
		# AND business_name = '". $tmp_account_details['accountname'] ."'
		# ORDER BY datetime_updated DESC
		# LIMIT 1
		# ;";
		# //test("tmp_sql",$tmp_sql);
		# $results['verified'] = object2array(readTHECASHIER($tmp_sql));
		# //test("results['verified']",$results['verified']);
		# $results['verified']['status'] = $tmp_member_details['current']['identity']['status'];



		### CURRENT IDENTITY
		$tmp_sql = "SELECT * FROM ids_business
		WHERE accountid = '". $accountid . "' 
		AND (business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
		ORDER BY datetime_updated DESC
		LIMIT 1
		;";
		//test("tmp_sql",$tmp_sql);
		$results['current'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['verified']",$results['verified']);
		$results['current']['status'] = $tmp_member_details['current']['identity']['status'];
		
	}
	
	//test("results",$results);
	//exit;
	return $results;
	
	
}

function get_business_location($accountid='',$memberid='') {



	if(empty($accountid)) $accountid = $_SESSION['account']['accountid'];
	//test("accountid",$accountid);
	$tmp_account_details = account($accountid);
	//test("tmp_account_details",$tmp_account_details);
	
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	//test("memberid",$memberid);
	$tmp_member_details = member($memberid);

	
	$tmp_sql = "SELECT * FROM ids_business 
				WHERE accountid = '". $accountid . "' 
				AND (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
				AND (status = 'SUBMITTED' OR status = 'VERIFIED' or status LIKE '%HOLD%')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['current'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['current']",$results['current']);
	
	$tmp_sql = "SELECT * FROM ids_business
				WHERE accountid = '". $accountid . "' 
				AND (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
				AND (status = 'VERIFIED')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['verified'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['verified']",$results['verified']);


	if(
	(stristr($tmp_account_details['business_type'],"DBA")) ||
	(stristr($tmp_account_details['business_type'],"GROUP"))
	) {
		
		if(
		(stristr($tmp_member_details['current']['location']['status'],"VERIFIED"))
		) {
			
			$results['verified']['idid'] = $tmp_member_details['current']['location']['idid'];
			$results['verified']['status'] = $tmp_member_details['current']['location']['status'];
			
			$results['verified']['proof_of_business_location_filename'] = $tmp_member_details['current']['location']['proof_of_residence_filename'];
			$results['verified']['business_address_1'] = $tmp_member_details['current']['location']['residential_address_1'];
			$results['verified']['business_address_2'] = $tmp_member_details['current']['location']['residential_address_2'];
			$results['verified']['business_address_3'] = $tmp_member_details['current']['location']['residential_address_3'];
			$results['verified']['business_country_iso3'] = $tmp_member_details['current']['location']['residential_country_iso3'];
			$results['verified']['datetime_updated'] = $tmp_member_details['current']['location']['datetime_updated'];
			
			
		} 
		
		$results['current']['idid'] = $tmp_member_details['current']['location']['idid'];
		
		$results['current']['status'] = $tmp_member_details['current']['location']['status'];
		
		$results['current']['proof_of_business_location_filename'] = $tmp_member_details['current']['location']['proof_of_residence_filename'];
		$results['current']['business_address_1'] = $tmp_member_details['current']['location']['residential_address_1'];
		$results['current']['business_address_2'] = $tmp_member_details['current']['location']['residential_address_2'];
		$results['current']['business_address_3'] = $tmp_member_details['current']['location']['residential_address_3'];
		$results['current']['business_country_iso3'] = $tmp_member_details['current']['location']['residential_country_iso3'];
		$results['current']['datetime_updated'] = $tmp_member_details['current']['location']['datetime_updated'];
		
					
			
		
				
	}
	
	
	
	
	
	
	//test("results",$results);
	return $results;
	
	
}


function confirm_plus($number) {
	if(!stristr($number,"+")) $number = "+".$number;
	return $number;
}

function get_current_verified_swift_account($memberid,$accountid,$status='') {

	if(empty($status)) {
		$status = "
		AND status = 'VERIFIED'";
	} else if(stristr($status,"ALL")) {
		$status = "";
	}
	
	if( !empty($memberid) && !empty($accountid) ) {
	
		$tmp_sql = "SELECT walletid FROM wallets
		WHERE memberid = '". $memberid ."'
		AND accountid = '". $accountid ."'
		$status
		AND type = 'SWIFT'
		ORDER BY datetime_created DESC
		LIMIT 1
		;";
		//test("tmp_sql",$tmp_sql);
		$current_swift_account_details = getTHECASHIER($tmp_sql);
		//test("current_swift_account_details",$current_swift_account_details);
		return $current_swift_account_details;
	}
}


function get_parent_details($accountid) {

	$account_details = account($accountid);
	
	//test("account_details",$account_details);
	
	if(stristr($account_details['accounttype'],"BUSINESS")) {
	
	
	
	
		if(
		(stristr($account_details['business_type'],"GROUP")) ||
		(stristr($account_details['business_type'],"PDB"))
		) {
		
			//test("this is a registered company",$account_details['business_type']);
			###
			$tmp_creator_member_details = member($account_details['creator_memberid']);
			//test("tmp_creator_member_details",$tmp_creator_member_details);

			$return['name'] = "";
			if(!empty($tmp_creator_member_details['current']['identity']['firstname'])) $return['name'] .= $tmp_creator_member_details['current']['identity']['firstname'];
			if(!empty($tmp_creator_member_details['current']['identity']['firstname'])) $return['name'] .= " ";
			if(!empty($tmp_creator_member_details['current']['identity']['middlename'])) $return['name'] .= $tmp_creator_member_details['current']['identity']['middlename'];
			if(!empty($tmp_creator_member_details['current']['identity']['middlename'])) $return['name'] .= " ";
			if(!empty($tmp_creator_member_details['current']['identity']['lastname'])) $return['name'] .= $tmp_creator_member_details['current']['identity']['lastname'];
			
			###
			
			$return['street_1'] = $tmp_creator_member_details['current']['location']['residential_address_1'];
			
			$return['street_2'] = $tmp_creator_member_details['current']['location']['residential_address_2'];
			
			if(!empty($tmp_creator_member_details['current']['location']['residential_address_3'])) {
				$return['street_2'] .= "; ". $tmp_creator_member_details['current']['location']['residential_address_3'];
			}
			
			$personal_account_hash = 			
			$return['city'] = "";
			$return['state'] = "";
			$return['region'] = "";
			$return['country_iso3'] = $tmp_creator_member_details['current']['location']['residential_country_iso3'];
			$return['account_hash'] = getTHECASHIER("SELECT hash FROM accounts WHERE accountid = '". $tmp_creator_member_details['accounts']['personal'] ."';");
			$return['accountid'] = $tmp_creator_member_details['accounts']['personal'];
			
		} else if(
		(stristr($account_details['business_type'],"CDBA"))
		) {
			$tmp_sql = "SELECT * FROM ids_business 
			 									WHERE business_name = '". $account_details['accountname'] ."'
			 									AND business_legal_extension = 'CDBA'
			 									AND accountid = '". $account_details['accountid'] ."' 
			 									ORDER BY datetime_updated
			 									LIMIT 1
			 									;";
			//test("tmp_sql",$tmp_sql);
			 					
			$ids_business_details = object2array(readTHECASHIER($tmp_sql));
			//test("000ids_business_details",$ids_business_details);
			//test("ids_business_details['accountid']",$ids_business_details['accountid']);
			$tmp_parent_account = object2array(readTHECASHIER("SELECT * FROM accounts WHERE hash = '" . $ids_business_details['parent_account_hash'] . "';")); 
			//test("tmp_cdba_account_details",$tmp_cdba_account_details);
			
			//$tmp_parent_account = account($ids_business_details['parent_account_hash']);
			//test("ids_business_details['parent_account_hash']",$ids_business_details['parent_account_hash']);
			//$tmp_parent_account = object2array(readTHECASHIER("SELECT * FROM accounts WHERE hash = '" . $ids_business_details['parent_account_hash'] . "';")); 
			//test("tmp_parent_account",$$tmp_parent_account);
						
			$return['name'] = $tmp_parent_account['accountname'] . " " . $tmp_parent_account['business_type'];
			###
			$return['street_1'] = $tmp_parent_account['streetaddress1'];
			$return['street_2'] = $tmp_parent_account['streetaddress2'];
			$return['city'] = $tmp_parent_account['city'];
			$return['state'] = $tmp_parent_account['state'];
			$return['region'] = $tmp_parent_account['region'];
			$return['country_iso3'] = $tmp_parent_account['country_iso3'];
			$return['account_hash'] = $tmp_parent_account['hash'];
			$return['accountid'] = $tmp_parent_account['accountid'];
			
			
		} else {
			//test("this is a DBA",$account_details['business_type']);
			###
			$return['name'] = $account_details['accountname'] . " " . $account_details['business_type'];
			###
			$return['street_1'] = $account_details['streetaddress1'];
			$return['street_2'] = $account_details['streetaddress2'];
			$return['city'] = $account_details['city'];
			$return['state'] = $account_details['state'];
			$return['region'] = $account_details['region'];
			$return['country_iso3'] = $account_details['country_iso3'];
			$return['account_hash'] = $account_details['hash'];
			$return['accountid'] = $account_details['accountid'];
			
		}
	}
	
	return $return;
	
}




function update_personal_identities($memberid="",$accountid="") {


	$tmp_datetime = datetime();
	
	$tmp_ids_personal_array = arrayTHECASHIER("select idid FROM ids_personal WHERE status = 'VERIFIED';");
	
	foreach($tmp_ids_personal_array as $key => $personal_idid) {
	

		$tmp_sql = "SELECT * FROM ids_personal WHERE idid = '$personal_idid';";
		$personal_id_details = readTHECASHIER($tmp_sql);	

		### START: UPDATE PERSONAL IDENTITY
		if(!empty($personal_id_details->photo_id_filename)) {
		    
		   // test("HIT!",$HIT++);
		    $tmp_sql = "UPDATE members 
		    		SET firstname = '$personal_id_details->firstname'
		    		, middlename = '$personal_id_details->middlename'
		    		, lastname = '$personal_id_details->lastname'
		    		, updated = '$tmp_datetime'
		    		WHERE 
		    		memberid = '$personal_id_details->memberid'
		    		;";
		   //test("tmp_sql",$tmp_sql);
		    $updated_members = updateTHECASHIER($tmp_sql);
		    //test("updated_members",$updated_members);
		    
		    $account_name = "";
		    if(!empty($personal_id_details->firstname)) $account_name .= $personal_id_details->firstname;
		    if(
		    (!empty($personal_id_details->firstname)) &&
		    (!empty($personal_id_details->middlename))
		    ) {
			    $account_name .= " ";
		    }
		    if(!empty($personal_id_details->middlename)) $account_name .= $personal_id_details->middlename;
		    
		    if(
		    (
		    (!empty($personal_id_details->firstname)) ||
		    (!empty($personal_id_details->middlename))
		    ) &&
		    (!empty($personal_id_details->lastname))
		    ) {
			    $account_name .= " ";
		    }
		    if(!empty($personal_id_details->lastname)) $account_name .= $personal_id_details->lastname;
		    
		    $tmp_sql = "UPDATE accounts 
		        		SET accountname = '$account_name'
		        		, business_type = ''
		        		, updated = '$tmp_datetime'
		        		WHERE 
		        		accountid = '$personal_id_details->accountid'
		        		;";
		   //test("tmp_sql",$tmp_sql);
		    $updated_accounts = updateTHECASHIER($tmp_sql);
		    //test("updated_accounts",$updated_accounts);
		
		}
			### END: UPDATE PERSONAL IDENTITY
			
			
			
		### START: UPDATE PERSONAL LOCATION
		if(!empty($personal_id_details->proof_of_residence_filename)) {
		    
		    // test("HIT!",$HIT++);
		    // note missing formal state city region structure. should be added and change in the ids_personal table to accommodate said structure.
		    $tmp_sql = "UPDATE accounts 
		        		SET streetaddress1 = '$personal_id_details->residential_address_1'
		        		, streetaddress2 = '$personal_id_details->residential_address_2'
		    			, country_iso3 = '$personal_id_details->residential_country_iso3'
		        		, updated = '$tmp_datetime'
		        		WHERE 
		        		accountid = '$personal_id_details->accountid'
		        		;";
		   //test("tmp_sql",$tmp_sql);
		    $updated_accounts = updateTHECASHIER($tmp_sql);
		    //test("updated_accounts",$updated_accounts);
	
		}
		### END: UPDATE PERSONAL LOCATION	
	
	}

}


function update_business_identities($memberid="",$accountid="") {


	$tmp_datetime = datetime();
	
	$tmp_ids_business_array = arrayTHECASHIER("select idid FROM ids_business WHERE status = 'VERIFIED';");
	
	foreach($tmp_ids_business_array as $key => $business_idid) {
	
		$tmp_sql = "SELECT * FROM ids_business WHERE idid = '$business_idid';";
		$business_id_details = readTHECASHIER($tmp_sql);
		
	
	
		### START: UPDATE BUSINESS IDENTITY
		if(!empty($business_id_details->business_certificate_filename)) {
		    
		   // test("HIT!",$HIT++);
		  	//$account_name = "";
		    //if(!empty($business_id_details->firstname)) $account_name .= $business_id_details->firstname;
		    //if(!empty($account_name)) $account_name .= " ";
		    //if(!empty($business_id_details->middlename)) $account_name .= $business_id_details->middlename;
		    //if(!empty($account_name)) $account_name .= " ";
		    //if(!empty($business_id_details->lastname)) $account_name .= $business_id_details->lastname;
		    
		    $tmp_sql = "UPDATE accounts 
		        		SET accountname = '$business_id_details->business_name'
		        		, business_type = '$business_id_details->business_legal_extension'
		        		, updated = '$tmp_datetime'
		        		WHERE 
		        		accountid = '$business_id_details->accountid'
		        		;";
		   //test("tmp_sql",$tmp_sql);
		    $updated_accounts = updateTHECASHIER($tmp_sql);
		    //test("updated_accounts",$updated_accounts);
		
		}
			### END: UPDATE BUSINESS IDENTITY
			
			
			
		### START: UPDATE BUSINESS LOCATION
		if(!empty($personal_id_details->proof_of_business_location_filename)) {
		
			// test("HIT!",$HIT++);
		    
		    // note missing formal state city region structure. should be added and change in the ids_personal table to accommodate said structure.
		    $tmp_sql = "UPDATE accounts 
		        		SET streetaddress1 = '$business_id_details->business_address_1'
		        		, streetaddress2 = '$business_id_details->business_address_2'
		    			, country_iso3 = '$business_id_details->business_country_iso3'
		        		, updated = '$tmp_datetime'
		        		WHERE 
		        		accountid = '$business_id_details->accountid'
		        		;";
		   //test("tmp_sql",$tmp_sql);
		    $updated_accounts = updateTHECASHIER($tmp_sql);
		   // test("updated_accounts",$updated_accounts);
	
		}
		### END: UPDATE BUSINESS LOCATION	
	
	}

}




# function fix_account_sharing_issue(){
# 	
# 	$tmp_sql = "SELECT accountid FROM accounts WHERE accounttype = 'BUSINESS';";
# 	$account_ids = arrayTHECASHIER($tmp_sql);
# 	
# 	foreach($account_ids as $key => $accountid) {
# 	
# 		$account_details = account($accountid);
# 		$tmp_sql = "UPDATE accounts 
# 					SET transaction_fee_my = '". $account_details['transaction_fee_total'] ."' 
# 					WHERE accountid = '". $accountid ."';";
# 		
# 	}
# 	
# 	
# }


function get_account_telephone_support($accountid='') {

	if(empty($accountid)) $accountid = $_SESSION['account']['accountid'];
	if(empty($accountid)) return FALSE;
	
	$account_details = account($accountid);
	$authorization_details = authorization_number($account_details['creator_memberid']);
	$results = "";
	$results = array();
	if(empty($account_details['customer_support_phone_number_1'])) {
		$results['formatted_number'] = $authorization_details['formatted_number'];
		$results['calling_code'] = $authorization_details['calling_code'];
		$results['phone_number'] = $authorization_details['phone_number'];
	} else {
		
		$tmp_customer_support_number = explode("/",$account_details['customer_support_phone_number_1']);
		
		$results['formatted_number'] = $account_details['customer_support_phone_number_1'];
		$results['calling_code'] = $tmp_customer_support_number[0];
		$results['phone_number'] = $tmp_customer_support_number[1];
		
	}
	
	
	//test("results",$results);
	return $results;
}



function get_bank_account($accountid='') {

	//test("get_bank_account(): accountid",$accountid);
	
	if(empty($accountid)) $accountid = $_SESSION['account']['accountid'];
	if(empty($accountid)) return FALSE;
	
	$tmp_sql = "SELECT * FROM wallets
				WHERE accountid = '". $accountid ."'
				AND type = 'SWIFT'
				AND (status = 'SUBMITTED' OR status = 'VERIFIED')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['current'] = object2array(readTHECASHIER($tmp_sql));

	$tmp_sql = "SELECT * FROM wallets
				WHERE accountid = '". $accountid ."'
				AND type = 'SWIFT'
				AND (status = 'VERIFIED')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['verified'] = object2array(readTHECASHIER($tmp_sql));
	
	//test("results",$results);
	return $results;
	
}


function get_CRM_count() {
	
	$day_to_search = date("Y-m-d",strtotime("-5 days"));
	$tmp_sql = "SELECT transactionid FROM transactions
			WHERE accountid = '". $_SESSION['account']['accountid'] . "'
			AND description = 'INCOMING'
			AND (status = 'APPROVED' OR status = 'COMPLETED')
			AND (CRM_CALLBACK_FOLLOWUP = '' OR CRM_CALLBACK_FOLLOWUP = 'CHECKED')
			AND CRM_CALLBACK_MESSAGE = ''
			AND CRM_CALLBACK_REFUNDED = ''
			AND CRM_CALLBACK_SATISFIED = ''
			AND requested_datetime LIKE '". $day_to_search ."%'
			;";
	
	$results = arrayTHECASHIER($tmp_sql);
	return count($results);
	
}


function in_array_MD($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if(
        ($strict ? $item === $needle : $item == $needle) || 
        (is_array($item) && in_array_MD($needle, $item, $strict))
        ) {
            return TRUE;
        }
    }

    return FALSE;
}



#### FROM FRREESWITCH.AUTH
function get_gateway($gateway_attempt) {


 # 0000
 # 1  = worlddialpoint
 # 2  = lax.teliax.net
 # 3  = nyc.teliax.net
 # 4  = den.teliax.net
 # 5  = atl.teliax.net
 # 6  = grnvoip - premium
 # 7  = grnvoip - standard
 # 8  = clickncallnow
 # 9  = flowroute
 # 10 = voiptraffic

### GATEWAY:

	if(empty($_SESSION['function']['gateway_attempt'])) {
		$_SESSION['function']['authorization_voip_gateway_attempt'] = 1;
	
	} else {
		$_SESSION['function']['authorization_voip_gateway_attempt'] = $_SESSION['function']['authorization_voip_gateway_attempt'] + 1;
		
		if($_SESSION['function']['authorization_voip_gateway_attempt'] > $number_of_gateways) {
			$_SESSION['function']['authorization_voip_gateway_attempt'] = $starting_gateway;
		}
		
	}
	
	$gateway_attempt = $_SESSION['function']['authorization_voip_gateway_attempt'];
	
	global $authorization;

	### NOTE:
		# leave a space (" ") after the IP/gateway (which will preceed the extension) - example: "@70.42.72.49 " or "lax.teliax.net "
	
	##############################################################################
	### BLANK ########################################################################
	
	if($gateway_attempt == "0000") {  /// just makes it easier to move-around/re-order the gateways below
		//$gateway_uri = "";



	##############################################################################
	### VOIPBUSTER ###################################################
	

	} else if($gateway_attempt == "xxxxxxxxxxx") { ## more reliable

		$gateway_uri = "sofia/gateway/voipbuster/" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@sip.voipbuster.com ";
		
		
		
	##############################################################################
	### WORLDDIALPOINT #####################################################
	
	} else if(

	($gateway_attempt == "xxxxxxxxxxx")

	) {

		if($_SESSION['authorization']['phone']['country_code'] == "61") { // australian calls
			
			if($_SESSION['authorization']['phone']['number'][0] == "2") { // sydney local landline
				$number_to_dial = $_SESSION['authorization']['phone']['number'][1] . $_SESSION['authorization']['phone']['number'][2] . $_SESSION['authorization']['phone']['number'][3] . $_SESSION['authorization']['phone']['number'][4] . $_SESSION['authorization']['phone']['number'][5] . $_SESSION['authorization']['phone']['number'][6] . $_SESSION['authorization']['phone']['number'][7] . $_SESSION['authorization']['phone']['number'][8];
				
			} else { // all other aussie numbers
				$number_to_dial = "0" . $_SESSION['authorization']['phone']['number'];
			}
		
		} else { // non-australian calls
			$number_to_dial = "0011" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'];
		}
		
		//$gateway_uri = "sofia/gateway/worlddialpoint/" . $number_to_dial . "@203.176.185.10 ";
		$gateway_uri = "sofia/gateway/worlddialpoint/" . $number_to_dial . "@sip.bbvoice.com.au ";
		
	
	##############################################################################
	### TELIAX/LAX #########################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") {
		if($_SESSION['authorization']['phone']['country_code'] == "1") {
			$gateway_prefix = NULL;
		} else {
			$gateway_prefix = "011";
		}
		$gateway_uri = "sofia/gateway/teliax/" . $gateway_prefix . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@lax.teliax.net ";

		
	##############################################################################
	### TELIAX/NYC #########################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") {
		if($_SESSION['authorization']['phone']['country_code'] == "1") {
			$gateway_prefix = NULL;
		} else {
			$gateway_prefix = "011";
		}
		$gateway_uri = "sofia/gateway/teliax/" . $gateway_prefix . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@nyc.teliax.net ";


	##############################################################################
	### TELIAX/DENVER ######################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") {
		if($_SESSION['authorization']['phone']['country_code'] == "1") {
			$gateway_prefix = NULL;
		} else {
			$gateway_prefix = "011";
		}
		$gateway_uri = "sofia/gateway/teliax/" . $gateway_prefix . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@den.teliax.net ";
	
	
	##############################################################################
	### TELIAX/ATL #########################################################
	

	} else if($gateway_attempt == "xxxxxxxxxxx") {

		if($_SESSION['authorization']['phone']['country_code'] == "1") {
			$gateway_prefix = NULL;
		} else {
			$gateway_prefix = "011";
		}
		$gateway_uri = "sofia/gateway/teliax/" . $gateway_prefix . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@atl.teliax.net ";
		
	
	##############################################################################
	### GRNVOIP/PREMIUM ###################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") { ## more reliable
		$gateway_uri = "sofia/gateway/grnvoip/13024401" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@bangk.grnvoip.com ";

	
	##############################################################################
	### GRNVOIP/STANDARD ###################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") { ## more reliable
		$gateway_uri = "sofia/gateway/grnvoip/13024400" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@bangk.grnvoip.com ";

	
	##############################################################################
	### CLICKNCALLNOW ##########################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") {
		$gateway_uri = "sofia/gateway/clickncallnow/" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@sip.clickncallnow.com ";



		
	##############################################################################
	### VOIPTRAFFIC ##########################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") {
		$gateway_uri = "sofia/gateway/voiptraffic/" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@sip.voiptraffic.net ";


	##############################################################################
	### TWILIO ##########################################################
	
	} else if($gateway_attempt == "2") {
		$gateway_uri = "sofia/gateway/Twilio-outbound/+" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@nsdb.pstn.twilio.com ";

	##############################################################################
	### FLOWROUTE ##########################################################
	
	} else if($gateway_attempt == "1") {
		
		$gateway_uri = "sofia/gateway/flowroute/" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@sip.flowroute.com ";
		logger3(">>> gateway_uri",$gateway_uri);
		logger3(">>> _SESSION['authorization']",$_SESSION['authorization']);


	}
	
	
	
	
	
	
	logger3("gateway_uri",$gateway_uri);
	return $gateway_uri;
}



function cancel_withdrawal_request($transactionid,$request_updated_banking_documents,$reason,$send_email) {
	
	global $master_config_accounting_emailaddress;
	if(empty($request_updated_banking_documents)) $request_updated_banking_documents = "YES";
	if(empty($reason)) $reason = "Administrative Adjustment";
	if(empty($send_email)) $send_email = "YES";

	### UPDATE TRANSACTION:
	$tmp_datetime = datetime();
	$tmp_sql = "UPDATE transactions 
	SET
	status = 'Canceled',
	return_datetime = '".$tmp_datetime."',
	return_reason = '". $reason ."',
	updated_datetime = '". $tmp_datetime ."'
	WHERE
	transactionid = '". $transactionid ."';";
	//test("tmp_sql",$tmp_sql);
	$update_results = updateTHECASHIER($tmp_sql);
	test("cancel_withdrawal_request(): $transactionid update_results",$update_results);
	
	## $tmp_transactionid = $_SESSION['admin']['withdrawal']['transaction_details']['transactionid'];
	## $_SESSION['admin']['withdrawal']['transaction_details']['transactionid'] = "";
	
	$transaction_details = transaction($transactionid);
	
	
	if(!empty($_SESSION['admin']['withdrawal']['transaction_details']['transactionid'])) {

		$_SESSION['admin']['withdrawal']['transaction_details']['transactionid'] = "";
		$_SESSION['admin']['withdrawal']['transaction_details'] = $transaction_details;
	}

	$current_balance = balance($transaction_details['accountid']);
	//test("current_balance",$current_balance);
	
	//test("_SESSION['admin']['withdrawal']['transaction_details']['transaction_gross_value']",$_SESSION['admin']['withdrawal']['transaction_details']['transaction_gross_value']);
	
	$new_account_balance = currency_format($current_balance['account_balance'] + $transaction_details['transaction_gross_value']);
	//test("new_account_balance",$new_account_balance);
	
	$new_available_balance = currency_format($current_balance['available'] + $transaction_details['transaction_gross_value']);
	//test("new_available_balance",$new_available_balance);
	
	
	### UPDATE BALANCES:
	$tmp_sql = "UPDATE balances SET 
				account_balance = '".$new_account_balance."',
				available = '".$new_available_balance."'
				WHERE 
				accountid = '". $transaction_details['accountid']."'
				;";
	//test("tmp_sql",$tmp_sql);
	$update_results = updateTHECASHIER($tmp_sql);
	//test("update_results",$update_results);

	### SEND BUSINESS UPDATE EMAIL:
	# $member_emailaddress = $email_member_details['emailaddress'];
	# $email_to = $email_member_details['emailaddress'];


	if(stristr($_POST['request_updated_banking_documents'],"YES")) {
		
		
		$tmp_sql = "UPDATE wallets
					SET status = 'INVALID'
					WHERE walletid = '". $transaction_details['walletid'] ."';";
		//test("tmp_sql",$tmp_sql);
		$update_results = updateTHECASHIER($tmp_sql);
		//test("update_results",$update_results);
		
	}

	if(!stristr($send_email,"NO")) {
		
		$email_receipt = "canceled_withdrawal_to_swift_account";
		$email_receipt_cc = $master_config_accounting_emailaddress;
		include($_SESSION['template']['company']['file_path'] . "shared/email_receipts.shared");
		
		
		$_SESSION['SYSMSG'] = "
		<span style='line-height:35px;'>
		CANCELED...<br>
		Funds reverted back to the account.<br>
		Please continue...
		</span>
		";
	}
	
	return "OK";
	
	
}


################################################################################
### FS FUNCTIONS:
 
function event_socket_create($host, $port, $password) {
	
	logger3("got to event_socket_create()",$x);
	
	$fp = fsockopen($host, $port, $errno, $errdesc) or die("Connection to [" . $host . "] failed");
	
	logger3("0 event_socket_create() fp",$fp);
	
	if($fp == FALSE) logger3("1 event_socket_create() fp = FLASE",$x);
	
	if($fp != FALSE) logger3("2 event_socket_create() fp",$fp);
	
	socket_set_blocking($fp,false);
     
	if ($fp) {
		while (!feof($fp)) {
			$buffer = fgets($fp, 1024);
			usleep(100); //allow time for reponse
			if (trim($buffer) == "Content-Type: auth/request") {
				fputs($fp, "auth $password\n\n");
				break;
			}
		}
		return $fp;
	}	else {
		return false;
	}           
}
 



function event_socket_request($fp, $cmd) {
    
	if ($fp) {    
		fputs($fp, $cmd."\n\n");    
		usleep(1000); //allow time for reponse
         
		$response = "";
		$i = 0;
		$contentlength = 0;
		while (!feof($fp)) {
			$buffer = fgets($fp, 4096);
			if ($contentlength > 0) {
				$response .= $buffer;
			}
            
			if ($contentlength == 0) { //if contentlenght is already don't process again
				if (strlen(trim($buffer)) > 0) { //run only if buffer has content
					$temparray = split(":", trim($buffer));
					if ($temparray[0] == "Content-Length") {
						$contentlength = trim($temparray[1]);
					}
				}
			}
            
			usleep(1000); //allow time for reponse
            
			//optional because of script timeout //don't let while loop become endless
			if ($i > 10000) { break; } 
            
			if ($contentlength > 0) { //is contentlength set
				//stop reading if all content has been read.
				if (strlen($response) >= $contentlength) {  
					break;
				}
			}
			$i++;
		}
         
		return $response;
	
	}	else {
		echo "no handle";
	}
}


function process_dump($response) {

 	$order  = array("\r\n", "\n", "\r");
 	$replace = ",";
 	
 	$response = str_replace($order, $replace, $response);	
 	
 
 	$response_array = split(",", $response);
 	$new_array;
 	
 	foreach ($response_array as $item) {
 		$key = substr($item, 0, strpos($item, ":"));
 		$value = substr($item, strpos($item, " "), strlen($item)-1);
 		
 		$new_array[$key] = $value;
 	}
 	
 	return $new_array;
 
}




function process_withdrawal($memberid='',$accountid='',$withdrawal_amount='',$memo='') {


	global $master_config_platform_emulation;
	global $master_config_wire_to_bank_fee_USD;
	global $master_config_wire_to_bank_fee_EUR;
	
	test("process_withdrawal(): accountid",$accountid);
	
	###################################################
	### START: FIX EMPTY VARS:
	if(empty($_SESSION['authorization']['timestamp'])) $_SESSION['authorization']['timestamp'] = datetime();
	
	if(!empty($memberid)) {
		$tmp_admin_member = $_SESSION['member'];
		$_SESSION['member'] = "";
		$_SESSION['member'] = member($memberid);
	}
	
	if(!empty($accountid)) {
		$tmp_admin_account = $_SESSION['account'];
		$_SESSION['account'] = "";
		$_SESSION['account'] = account($accountid);
		
	}
	
	$_SESSION['withdrawal']['banking_account_owner_account_hash'] = $_SESSION['account']['hash'];
	if(!empty($withdrawal_amount)) $_SESSION['withdrawal']['amount'] = $withdrawal_amount;
	
	
	### END: FIX EMPTY VARS:
	###################################################
	


	##############################################################################
	### SET SOME VARS THAT WILL BE COMMON TO ALL TRANSACTION RESULTS:
	$_SESSION['transaction']['ratio'] = get_fx($_SESSION['template']['company']['currency1'],$_SESSION['account']['currency_code_1'],"1.00");
	logger3("_SESSION['transaction']['ratio']",$_SESSION['transaction']['ratio']);
	
	if(empty($_SESSION['authorization']['timestamp'])) $_SESSION['authorization']['timestamp'] = time();
	
	$_SESSION['transaction']['datetime_requested'] = date("Y-m-d H:i:s",$_SESSION['authorization']['timestamp']);
	$_SESSION['transaction']['datetime_updated'] = date("Y-m-d H:i:s",time());
	$_SESSION['transaction']['original_balance'] = balance($_SESSION['account']['accountid']);
	
	logger3("_SESSION['transaction']['original_balance']",$_SESSION['transaction']['original_balance']);
  
	# SET INITIATED BY:
	$_SESSION['transaction']['results'] = "INITIATED BY ACCOUNTID][" . $_SESSION['account']['accountid'] . "][accountname][" . $_SESSION['account']['accountname'] . "][emailaddress][" . $_SESSION['account']['emailaddress'] . "][";
  
	# SET ACCOUNT DETAILS:
	$_SESSION['account_details'] = "ACCOUNTID][" . $_SESSION['account']['accountid'] . "][accountname][" . $_SESSION['account']['accountname'] . "][emailaddress][" . $_SESSION['account']['emailaddress'] . "][";
	
	# SET FEES
	$tmp_transaction_fee = "master_config_wire_to_bank_fee_".$_SESSION['template']['company']['currency1'];
    $tmp_transaction_fee = $$tmp_transaction_fee; //"0.00";

  
	##############################################################################
	### SET AMOUNT_VALUES: (has o be set b4 therwsie valus wonlt display or something)
	#
	# USE VARS:
	$_SESSION['transaction']['requested_value'] = $_SESSION['withdrawal']['amount'];
	//$_SESSION['transaction']['gross_value'] = $_SESSION['withdrawal']['amount'];
	//$_SESSION['transaction']['net_value'] = $_SESSION['withdrawal']['amount'] - $tmp_transaction_fee;
	$_SESSION['transaction']['account_bonus_value'] = "0.00";
	$_SESSION['transaction']['fee_sponsor_value'] = "0.00";
	$_SESSION['transaction']['fee_bonus_value'] = "0.00";
	$_SESSION['transaction']['fee_network_value'] = $tmp_transaction_fee;
	# $_SESSION['transaction']['fee_total_value']
	#
	### UPDATE FOR BANK:
	# $_SESSION['withdrawal']['name_of_banking_institution'];
	# $_SESSION['withdrawal']['banking_routing_number'];
	# $_SESSION['withdrawal']['banking_account_number'];
	# $_SESSION['withdrawal']['banking_iban_swift'];
	# $_SESSION['withdrawal']['banking_telephone_number'];
	
	### GROSS:
	$_SESSION['transaction']['gross_value'] = $_SESSION['withdrawal']['amount']; // + $_SESSION['transaction']['fee_network_value'];
	
	
	    
	#
	### FEES:
	$_SESSION['transaction']['fee_total_value'] = $_SESSION['transaction']['fee_network_value'] + $_SESSION['transaction']['fee_bonus_value'] + $_SESSION['transaction']['fee_sponsor_value'];
	
	
	
	
	#  
	### NET:
	//$_SESSION['transaction']['net_value'] = currency_format($_SESSION['transaction']['requested_value'] * (1-$_SESSION['account']['transaction_fee_my']));
	$_SESSION['transaction']['net_value'] = currency_format($_SESSION['transaction']['gross_value'] - $_SESSION['transaction']['fee_total_value']);
	
	
	#
	### MAKE 'EM LOOK PRETTY:
	$_SESSION['transaction']['gross_value'] = number_format($_SESSION['transaction']['gross_value'],2,".","");
	$_SESSION['transaction']['fee_total_value'] = number_format($_SESSION['transaction']['fee_total_value'],2,".","");
	$_SESSION['transaction']['net_value'] = number_format($_SESSION['transaction']['net_value'],2,".","");

  
	logger3("_SESSION['transaction']['gross_value']",$_SESSION['transaction']['gross_value']);
	logger3("_SESSION['transaction']['fee_total_value']",$_SESSION['transaction']['fee_total_value']);
	logger3("_SESSION['transaction']['net_value']",$_SESSION['transaction']['net_value']);
  
  
	##############################################################################
	### THIS IS A WIRE SO WE HAVE TO SET THE MAIL TO ADDRESS AT THE ACCOUNT NUMBER:
	$banking_account_owner_account_details = account($_SESSION['withdrawal']['banking_account_owner_account_hash']);
	$_SESSION['transaction']['wire_instructions'] = "";
	$_SESSION['transaction']['wire_instructions'] .= "ACCOUNT_NAME][" . $banking_account_owner_account_details['accountname'] . " " . $banking_account_owner_account_details['business_type'] . "][";
	$_SESSION['transaction']['wire_instructions'] .= "BANK_NAME][" . $_SESSION['withdrawal']['name_of_banking_institution'] . "][";
	$_SESSION['transaction']['wire_instructions'] .= "ABA_NUMBER][" . $_SESSION['withdrawal']['banking_routing_number'] . "][";
	$_SESSION['transaction']['wire_instructions'] .= "ACCOUNT_NUMBER][" . $_SESSION['withdrawal']['banking_account_number'] . "][";
	$_SESSION['transaction']['wire_instructions'] .= "IBAN_SWIFT][" . $_SESSION['withdrawal']['banking_iban_swift'] . "][";
	$_SESSION['transaction']['wire_instructions'] .= "PHONE_NUMBER][" . $_SESSION['withdrawal']['banking_telephone_number'] . "][";

	logger3("_SESSION['transaction']['wire_instructions']",$_SESSION['transaction']['wire_instructions']);
  
  
	##############################################################################
	### CANCELED:
	logger3("_SESSION['transaction']['status']",$_SESSION['transaction']['status']);
	if($_SESSION['transaction']['status'] == "Canceled") {
  	
  		# do nothing special
  		
  		//logger3("transaction['status'] 2",$_SESSION['transaction']['status']);
  
  	
		


  	 ##############################################################################
  	### VERIFY SUFFICIENT BALANCE:
  	//} else if(($_SESSION['transaction']['requested_value'] + $_SESSION['transaction']['fee_network_value']) > $_SESSION['transaction']['original_balance']['available']) {
  	
  	} else if($_SESSION['transaction']['requested_value'] > $_SESSION['transaction']['original_balance']['available']) {
    	test("$accountid _SESSION['transaction']['requested_value'] > _SESSION['transaction']['original_balance']['available']", $_SESSION['transaction']['requested_value'] ." > ". $_SESSION['transaction']['original_balance']['available']);
    	$_SESSION['transaction']['status'] = "Rejected";
    	$_SESSION['transaction']['results'] = "Insufficient Funds";
   
   /* 	
    	$_SESSION['SYSMSG'] = "<font color='990000'>REJECTED! Your " . currency1($_SESSION['transaction']['requested_value'],$blank) . " withdrawal request is greater than your current Available Balance of " . currency1($_SESSION['transaction']['original_balance']['available'],$blank) . ".</font color><br>
<br>
<font color='000099'>Please review your transaction receipt below...</font color>";
*/


  	##############################################################################
  	} else { ### ALL GOOD NOW PROCESS TRANSACTION:
  
    	### SET COMMON VARS:
    	$_SESSION['transaction']['status'] = "Approved";
    	logger3("_SESSION['transaction']['status']",$_SESSION['transaction']['status']);
    	//logger3("transaction['status'] 3",$_SESSION['transaction']['status']);
   
   
    	##############################################################################
    	### UPDATE ACCOUNT BALANCE:
    	//$_SESSION['transaction']['new_balance']['available'] = $_SESSION['transaction']['original_balance']['available'] - $_SESSION['transaction']['requested_value'] - $_SESSION['transaction']['fee_total_value'];
    	$_SESSION['transaction']['new_balance']['available'] = $_SESSION['transaction']['original_balance']['available'] - $_SESSION['transaction']['requested_value'];
    	 
    	logger3("_SESSION['transaction']['new_balance']['available']",$_SESSION['transaction']['new_balance']['available']);
    	
    	//$_SESSION['transaction']['new_balance']['account'] = $_SESSION['transaction']['original_balance']['account'] - $_SESSION['transaction']['requested_value'] - $_SESSION['transaction']['fee_total_value'];
    	$_SESSION['transaction']['new_balance']['account'] = $_SESSION['transaction']['original_balance']['account'] - $_SESSION['transaction']['requested_value'];
    	
    	test("$accountid _SESSION['transaction']['new_balance']['account_balance']",$_SESSION['transaction']['new_balance']['account_balance']);
    	
    	if(!empty($master_config_platform_emulation)) {
    		$tmp_platform = $master_config_platform_emulation;
    	} else {
	    	$tmp_platform = $_SESSION['template']['company']['domain'];
    	}
    	$tmp_sql = "UPDATE balances 
    						SET 
    						available = '" . $_SESSION['transaction']['new_balance']['available'] . "' 
							WHERE 
							accountid = '" . $_SESSION['account']['accountid'] . "'
							AND platform = '".$tmp_platform."' 
							AND currency_iso3 = '".$_SESSION['template']['company']['currency1']."'
							;";
		$tmp_results = updateTHECASHIER($tmp_sql);
		test("tmp_sql",$tmp_sql);
		test("tmp_results",$tmp_results);
    	
    	
    	$tmp_sql = "UPDATE balances 
    						SET 
    						account_balance = '" . $_SESSION['transaction']['new_balance']['account'] . "' 
    						WHERE
							accountid = '" . $_SESSION['account']['accountid'] . "'
							AND platform = '". $tmp_platform ."' 
							AND currency_iso3 = '".$_SESSION['template']['company']['currency1']."'
							;";
		$tmp_results = updateTHECASHIER($tmp_sql);
		test("tmp_sql",$tmp_sql);
		test("tmp_results",$tmp_results);
    }
  
 
    //// SET SOME VARS FOR DB:
    $_SESSION['transaction']['hash'] = hash_me();
	$tmp_transaction_fee = "master_config_wire_to_bank_fee_".$_SESSION['template']['company']['currency1'];
    $_SESSION['withdrawal']['fee'] = $$tmp_transaction_fee; //"0.00";
 	$_SESSION['transaction']['currency_0_iso3'] = $_SESSION['template']['company']['currency1'];
	$_SESSION['transaction']['currency_0_request'] = currency_format($_SESSION['withdrawal']['amount']);
	$_SESSION['transaction']['currency_0_fee'] = currency_format($_SESSION['withdrawal']['fee']);
	$_SESSION['transaction']['currency_0_total'] = currency_format($_SESSION['withdrawal']['amount']);
	
	### new:
	$_SESSION['transaction']['net_value'] = currency_format($_SESSION['withdrawal']['amount'] - $_SESSION['withdrawal']['fee']);

		
		
    if($_SESSION['account']['currency_code_1']) {
		$_SESSION['transaction']['currency_1_iso3'] = $_SESSION['account']['currency_code_1'];
		$_SESSION['transaction']['currency_1_request'] = currency_format($_SESSION['withdrawal']['amount'] * $_SESSION['transaction']['ratio']);
		$_SESSION['transaction']['currency_1_total'] = currency_format($_SESSION['withdrawal']['amount'] * $_SESSION['transaction']['ratio']);
		$_SESSION['transaction']['currency_1_ratio'] = $_SESSION['transaction']['ratio'];
	}
	
	$_SESSION['transaction']['walletid'] = $_SESSION['withdrawal']['destination_banking_details']['walletid'];
    
    
    
   
    ##############################################################################
    ### ALWAYS RECORD ABOVE TRANSACTION: (ALWAYS SEND)
    $tmp_sql = "INSERT into transactions 
    (`transactionid`,
    `platform`,
    `hash`,
    `source`,
    `memberid`,
    `accountid`,
    `account_details`,
    `description`,
    `method`,
    `method_details`,
    `walletid`,
    `transaction_gross_value`,
    `fee_sponsor_value`,
    `fee_bonus_value`,
    `fee_network_value`,
    `fee_total_value`,
    `status`,
    `results`,
    `account_balance_before`,
    `available_balance_before`,
    `transaction_net_value`,
    `account_bonus_value`,
    `account_balance_after`,
    `available_balance_after`,
    `ratio`,
    `currency_0_iso3`,
    `currency_0_request`,
    `currency_0_fee`,
    `currency_0_total`,
    `currency_1_iso3`,
    `currency_1_request`,
    `currency_1_total`,
    `currency_1_ratio`,
    `memo`,
    `requested_datetime`,
    `updated_datetime`,
    `authorization`) 
    
    VALUES 
    
    ('" . $blank_id . "',
    '" . $tmp_platform . "',
    '" . $_SESSION['transaction']['hash'] . "',
    'WWW',
    '" . $_SESSION['member']['memberid'] . "',
    '" . $_SESSION['account']['accountid'] . "',
    '" . $_SESSION['accountdetails'] . "',
    'Withdrawal',
    'Bank Wire',
    '" . $_SESSION['transaction']['wire_instructions'] . "',
    '" . $_SESSION['transaction']['walletid'] . "',
    '" . $_SESSION['transaction']['gross_value'] . "',
    '" . $_SESSION['transaction']['fee_sponsor_value'] . "',
    '" . $_SESSION['transaction']['fee_bonus_value'] . "',
    '" . $_SESSION['transaction']['fee_network_value'] . "',
    '" . $_SESSION['transaction']['fee_total_value'] . "',
    '".  $_SESSION['transaction']['status'] . "',
    '" . $_SESSION['transaction']['results'] . "',
    '" . $_SESSION['transaction']['original_balance']['account'] . "',
    '" . $_SESSION['transaction']['original_balance']['available'] . "',
    '" . $_SESSION['transaction']['net_value'] . "',
    '" . $_SESSION['transaction']['account_bonus_value'] . "',
    '" . $_SESSION['transaction']['new_balance']['account'] . "',
    '" . $_SESSION['transaction']['new_balance']['available'] . "',
    '" . $_SESSION['transaction']['ratio'] . "',

    '" . $_SESSION['transaction']['currency_0_iso3'] . "',
    '" . $_SESSION['transaction']['currency_0_request'] . "',
    '" . $_SESSION['transaction']['currency_0_fee'] . "',
    '" . $_SESSION['transaction']['currency_0_total'] . "',
    
    '" . $_SESSION['transaction']['currency_1_iso3'] . "',
    '" . $_SESSION['transaction']['currency_1_request'] . "',
    '" . $_SESSION['transaction']['currency_1_total'] . "',
    '" . $_SESSION['transaction']['currency_1_ratio'] . "',
    '" . $memo . "',
    '" . $_SESSION['transaction']['datetime_requested'] . "',
    '" . $_SESSION['transaction']['datetime_updated'] . "',
    '" . $_SESSION['authorization']['voice_file'] . "');";
    
    //test("tmp_sql",$tmp_sql);
    
    $_SESSION['transaction']['transactionid'] = insertTHECASHIER($tmp_sql);
    
    test("_SESSION['transaction']['transactionid']",$_SESSION['transaction']['transactionid']);
    
    ### $email_alert_message  = "WITHDRAWAL:
    ### ACCOUNTID: " . $_SESSION['account']['accountid'] . "
    ### AMOUNT: " . currency_format($_SESSION['transaction']['gross_value']);
    ### email_alert($email_alert_message,"accounting@nsdb.com");

	### SET TRANSACTION STATUS:
	$_SESSION['transaction']['status'] = "Approved";


	if( $send_email != "NO") {
		#############################################################################
		### SEND AN EMAIL RECEIPT TO THE ACCOUNT HOLDER: ############
		#$email_transaction = "approved pending deposit";
		#include($_SESSION['template']['company']['file_path'] . "shared/email_admin_receipts.shared");
		$email_receipt = "approved_withdrawal_to_swift_account";
		include($_SESSION['template']['company']['file_path'] . "shared/email_receipts.shared");
		############################################################
		
		
		    
		## SYSMSG:
		$_SESSION['SYSMSG'] = "<span style='line-height:35px;'>
		<b>SUCCESS!</b><br>
		Your " . displayCURRENCY1($_SESSION['transaction']['requested_value']) . " withdrawal has been APPROVED!<br>
		A withdrawal receipt has been emailed to: ". $_SESSION['account']['emailaddress'] ."<br>
		<b>ALSO PLEASE NOTE:</b> you will receive a FOLLOW-UP CONFIRMATION (<u>within 24 hours</u>) when funds have been SENT!
		</span>";

	}
	
	
	### RESET MY SESSION:
	
	$_SESSION['member'] = "";
	$_SESSION['member'] = $tmp_admin_member;
	
	
	$_SESSION['account'] = "";
	$_SESSION['account'] = $tmp_admin_account;
}



function check_credit_cards_per_member_limit($memberid='',$new_credit_card_number='') {

	global $master_config_basic_limits_per_member_number_of_registered_creditcards;
	
	if(empty($new_credit_card_number)) return FALSE;
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	if(empty($memberid)) return FALSE;

	$tmp_sql = "SELECT * FROM wallets 
				WHERE memberid = '". $memberid ."'
				AND type != 'SWIFT'
				AND number = '". $new_credit_card_number ."'
				;";
	$card_already_exists = readTHECASHIER($tmp_sql);
	if(!empty($card_already_exists->walletid)) return "OK";
	
	$tmp_sql = "SELECT distinct(number) FROM wallets 
				WHERE memberid = '". $memberid ."'
				AND type != 'SWIFT'
				;";
	$results = arrayTHECASHIER($tmp_sql);
	$number_of_cards = count($results);
	if($number_of_cards >= $master_config_basic_limits_per_member_number_of_registered_creditcards) {
		return "LIMIT REACHED";
	} else {
		return "OK";
	}
}	



function generateGUID() {
   return sprintf('%04x', mt_rand(0, 0xffff));
}

function generateUUID() {
   return (generateGUID().generateGUID()."-".generateGUID()."-".generateGUID()."-".generateGUID()."-".generateGUID().generateGUID().generateGUID());
}


function get_dynamic_processing_profile($accountid='') {

	
	
	//test("accountid",$accountid);
	
	global $master_config_default_gateway;

	if($_COOKIE['sponsor_accountid']) $sponsor_accountid = $_COOKIE['sponsor_accountid'];
	
	

    
    if(is_array($_SESSION['account'])) {
    	if($_SESSION['account']['sponsor_accountid']) $sponsor_accountid = $_SESSION['account']['sponsor_accountid'];
    }
    
    if(is_array($_SESSION['member'])){
    	if($_SESSION['member']['sponsor_accountid']) $sponsor_accountid = $_SESSION['member']['sponsor_accountid'];
    }
	



	
	if(!empty($accountid)) {
		$sponsor_accountid = getTHECASHIER("SELECT sponsor_accountid FROM accounts WHERE accountid = '". $accountid ."';");
		$account_details = getTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';");
	}
	
	$sponsor_details = readTHECASHIER("SELECT * FROM affiliates WHERE hash = '". $sponsor_accountid ."';");
	
	if(
	(stristr($sponsor_details->associated_gateway,"ECP")) ||
	(stristr($account_details->gateway_profile,"ECP"))
	) {
		
		$dynamic_schedule['profile_name'] = "ECP";
		$dynamic_schedule['starting_fee'] = "12.9%";
		$dynamic_schedule['starting_payout_schedule'] = "30 Days";
		$dynamic_schedule['profile_html_table'] = "
	

<table style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center;'>
	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Merchant Rating:</b></nobr>
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Dynamic Processing Fee:</b></nobr>
			</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Dynamic Payout Schedule:</b></nobr>
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			99.0% - 100%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			12.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			30 Days
		</td>

	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			98.0 - 98.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			12.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			30 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			97.0 - 97.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			12.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			30 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			96.0 - 96.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			12.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			30 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			95.0 - 95.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			13.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			35 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			94.0 - 94.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			14.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			40 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			93.0 - 93.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			16.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			45 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			92.0 - 92.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			18.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			50 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			91.0 - 91.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			20.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			55 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			90.0 - 90.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			25.0%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			60 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#888888;'>
			< 90%
		</td><td colspan='2' style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#888888;'>
			(account deactivation and review)
		</td>
	</tr>
	
	
</table>";



	} else { /// DEFAULT
	
		$dynamic_schedule['profile_name'] = $master_config_default_gateway;
		$dynamic_schedule['starting_fee'] = number_format($master_config_business_transaction_fee_services*100,1)."%";
		$dynamic_schedule['starting_payout_schedule'] = $master_config_DTR. " Days";
		$dynamic_schedule['profile_html_table'] = "
	

<table style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center;'>
	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Merchant Rating:</b></nobr>
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Dynamic Processing Fee:</b></nobr>
			</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Dynamic Payout Schedule:</b></nobr>
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			99.0% - 100%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			9.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			15 Days
		</td>

	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			98.0 - 98.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			10.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			20 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			97.0 - 97.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			11.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			25 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			96.0 - 96.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			12.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			30 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			95.0 - 95.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			13.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			35 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			94.0 - 94.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			14.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			40 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			93.0 - 93.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			16.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			45 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			92.0 - 92.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			18.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			50 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			91.0 - 91.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			20.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			55 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			90.0 - 90.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			25.0%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			60 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#888888;'>
			< 90%
		</td><td colspan='2' style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#888888;'>
			(account deactivation and review)
		</td>
	</tr>
	
	
</table>";
	
	
	
	
	}
	
	return $dynamic_schedule;
	
}





function void_a_refund($transactionid) {
	
	$tmp_datetime = datetime();
	
	$the_three_transaction_details = get_the_three_transactions($transactionid);
	

	test("the_three_transaction_details",$the_three_transaction_details);
	


	/// TRANSLOG
	$tmp_sql = "
	UPDATE translog
	SET status = ''
	, datetime_updated = '". $tmp_datetime ."'
	WHERE translogid = '". $the_three_transaction_details['translog']['translogid'] ."';
	";
	test("tmp_sql",$tmp_sql);
	$update = updateTHECASHIER($tmp_sql);
	test("update translog",$update);

	/// set the correct status
	$status_reset = "Approved";
	if($the_three_transaction_details['deposit']['requested_datetime'] < date("Y-m-d H:i:s",strtotime("-".$the_three_transaction_details['incoming']['DTR'] ." days"))) {
		$status_reset = "Completed";
	}
	
	/// CUSTOMER DEPOSIT
	$tmp_sql = "
	UPDATE transactions
	SET status = '". $status_reset ."'
	,return_datetime = NULL
	,return_reason = NULL
	,return_account_balance_before = NULL
	,return_account_balance_after = NULL
	,return_available_balance_before = NULL
	,return_available_balance_after = NULL
	,return_effects_merchant_rating = NULL
	, updated_datetime = '". $tmp_datetime ."'
	WHERE transactionid = '". $the_three_transaction_details['deposit']['transactionid'] ."';
	";
	test("tmp_sql",$tmp_sql);
	$update = updateTHECASHIER($tmp_sql);
	test("CUSTOMER DEPOSIT",$update);

	/// CUSTOMER OUTGOING
	$tmp_sql = "
	UPDATE transactions
	SET status = '". $status_reset ."'
	,return_datetime = NULL
	,return_reason = NULL
	,return_account_balance_before = NULL
	,return_account_balance_after = NULL
	,return_available_balance_before = NULL
	,return_available_balance_after = NULL
	,return_effects_merchant_rating = NULL
	, updated_datetime = '". $tmp_datetime ."'
	WHERE transactionid = '". $the_three_transaction_details['outgoing']['transactionid'] ."';
	";
	test("tmp_sql",$tmp_sql);
	$update = updateTHECASHIER($tmp_sql);
	test("CUSTOMER OUTGOING",$update);
	
	/// BUSINESS INCOMING
	$tmp_sql = "
	UPDATE transactions
	SET status = '". $status_reset ."'
	,return_datetime = NULL
	,return_reason = NULL
	,return_account_balance_before = NULL
	,return_account_balance_after = NULL
	,return_available_balance_before = NULL
	,return_available_balance_after = NULL
	,return_effects_merchant_rating = NULL
	, updated_datetime = '". $tmp_datetime ."'
	WHERE transactionid = '". $the_three_transaction_details['incoming']['transactionid'] ."';
	";
	test("tmp_sql",$tmp_sql);
	$update = updateTHECASHIER($tmp_sql);
	test("BUSINESS INCOMING",$update);


	/// BUSINESS BALANCE
	$balance_before_update = balance($the_three_transaction_details['incoming']['accountid']);
	$new_account_balance = currency_format($balance_before_update['account_balance'] + $the_three_transaction_details['incoming']['transaction_net_value']);
	
	
	$tmp_sql = "
	UPDATE balances
	SET account_balance = '". $new_account_balance ."'
	, updated = '". $tmp_datetime ."'
	WHERE accountid = '". $the_three_transaction_details['incoming']['accountid'] ."'
	AND platform = 'BANGK.com'
	AND currency_iso3 = 'USD'
	;";
	test("tmp_sql",$tmp_sql);
	$update = updateTHECASHIER($tmp_sql);
	test("BUSINESS BALANCE",$update);
	
}



function country2iso3($country) {
	
	$country = trim($country);
	
	
	
	if(stristr($country,"united kingdom")) return "GBR";
	if(stristr($country,"UK")) return "GBR";
	if(stristr($country,"great britain")) return "GBR";
	if(stristr($country,"england")) return "GBR";
	
	if(stristr($country,"US")) return "USA";
	if(stristr($country,"United States")) return "USA";
	
	
	if(strlen($country)==3) return $country;
	
	return geo_data($country,"printable_name","iso3");	
	
	
	
}

function country2printable($country) {
	$country = trim($country);
	if(strlen($country)!=3) return $country;
	return geo_data($country,"iso3","printable_name");	
}



function clear_identities_and_wallets($business_accountid='',$creator_memberid='') {
	
	### GET MEMBERID
	if(
	(empty($creator_memberid)) &&
	(!empty($business_accountid))
	) {	
	
		$tmp_sql = "SELECT creator_memberid FROM accounts WHERE accountid = '". $business_accountid ."';";
		$creator_memberid = getTHECASHIER($tmp_sql);
		
	} else {
	
		$creator_memberid = $creator_memberid;
	
	}




	### IDS_PERSONAL 
	if(
	(!empty($creator_memberid))
	) {
	
		/// clear ids_personal
		$tmp_sql = "UPDATE ids_personal
		SET 
		status = 'CLEARED', 
		datetime_updated = '". datetime() ."'
		WHERE 
		memberid = '". $creator_memberid ."'
		AND (status = 'SUBMITTED' OR status LIKE '%HOLD%' OR status = 'VERIFIED')
		;";
		logger3("tmp_sql",$tmp_sql);
		$clear_old_submissions = updateTHECASHIER($tmp_sql);
		logger3("clear_old_submissions",$clear_old_submissions);
	}

	
	### IDS_BUSINESS & WALLET
	if(
	(!empty($creator_memberid))
	) {
	
		//test("clear_identities_and_wallets(): business_accountid",$business_accountid);
	
		/// clear ids_business
		$tmp_sql = "UPDATE ids_business
		SET 
		status = 'CLEARED', 
		datetime_updated = '". datetime() ."'
		WHERE 
		memberid = '". $creator_memberid ."'
		AND (status = 'SUBMITTED' OR status LIKE '%HOLD%' OR status = 'VERIFIED')
		;";
		//test("tmp_sql",$tmp_sql);
		$clear_old_submissions = updateTHECASHIER($tmp_sql);
		//test("clear_old_submissions",$clear_old_submissions);
		
		
		/// clear ids_business
		$tmp_sql = "UPDATE wallets
		SET 
		status = 'CLEARED', 
		datetime_updated = '". datetime() ."'
		WHERE 
		memberid = '". $creator_memberid ."'
		AND (status = 'SUBMITTED' OR status LIKE '%HOLD%' OR status = 'VERIFIED')
		;";
		//test("tmp_sql",$tmp_sql);
		$clear_old_submissions = updateTHECASHIER($tmp_sql);
		//test("clear_old_submissions",$clear_old_submissions);
	
	}
}



function get_ids_personal($memberid='',$accountid='',$account_hash="",$member_hash="", $multiple=false) {

	//test("memberid",$memberid);
	
	//test("multiple",$multiple);
	
	//test("_SERVER['HTTP_HOST']",$_SERVER['HTTP_HOST']);

	if(!empty($memberid)) $add_memberid = "AND memberid = '". $memberid ."'";
	if(!empty($accountid)) $add_accountid = "AND accountid = '". $accountid ."'";
	
	if(!empty($account_hash)) $add_account_hash = "AND account_hash = '". $account_hash ."'";
	if(!empty($member_hash)) $add_member_hash = "AND member_hash = '". $member_hash ."'";
	
	
	### CURRENT IDENTITY
	// $current_account_identity_details = "";
	// $tmp_sql = "SELECT * FROM ids_business 
	// WHERE 
	// accountid = '". $parent_accountid ."' 
	// AND 
	// (
	// (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL) OR
	// (business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
	// )
	// AND business_name = '". $tmp_account['accountname'] ."'
	// ;";
	 
	$current_account_identity_details = "";
	# $tmp_sql = "SELECT * FROM ids_personal 
	# WHERE 
	# photo_id_filename != '' 
	# AND photo_id_filename IS NOT NULL
	# AND (proof_of_residence_filename IS NULL OR proof_of_residence_filename = '')
	# $add_memberid
	# $add_accountid
	# $add_account_hash
	# $add_member_hash
	# AND datetime_created != ''
	# AND datetime_created != '0000-00-00 00:00:00'
	# ORDER BY datetime_created DESC
	# ;";		
	 
	 
	//test("tmp_sql",$tmp_sql);
	if($multiple == false){
		
		//test("got here",1);
		
		$tmp_sql = "SELECT * FROM ids_personal 
		WHERE (photo_id_filename != '' OR document_description != '')
		$add_memberid
		$add_accountid
		$add_account_hash
		$add_member_hash
		AND datetime_created != ''
		AND datetime_created != '0000-00-00 00:00:00'
		ORDER BY datetime_updated DESC
		LIMIT 1
		;";
		
		//test("tmp_sql",$tmp_sql);
		
		$tmp_ids_personal['current']['identity'] = object2array(readTHECASHIER($tmp_sql));
	}
	else{
		
		//test("got here",2);
		
		
		$tmp_sql = "SELECT * FROM ids_personal 
		WHERE (photo_id_filename != '' )
		$add_memberid
		$add_accountid
		$add_account_hash
		$add_member_hash
		AND datetime_created != ''
		AND datetime_created != '0000-00-00 00:00:00'
		ORDER BY datetime_updated ASC
		LIMIT 50
		;";
		
		//test("tmp_sql",$tmp_sql);
		//if(stristr($_SERVER['HTTP_HOST'],"intelitruth.intelitruth.com")) test("tmp_sql",$tmp_sql);
		
		$tmp_ids_personal['current']['identity'] = readArrayTHECASHIER($tmp_sql);
		
		//if(stristr($_SERVER['HTTP_HOST'],"intelitruth.intelitruth.com")) test("tmp_ids_personal['current']['identity']",$tmp_ids_personal['current']['identity']);
		
		
	}
	//test("zzz. tmp_account['current']['identity']",$tmp_account['current']['identity']);
	 
	### CURRENT LOCATION
	$verified_account_location_details = "";
	//$tmp_sql = "SELECT * FROM ids_business 
	//WHERE 
	//accountid = '". $parent_accountid ."' 
	//AND 
	//(
	//(proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL) OR 
	//(business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
	//)
	//AND business_name = '". $tmp_account['accountname'] ."'
	//;";
	 
	# $tmp_sql = "SELECT * FROM ids_personal 
	# WHERE 
	# (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
	# OR
	# (photo_id_filename IS NULL AND photo_id_filename != '')
	# $add_memberid
	# $add_accountid
	# AND datetime_created != ''
	# AND datetime_created != '0000-00-00 00:00:00'
	# ORDER BY datetime_updated DESC
	# ;";
		
	 
	# //test("tmp_sql",$tmp_sql);
	# if($multiple == false){
	# 	$tmp_sql = "SELECT * FROM ids_personal 
	# 	WHERE (proof_of_residence_filename != '' OR proof_of_residence_filename IS NOT NULL)
	# 	$add_memberid
	# 	$add_accountid
	# 	AND datetime_created != ''
	# 	AND datetime_created != '0000-00-00 00:00:00'
	# 	ORDER BY datetime_updated DESC
	# 	LIMIT 1;";
	# 	
	# 	$tmp_ids_personal['current']['location'] = object2array(readTHECASHIER($tmp_sql));
	# }
	# else{
	# 	
	# 	
	# 	$tmp_sql = "SELECT * FROM ids_personal 
	# 	WHERE (proof_of_residence_filename != '' OR proof_of_residence_filename IS NOT NULL)
	# 	
	# 	$add_memberid
	# 	$add_accountid
	# 	$add_account_hash
	# 	$add_member_hash
	# 	AND datetime_created != ''
	# 	AND datetime_created != '0000-00-00 00:00:00'
	# 	ORDER BY datetime_updated ASC
	# 	LIMIT 50;
	# 	";
	# 	
	# 	test("tmp_sql",$tmp_sql);
	# 	
	# 	$tmp_ids_personal['current']['location'] = readArrayTHECASHIER($tmp_sql);
	# 	
	# 	test("tmp_ids_personal",$tmp_ids_personal);
	# 	
	# 	
	# }
	# //test("tmp_account['current']['location']",$tmp_account['current']['location']);
	

	////////////////////////////////////////////////////////////////
	/// PROOF OF RESIDENCE
	$limit = 1;
	$where_document = "(proof_of_residence_filename != '' OR proof_of_residence_description != '')";
	if($multiple){ $limit = 50; $where_document = "proof_of_residence_filename != ''";}
	
	$tmp_sql = "SELECT * FROM ids_personal 
	WHERE $where_document
	
	$add_memberid
	$add_accountid
	$add_member_hash
	
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	 
	//test("tmp_sql",$tmp_sql);
	
	if($multiple) $tmp_ids_personal['current']['location'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_personal['current']['location'] = object2array(readTHECASHIER($tmp_sql));
	
	//test("tmp_ids_personal['current']['location']",$tmp_ids_personal['current']['residence']);	
	
	
	
	return $tmp_ids_personal;
}

function get_ids_personal_document($memberid='',$accountid='',$account_hash="",$member_hash="") {

	logger3("memberid",$memberid);

	if(!empty($memberid)) $add_memberid = "AND memberid = '". $memberid ."'";
	if(!empty($accountid)) $add_accountid = "AND accountid = '". $accountid ."'";
	
	if(!empty($account_hash)) $add_account_hash = "AND account_hash = '". $account_hash ."'";
	if(!empty($member_hash)) $add_member_hash = "AND member_hash = '". $member_hash ."'";
	
		
	$tmp_sql = "SELECT * FROM ids_personal 
	WHERE document_description != ''
	
	$add_memberid
	$add_accountid
	$add_account_hash
	$add_member_hash
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_updated DESC
	LIMIT 1
	;";
	 
	 
	//test("tmp_sql",$tmp_sql);
	$tmp_ids_personal['current']['identity'] = object2array(readTHECASHIER($tmp_sql));
	//test("zzz. tmp_account['current']['identity']",$tmp_account['current']['identity']);	 	

	//if(stristr($_SERVER['HTTP_HOST'],"intelitruth.intelitruth.com")) test("tmp_ids_personal['current']['identity']",$tmp_ids_personal['current']['identity']);




	////////////////////////////////////////////////////////////////
	/// PROOF OF RESIDENCE
	$tmp_sql = "SELECT * FROM ids_personal 
	WHERE (proof_of_residence_description != '' AND proof_of_residence_description IS NOT NULL)
	
	$add_memberid
	$add_accountid
	$add_account_hash
	$add_member_hash
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	 
	//test("tmp_sql",$tmp_sql);
	$tmp_ids_personal['current']['location'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_personal['current']['location']",$tmp_ids_personal['current']['tax_returns']);	
	////////////////////////////////////////////////////////////////



	
	return $tmp_ids_personal;
}

function get_ids_business($memberid='',$accountid='',$account_hash="", $multiple=false) {


	# test("memberid",$memberid);
	# 
	# test("accountid",$accountid);
	# 
	# test("account_hash",$account_hash);
	# 
	# test("multiple",$multiple);
	
	
	//exit;
	// get business type
	if(!empty($accountid)) {
		
		$business_details = readTHECASHIER("SELECT * FROM accounts 
											WHERE accountid = '". $accountid ."'
											AND accountid != ''
											AND accountid != '0'
											;");
		
		if(stristr($business_details->business_type,"PDB")) {
			$ids_personal_details = get_ids_personal($memberid=$business_details->creator_memberid,$accountid='');
			//exit;
		}
	}



	if(!empty($memberid)) $add_memberid = "	AND memberid = '". $memberid ."' 
											AND memberid != ''
											AND memberid != '0'
											";
	if(!empty($accountid)) $add_accountid = "AND accountid = '". $accountid ."' 
											AND accountid != ''
											AND accountid != '0'
											";
	if(!empty($account_hash)) $add_account_hash = "AND account_hash = '". $account_hash ."' 
											AND account_hash != ''
											AND account_hash != '0'
											";
	
	
	### CURRENT IDENTITY
	// $current_account_identity_details = "";
	// $tmp_sql = "SELECT * FROM ids_business 
	// WHERE 
	// accountid = '". $parent_accountid ."' 
	// AND 
	// (
	// (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL) OR
	// (business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
	// )
	// AND business_name = '". $tmp_account['accountname'] ."'
	// ;";
	 
	$current_account_identity_details = "";
	// $tmp_sql = "SELECT * FROM ids_business 
	// WHERE 
	// business_certificate_filename != '' 
	// AND business_certificate_filename IS NOT NULL
	// AND (proof_of_business_location_filename IS NULL OR proof_of_business_location_filename = '')
	// $add_memberid
	// $add_accountid
	// ORDER BY datetime_created DESC
	// ;";
	
	$limit = 1;
	$where_document = "(business_certificate_filename != '' OR document_description != '')";
	if($multiple){ $limit = 50; $where_document = "business_certificate_filename != ''";}
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE $where_document
	$add_account_hash
	$add_memberid
	$add_accountid
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	logger3("tmp_sql",$tmp_sql);
	 
	//if($accountid == 5538) test("get_ids_business(): tmp_sql",$tmp_sql);
	 
	logger3("tmp_sql",$tmp_sql);
	if($multiple) $tmp_ids_business['current']['identity'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_business['current']['identity'] = object2array(readTHECASHIER($tmp_sql));
	//test("zzz. tmp_account['current']['identity']",$tmp_account['current']['identity']);
	 
	//exit;
	
	
	### CURRENT LOCATION
	# $verified_account_location_details = "";
	//$tmp_sql = "SELECT * FROM ids_business 
	//WHERE 
	//accountid = '". $parent_accountid ."' 
	//AND 
	//(
	//(proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL) OR 
	//(business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
	//)
	//AND business_name = '". $tmp_account['accountname'] ."'
	//;";
	 
	// $tmp_sql = "SELECT * FROM ids_business 
	// WHERE 
	// proof_of_business_location_filename != '' 
	// AND proof_of_business_location_filename IS NOT NULL
	// AND (business_certificate_filename IS NULL OR business_certificate_filename = '')
	// $add_memberid
	// $add_accountid
	// ORDER BY datetime_created DESC
	// ;";
	
	// $tmp_sql = "SELECT * FROM ids_business 
	// WHERE 
	// proof_of_business_location_filename != '' 
	// AND proof_of_business_location_filename IS NOT NULL
	// $add_memberid
	// $add_accountid
	// AND datetime_created != ''
	// AND datetime_created != '0000-00-00 00:00:00'
	// ORDER BY datetime_created DESC
	// ;";
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 1 (COMPANY DOCUMENT)
	
	$limit = 1;
	$where_document = "(proof_of_business_location_filename != '' OR business_address_1 != '')";
	if($multiple){ $limit = 50; $where_document = "proof_of_business_location_filename != ''";}
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE $where_document
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	
	
	logger3("tmp_sql",$tmp_sql);
	if($multiple) $tmp_ids_business['current']['location'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_business['current']['location'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_account['current']['location']",$tmp_account['current']['location']);
	
	if(!empty($ids_personal_details)) {
		
		$tmp_ids_business['current']['identity']['status'] = $ids_personal_details['current']['identity']['status'];
		$tmp_ids_business['current']['location'] = $ids_personal_details['current']['location'];
	}
	
	
	### CURRENT PRICING
	# $verified_account_pricing_details = "";	 
	# $tmp_sql = "SELECT * FROM ids_business 
	# WHERE proof_of_pricing_filename != '' 
	# AND proof_of_pricing_filename IS NOT NULL
	# $add_memberid
	# $add_accountid
	# AND datetime_created != ''
	# AND datetime_created != '0000-00-00 00:00:00'
	# ORDER BY datetime_created DESC
	# LIMIT 1
	# ;";
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 2 (PRICING)
	$limit = 1;
	$where_document = "(proof_of_pricing_filename != '' OR proof_of_pricing_description != '')";
	if($multiple){ $limit = 50; $where_document = "proof_of_pricing_filename != ''";}
	
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE $where_document
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	 
	logger3("tmp_sql",$tmp_sql);
	if($multiple) $tmp_ids_business['current']['pricing'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_business['current']['pricing'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['pricing']",$tmp_ids_business['current']['pricing']);


	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 2B (TAX RETURNS)
	$limit = 1;
	$where_document = "(proof_of_tax_returns_filename != '' OR proof_of_tax_returns_description != '')";
	if($multiple){ $limit = 50; $where_document = "proof_of_tax_returns_filename != ''";}
	
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE $where_document
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	 
	logger3("tmp_sql",$tmp_sql);
	if($multiple) $tmp_ids_business['current']['tax_returns'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_business['current']['tax_returns'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['tax_returns']",$tmp_ids_business['current']['tax_returns']);
	
	
	
	

	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 2C (PROCESSING)
	$limit = 1;
	$where_document = "(proof_of_processing_filename != '' OR proof_of_processing_description != '')";
	if($multiple){ $limit = 50; $where_document = "proof_of_processing_filename != ''";}
	
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE $where_document
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	 
	//test("tmp_sql",$tmp_sql);
	if($multiple) $tmp_ids_business['current']['processing'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_business['current']['processing'] = object2array(readTHECASHIER($tmp_sql));
	//test("tmp_ids_business['current']['processing']",$tmp_ids_business['current']['processing']);
	
	
	////////////////////////////////////////////////////////////////
	/// SIGNATURE
	$limit = 1;
	$where_document = "(signature_filename != '')";
	if($multiple){ $limit = 50; $where_document = "signature_filename != ''";}
	
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE $where_document
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	 
	//test("tmp_sql",$tmp_sql);
	if($multiple) $tmp_ids_business['current']['signature'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_business['current']['signature'] = object2array(readTHECASHIER($tmp_sql));
	//test("tmp_ids_business['current']['signature']",$tmp_ids_business['current']['signature']);
	
	
	
	
	

	### [CURRENT][PROOF_OF_BUSINESS_3]
	# $verified_account_business_3_details = "";	 
	# $tmp_sql = "SELECT * FROM ids_business 
	# WHERE proof_of_pricing_filename != '' 
	# AND proof_of_pricing_filename IS NOT NULL
	# $add_memberid
	# $add_accountid
	# AND datetime_created != ''
	# AND datetime_created != '0000-00-00 00:00:00'
	# ORDER BY datetime_created DESC
	# LIMIT 1
	# ;";
	
	
		
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 3 (MORE DETAILS # 1)
	$limit = 1;
	$where_document = "(proof_of_business_3_filename != '' OR proof_of_business_3_description != '')";
	if($multiple){ $limit = 50; $where_document = "proof_of_business_3_filename != ''";}
	
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE $where_document
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	 
	logger3("tmp_sql",$tmp_sql);
	if($multiple) $tmp_ids_business['current']['proof_of_business_3'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_business['current']['proof_of_business_3'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_3']",$tmp_ids_business['current']['proof_of_business_3']);
	
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 4 (MORE DETAILS # 2)
	$limit = 1;
	$where_document = "(proof_of_business_4_filename != '' OR proof_of_business_4_description != '')";
	if($multiple){ $limit = 50; $where_document = "proof_of_business_4_filename != ''";}
	
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE $where_document
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	logger3("tmp_sql",$tmp_sql);
	if($multiple) $tmp_ids_business['current']['proof_of_business_4'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_business['current']['proof_of_business_4'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_4']",$tmp_ids_business['current']['proof_of_business_4']);


	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 5 (MORE DETAILS # 3)
	$limit = 1;
	$where_document = "(proof_of_business_5_filename != '' OR proof_of_business_5_description != '')";
	if($multiple){ $limit = 50; $where_document = "proof_of_business_5_filename != ''";}
	
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE
	
	(proof_of_business_5_description != ''
	OR 
	proof_of_business_5_filename != '')
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	logger3("tmp_sql",$tmp_sql);
	if($multiple) $tmp_ids_business['current']['proof_of_business_5'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_business['current']['proof_of_business_5'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_5']",$tmp_ids_business['current']['proof_of_business_5']);
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 6 (MORE DETAILS # 4)
	$limit = 1;
	$where_document = "(proof_of_business_6_filename != '' OR proof_of_business_6_description != '')";
	if($multiple){ $limit = 50; $where_document = "proof_of_business_6_filename != ''";}
	
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE $where_document
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	logger3("tmp_sql",$tmp_sql);
	if($multiple) $tmp_ids_business['current']['proof_of_business_6'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_business['current']['proof_of_business_6'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_6']",$tmp_ids_business['current']['proof_of_business_6']);
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 7 (MORE DETAILS # 5)
	$limit = 1;
	$where_document = "(proof_of_business_7_filename != '' OR proof_of_business_7_description != '')";
	if($multiple){ $limit = 50; $where_document = "proof_of_business_7_filename != ''";}
	
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE $where_document
		
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created ASC
	LIMIT $limit
	;";
	logger3("tmp_sql",$tmp_sql);
	if($multiple) $tmp_ids_business['current']['proof_of_business_7'] = readArrayTHECASHIER($tmp_sql);
	else $tmp_ids_business['current']['proof_of_business_7'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_7']",$tmp_ids_business['current']['proof_of_business_7']);


	//$tmp_ids_business = get_ids_personal($memberid=$business_owner_memberid,$accountid='');
	
	
	/*
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS (ADDITIONAL DOCUMNENTS)
	$tmp_sql = "SELECT * FROM KYC_additional_documents_options 
	WHERE account_hash = 
	
	AND status != 'TRASH'
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	 
	logger3("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['proof_of_business_3'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_3']",$tmp_ids_business['current']['proof_of_business_3']);
	
	*/
	
	
	
	
	
	
	return $tmp_ids_business;
}





function get_ids_business_document($memberid='',$accountid='',$account_hash="") {


	//test("accountid",$accountid);
	//exit;
	// get business type
	if(!empty($accountid)) {
		
		$business_details = readTHECASHIER("SELECT * FROM accounts 
											WHERE accountid = '". $accountid ."'
											AND accountid != ''
											AND accountid != '0'
											;");
		
		if(stristr($business_details->business_type,"PDB")) {
			$ids_personal_details = get_ids_personal($memberid=$business_details->creator_memberid,$accountid='');
			//exit;
		}
	}



	if(!empty($memberid)) $add_memberid = "	AND memberid = '". $memberid ."' 
											AND memberid != ''
											AND memberid != '0'
											";
	if(!empty($accountid)) $add_accountid = "AND accountid = '". $accountid ."' 
											AND accountid != ''
											AND accountid != '0'
											";
	if(!empty($account_hash)) $add_account_hash = "AND account_hash = '". $account_hash ."' 
											AND account_hash != ''
											AND account_hash != '0'
											";	
	
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE document_description != '' 
	$add_account_hash
	$add_memberid
	$add_accountid
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	logger3("tmp_sql",$tmp_sql);
	 
	//if($accountid == 5538) test("get_ids_business(): tmp_sql",$tmp_sql);
	 
	logger3("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['identity'] = object2array(readTHECASHIER($tmp_sql));
	//test("zzz. tmp_account['current']['identity']",$tmp_account['current']['identity']);
	 
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 1 (COMPANY DOCUMENT)
	
	
	if(!empty($ids_personal_details)) {
		
		$tmp_ids_business['current']['identity']['status'] = $ids_personal_details['current']['identity']['status'];		
	}
		
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 2 (PRICING)
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE proof_of_pricing_description != ''
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	 
	logger3("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['pricing'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['pricing']",$tmp_ids_business['current']['pricing']);	



	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 2B (TAX RETURNS)
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE proof_of_tax_returns_description != ''
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	 
	logger3("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['tax_returns'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['tax_returns']",$tmp_ids_business['current']['tax_returns']);	
	
	
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 2C (PROCESSING)
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE proof_of_processing_description != ''
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	 
	//test("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['processing'] = object2array(readTHECASHIER($tmp_sql));
	//test("tmp_ids_business['current']['processing']",$tmp_ids_business['current']['processing']);	
	
	
		
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 3 (MORE DETAILS # 1)
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE proof_of_business_3_description != ''
		
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	 
	logger3("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['proof_of_business_3'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_3']",$tmp_ids_business['current']['proof_of_business_3']);
	
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 4 (MORE DETAILS # 2)
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE proof_of_business_4_description != '' 
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	logger3("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['proof_of_business_4'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_4']",$tmp_ids_business['current']['proof_of_business_4']);


	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 5 (MORE DETAILS # 3)
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE proof_of_business_5_description != '' 
		
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	logger3("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['proof_of_business_5'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_5']",$tmp_ids_business['current']['proof_of_business_5']);
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 6 (MORE DETAILS # 4)
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE proof_of_business_6_description != '' 
	
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	logger3("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['proof_of_business_6'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_6']",$tmp_ids_business['current']['proof_of_business_6']);
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS 7 (MORE DETAILS # 5)
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE proof_of_business_7_description != '' 
		
	$add_account_hash
	$add_memberid
	$add_accountid
	
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	logger3("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['proof_of_business_7'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_7']",$tmp_ids_business['current']['proof_of_business_7']);


	//$tmp_ids_business = get_ids_personal($memberid=$business_owner_memberid,$accountid='');
	
	
	/*
	
	////////////////////////////////////////////////////////////////
	/// PROOF OF BUSINESS (ADDITIONAL DOCUMNENTS)
	$tmp_sql = "SELECT * FROM KYC_additional_documents_options 
	WHERE account_hash = 
	
	AND datetime_created != ''
	AND datetime_created != '0000-00-00 00:00:00'
	ORDER BY datetime_created DESC
	LIMIT 1
	;";
	 
	logger3("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['proof_of_business_3'] = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_ids_business['current']['proof_of_business_3']",$tmp_ids_business['current']['proof_of_business_3']);
	
	*/
	
	return $tmp_ids_business;
}


function get_ids_unified($member_hash="",$account_hash="") {
	
	
	logger3("get_ids_unified(member_hash)",$member_hash);
	logger3("get_ids_unified(account_hash)",$account_hash);
	
	
	
	//--------------------------------------------------------------------------------------
	// GET ACCOUNT_HASH
	//--------------------------------------------------------------------------------------
	
	if(
		($member_hash)
		&& (!$account_hash)
	) {
		
		$tmp_sql = "SELECT memberid 
					FROM members 
					WHERE hash = '". $member_hash ."'
					;";
		logger3("tmp_sql",$tmp_sql);
		$memberid = getTHECASHIER($tmp_sql);
		logger3("memberid",$memberid);
		
		$tmp_sql = "SELECT hash 
					FROM accounts 
					WHERE creator_memberid = '". $memberid ."'
					AND accounttype = 'BUSINESS'
					ORDER BY created
					LIMIT 1
					;";
		logger3("tmp_sql",$tmp_sql);
		$account_hash = getTHECASHIER($tmp_sql);
		logger3("account_hash",$account_hash);		
	}
	
	//--------------------------------------------------------------------------------------
	/// GET MEMBER_HASH
	//--------------------------------------------------------------------------------------
	
	if(
		(!$member_hash)
		&& ($account_hash)
	) {
		
		$tmp_sql = "SELECT creator_memberid 
					FROM accounts 
					WHERE hash = '". $account_hash ."'
					;";
		logger3("tmp_sql",$tmp_sql);
		$memberid = getTHECASHIER($tmp_sql);
		logger3("memberid",$memberid);
		
		$tmp_sql = "SELECT hash 
					FROM members 
					WHERE memberid = '". $memberid ."'
					;";
		logger3("tmp_sql",$tmp_sql);
		$member_hash = getTHECASHIER($tmp_sql);
		logger3("member_hash",$member_hash);	
	}


	//--------------------------------------------------------------------------------------
	/// PERSONAL
	//--------------------------------------------------------------------------------------

	/// personal SELFIE filenames,hash
	$tmp_sql = "SELECT selfie_filename,hash 
				FROM ids_personal
				WHERE member_hash = '". $member_hash ."'
				AND selfie_filename != ''
				AND selfie_filename IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['selfie']['filenames'] = readarrayTHECASHIER($tmp_sql);	
	logger3("return['selfie']['filenames']",$return['selfie']['filenames']);

	
	/// personal ID descriptions
	$tmp_sql = "SELECT document_description,hash
				FROM ids_personal
				WHERE member_hash = '". $member_hash ."'
				AND document_description != ''
				AND document_description IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['identity']['description'] = readarrayTHECASHIER($tmp_sql);
	logger3("return['identity']['description']",$return['identity']['description']);
	
	
	/// personal ID filenames
	$tmp_sql = "SELECT photo_id_filename,hash
				FROM ids_personal
				WHERE member_hash = '". $member_hash ."'
				AND photo_id_filename != ''
				AND photo_id_filename IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['identity']['filenames'] = readarrayTHECASHIER($tmp_sql);
	logger3("return['identity']['filenames']",$return['identity']['filenames']);
	
	
	/// personal RESIDENCE descriptions
	$tmp_sql = "SELECT proof_of_residence_description,hash
				FROM ids_personal
				WHERE member_hash = '". $member_hash ."'
				AND proof_of_residence_description != ''
				AND proof_of_residence_description IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['location']['description'] = readarrayTHECASHIER($tmp_sql);
	logger3("return['location']['description']",$return['location']['description']);
	
	
	/// personal RESIDENCE filenames
	$tmp_sql = "SELECT proof_of_residence_filename,hash
				FROM ids_personal 
				WHERE member_hash = '". $member_hash ."'
				AND proof_of_residence_filename != ''
				AND proof_of_residence_filename IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['location']['filenames'] = readarrayTHECASHIER($tmp_sql);
	logger3("return['location']['filenames']",$return['location']['filenames']);
	
	$personal = $return;
	$return = "";
	
	//--------------------------------------------------------------------------------------
	// BUSINESS
	//--------------------------------------------------------------------------------------
	
	
	/// business CERIFICATES descriptions
	$tmp_sql = "SELECT document_description,hash
				FROM ids_business
				WHERE account_hash = '". $account_hash ."'
				AND document_description != ''
				AND document_description IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['identity']['description'] = readarrayTHECASHIER($tmp_sql);
	logger3("return['identity']['description']",$return['identity']['description']);
	
	
	/// business CERIFICATES filenames
	$tmp_sql = "SELECT business_certificate_filename,hash
				FROM ids_business
				WHERE account_hash = '". $account_hash ."'
				AND business_certificate_filename != ''
				AND business_certificate_filename IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['identity']['filenames'] = readarrayTHECASHIER($tmp_sql);
	logger3("return['identity']['filenames']",$return['identity']['filenames']);
	
	

	/// business PRICING descriptions
	$tmp_sql = "SELECT proof_of_pricing_description,hash
				FROM ids_business 
				WHERE account_hash = '". $account_hash ."'
				AND proof_of_pricing_description != ''
				AND proof_of_pricing_description IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['pricing']['description'] = readarrayTHECASHIER($tmp_sql);
	logger3("return['pricing']['description']",$return['pricing']['description']);
	
	
	/// business PRICING filenames
	$tmp_sql = "SELECT proof_of_pricing_filename,hash 
				FROM ids_business
				WHERE account_hash = '". $account_hash ."'
				AND proof_of_pricing_filename != ''
				AND proof_of_pricing_filename IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['pricing']['filenames'] = readarrayTHECASHIER($tmp_sql);
	logger3("return['pricing']['filenames']",$return['pricing']['filenames']);


	/// business PROCESSING descriptions
	$tmp_sql = "SELECT proof_of_processing_description,hash 
				FROM ids_business
				WHERE account_hash = '". $account_hash ."'
				AND proof_of_processing_description != ''
				AND proof_of_processing_description IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['processing']['description'] = readarrayTHECASHIER($tmp_sql);
	logger3("return['processing']['description']",$return['processing']['description']);
	
	
	/// business PROCESSING filenames
	$tmp_sql = "SELECT proof_of_processing_filename,hash 
				FROM ids_business
				WHERE account_hash = '". $account_hash ."'
				AND proof_of_processing_filename != ''
				AND proof_of_processing_filename IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['processing']['filenames'] = readarrayTHECASHIER($tmp_sql);	
	logger3("return['processing']['filenames']",$return['processing']['filenames']);


	/// business TAX RETURNS descriptions
	$tmp_sql = "SELECT proof_of_tax_returns_description,hash 
				FROM ids_business
				WHERE account_hash = '". $account_hash ."'
				AND proof_of_tax_returns_description != ''
				AND proof_of_tax_returns_description IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['tax_returns']['description'] = readarrayTHECASHIER($tmp_sql);
	logger3("return['tax_returns']['description']",$return['tax_returns']['description']);
	
	
	/// business TAX RETURNS filenames
	$tmp_sql = "SELECT proof_of_tax_returns_filename,hash 
				FROM ids_business
				WHERE account_hash = '". $account_hash ."'
				AND proof_of_tax_returns_filename != ''
				AND proof_of_tax_returns_filename IS NOT NULL
				AND datetime_created != ''
				AND datetime_created != '0000-00-00 00:00:00'
				ORDER BY datetime_created ASC
				;";
	logger3("tmp_sql",$tmp_sql);
	$return['tax_returns']['filenames'] = readarrayTHECASHIER($tmp_sql);
	logger3("return['tax_returns']['filenames']",$return['tax_returns']['filenames']);

	$business = $return;
	$return = "";
	
	$final_return['personal'] = $personal;
	$final_return['business'] = $business;
	
	return $final_return;
	
	/*
				
				///  LEGACY REFERENCE
				
				$tmp_ids_personal['current']['selfie']
				$tmp_ids_personal['current']['identity']
				$tmp_ids_personal['current']['location']
				
				$tmp_ids_business['current']['identity']
				$tmp_ids_business['current']['location']
				$tmp_ids_business['current']['pricing']
				$tmp_ids_business['current']['tax_returns']
				$tmp_ids_business['current']['processing']
				
				///  NEW
			
				$ids_unified_details['selfie']['filenames']
				
				$ids_unified_details['identity']['description']
				$ids_unified_details['identity']['filenames']
				
				$ids_unified_details['location']['description']
				$ids_unified_details['location']['filenames']
				
				$ids_unified_details['identity']['description']
				$ids_unified_details['identity']['filenames']
				
				$ids_unified_details['pricing']['description']
				$ids_unified_details['pricing']['filenames']
				
				$ids_unified_details['processing']['description']
				$ids_unified_details['processing']['filenames']
				
				$ids_unified_details['tax_returns']['description']
				$ids_unified_details['tax_returns']['filenames']

			*/
	
}





function is_this_business_account_verified($business_accountid,$qualified="") {
	
	$tmp_ids_business = get_ids_business($memberid='',$accountid=$business_accountid);
	//test("tmp_ids_business",$tmp_ids_business);
	
	$tmp_sql = "SELECT creator_memberid FROM accounts WHERE accountid = '". $business_accountid ."';";
	$business_owner_memberid = getTHECASHIER($tmp_sql);
	$tmp_ids_personal = get_ids_personal($memberid=$business_owner_memberid,$accountid='');
	//test("tmp_ids_personal",$tmp_ids_personal);
	
	
	if($qualified) {
		
		if(
		(stristr($tmp_ids_business['current']['identity']['status'],'SUBMITTED')) ||
		(stristr($tmp_ids_business['current']['identity']['status'],'VERIFIED'))
		) {
			return "VERIFIED";
		} else {
			return FALSE;
		}	
	}
	
	
	if(
	(stristr($tmp_ids_personal['current']['identity']['status'],'VERIFIED')) &&
	(stristr($tmp_ids_personal['current']['location']['status'],'VERIFIED')) &&
	(stristr($tmp_ids_business['current']['identity']['status'],'VERIFIED')) &&
	(stristr($tmp_ids_business['current']['location']['status'],'VERIFIED'))
	) {
		return "VERIFIED";
	} else {
		return FALSE;
	}
}

function authorization_template_original_text_to_html($original_text) {
		
		/// clear for testing:
		//$_SESSION['voice_authorization_api'] = "";
		
		//test("1. original_text",$original_text);
	
		###
		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_AMOUNT'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_AMOUNT'] = "<span style='color:#888888;'>[amount]</span>";
		}
		
		
		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_RECURRING_AMOUNT'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_RECURRING_AMOUNT'] = "<span style='color:#888888;'>[amount_recurring]</span>";
		}
		
		
		
		if(isset($_SESSION['voice_authorization_api']['business_account_details'])) {
			$business_subcategory = MCC2TEXT($_SESSION['voice_authorization_api']['business_account_details']['business_subcategory']);
		} else {
			$business_subcategory = MCC2TEXT($_SESSION['account']['business_subcategory']);
		}
		
		
		
		
		
		### If GATEWAY:
		logger3("_SESSION['template']['company']['text_name']",$_SESSION['template']['company']['text_name']);
		logger3("business_subcategory",$business_subcategory);
		logger3("_SESSION['voice_authorization_api']['business_account_details']['business_subcategory']",$_SESSION['voice_authorization_api']['business_account_details']['business_subcategory']);
		logger3("_SESSION['voice_authorization_api']['business_account_details']['business_category']",$__SESSION['voice_authorization_api']['business_account_details']['business_category']);
		logger3("_SESSION['account']['business_subcategory']",$_SESSION['account']['business_subcategory']);
		
		if(
		(stristr($_SESSION['template']['company']['text_name'],"vSIGN")) &&
		(
		(stristr($business_subcategory,"GATEWAY")) ||
		(stristr($_SESSION['voice_authorization_api']['business_account_details']['business_subcategory'],"GATEWAY")) ||
		(stristr($_SESSION['voice_authorization_api']['business_account_details']['business_category'],"GATEWAY")) ||
		(stristr($_SESSION['account']['business_subcategory'],"GATEWAY"))
		)
		
		) {

			//test("2. business_subcategory",$business_subcategory);
			/// POSSIBLE GATEWAY VARS:
			
			logger3("2. _SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']);
			
			//$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']
			
			
			//test("2. _SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);
			//exit;
			
			/// set account business name
			$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'] = $_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME'];
			
			if(!empty($_SESSION['incoming_api_session']['GATEWAY_MERCHANT_NAME'])) {
				
				$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'] = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_NAME'];
					
			}
			
			logger3("_SESSION['voice_authorization_api']",$_SESSION['incoming_authorization_api']);
			
			
			
			
			if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'])) {
				$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'] = "<span style='color:#888888;'>[merchant name]</span>";
			}
			
			
			$submerchant_account_details = account($_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_MID']);
			
			
			if($submerchant_account_details['business_subcategory']) $_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'] = $submerchant_account_details['business_subcategory'];
			
			
			
			if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'])) {
				$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'] = "<span style='color:#888888;'>[merchant category]</span>";
			}
		

			if(!empty($_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC'])) {
				
				$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'] = MCC2TEXT($_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC']);
					
			}
		
		
		
		} else { ///nomral:
		
			//test("_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME']",$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME']);
			
			/// set account business name
			if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'])) {
			
				$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'] = "<span style='font-size:105%;'>". $_SESSION['account']['accountname'] ." ". $_SESSION['account']['business_type'] ."</span>";
			
			}
			
			global $business_account_details;
			
			//test("business_account_details",$business_account_details);
			
			
			
			if(!empty($business_account_details)) {
				
				$tmp_merchant_AUTHORIZATION_BUSINESS_CATEGORY = MCC2TEXT($business_account_details['business_subcategory']);
				
			} else {
				
				$tmp_merchant_AUTHORIZATION_BUSINESS_CATEGORY = MCC2TEXT($_SESSION['account']['business_subcategory']); //  ." ". $_SESSION['account']['business_category'];
				
			}
			
			
			$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'] = strtolower($tmp_merchant_AUTHORIZATION_BUSINESS_CATEGORY);
			
			
		}
		
		//AUTHORIZATION_BUSINESS_CATEGORY
		
		
		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'] = "<span style='color:#888888;'>[customer name]</span>";
		}

		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TIME'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TIME'] = "<span style='color:#888888;'>[time of authorization]</span>";
		}
			
		
		//$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_FIRST_DIGIT'] = "";
		
		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_LAST4_DIGITS'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_LAST4_DIGITS'] = "<span style='color:#888888;'>[last 4 digits]</span>";
		}
		
		// not an api paramater -- only for template transalation.  get brand from first-digit
		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_BRAND'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_BRAND'] = "<span style='color:#888888;'>[card brand]</span>";
		}
		




                if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_PASSPHRASE'])){
                    $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_PASSPHRASE'] = "<span style='color:#888888;' id='customer_secret_passphrase'>[customer secret passphrase]</span>";
                }




		###
		$original_text = str_replace("AUTHORIZATION_AMOUNT","$". $_SESSION['voice_authorization_api']['AUTHORIZATION_AMOUNT'],$original_text);
		$original_text = str_replace("AUTHORIZATION_RECURRING_AMOUNT","$". $_SESSION['voice_authorization_api']['AUTHORIZATION_RECURRING_AMOUNT'],$original_text);
		
		
		$tmp_AUTHORIZATION_BUSINESS_NAME = trim($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME']);
		$original_text = str_replace("AUTHORIZATION_BUSINESS_NAME",$tmp_AUTHORIZATION_BUSINESS_NAME,$original_text);
		
		
		## test("_SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);
		## 
		## AUTHORIZATION_MERCHANT_CATEGORY
		## 
		## AUTHORIZATION_BUSINESS_CATEGORY
		
		
		### SET BUSINESS CTEGORY
		if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'])) $tmp_category = $_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'];
		
		if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_CATEGORY'])) $tmp_category = $_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_CATEGORY'];
		
		if(!empty($_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC'])) $tmp_category = MCC2TEXT($_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC']);
		
		//test("_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC']",$_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC']);
		
		
		if(!empty($tmp_category)) {
			
			$original_text = str_replace("AUTHORIZATION_BUSINESS_CATEGORY",$tmp_category,$original_text);
		}
		
		
		

		$original_text = str_replace("AUTHORIZATION_CUSTOMER_NAME",$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'],$original_text);
		
		
		$original_text = str_replace("AUTHORIZATION_CUSTOMER_TIME",$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TIME'],$original_text);
		//$original_text = str_replace("AUTHORIZATION_CARD_FIRST_DIGIT",$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_FIRST_DIGIT'],$original_text);
		$original_text = str_replace("AUTHORIZATION_CARD_LAST4_DIGITS",$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_LAST4_DIGITS'],$original_text);
		$original_text = str_replace("AUTHORIZATION_CARD_BRAND",$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_BRAND'],$original_text);

		$original_text = str_replace("AUTHORIZATION_CUSTOMER_PASSPHRASE",$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_PASSPHRASE'],$original_text);
        
        
        
        $original_text = str_replace("[speak your secret passphrase]","<span style='color:#E77D76;'>[speak your secret passphrase]</span>",$original_text);

		###
		$original_text = str_replace("\\n","<br>",$original_text);
		$original_text = str_replace("\\r","<br>",$original_text);
		$original_text = str_replace("
","<br>",$original_text);

		
		//test("2. original_text",$original_text);
		
		return $original_text;
		
		
		
}



function authorization_template_original_text_to_grammar($original_text) {
	
	logger3("authorization_template_original_text_to_grammar(): original_text",$original_text);
	logger3("authorization_template_original_text_to_grammar(): _SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);
	
	$personalized_text = "";
	$personalized_text = $original_text;
	
	### REPLACE SINGLE DIGITS WITH WORDS:
	$personalized_text = str_replace(" 1 "," one ",$personalized_text);
	$personalized_text = str_replace(" 2 "," two ",$personalized_text);
	$personalized_text = str_replace(" 3 "," three ",$personalized_text);
	$personalized_text = str_replace(" 4"," four ",$personalized_text);
	$personalized_text = str_replace(" 5 "," five ",$personalized_text);
	$personalized_text = str_replace(" 6 "," six ",$personalized_text);
	$personalized_text = str_replace(" 7 "," seven ",$personalized_text);
	$personalized_text = str_replace(" 8 "," eight ",$personalized_text);
	$personalized_text = str_replace(" 9 "," nine ",$personalized_text);
	$personalized_text = str_replace(" 10 "," ten ",$personalized_text);
	$personalized_text = str_replace(" 72 "," seventy two ",$personalized_text);
	$personalized_text = str_replace(" 100% "," one hundred percent ",$personalized_text);
	
	### CUSTOMER AUTHORZATION TIME
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TIME'])) {
		$personalized_text = str_replace("AUTHORIZATION_CUSTOMER_TIME","<ruleref uri='builtin:/grammar/date'/> at <ruleref uri='builtin:/grammar/time'/>",$personalized_text);
	}
	
	
	/// NAME=FIRSTNAME+LASTNAME
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) {
		$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'] = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
		
		if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'] .= " ". $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'];
		}
	}
	
	$tmp_AUTHORIZATION_CUSTOMER_NAME = trim($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME']);
	$personalized_text = str_replace("AUTHORIZATION_CUSTOMER_NAME",$tmp_AUTHORIZATION_CUSTOMER_NAME,$personalized_text);
	
        
        
        
        
        ##PASSPHRASE + NEGATIVE WORDS
        if(isset($_SESSION['voice_authorization_api']['biometric_passphrase'])){                
        
        
            $personalized_text = str_replace("[speak your secret passphrase]","
            
            	<one-of>
            	
            		<item>
            			". $_SESSION['voice_authorization_api']['biometric_passphrase'] ."
            		</item>

            		<item>
						speak your secret passphrase
					</item>

            		<item>
						speak my secret passphrase
					</item>
					
            		<item>
						my secret passphrase
					</item>

            		<item>
						your secret passphrase
					</item>
						
            		<item>
						my voice is my passport
					</item>

            		<item>
						my voice is my password
					</item>
					
            		<item>
						blah blah blah
					</item>

            		<item>
						something something something
					</item>
					
            		<item>
						whatever whatever whatever
					</item>
					
								
				</one-of>

            	",$personalized_text);
            	
        
        }
        
        
        
        
        
        
        
	### CUSTOMER AMOUNT (USD)
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'])) {
		$personalized_text = str_replace("AUTHORIZATION_AMOUNT","<item xml:lang='en-US'><ruleref uri='builtin:/grammar/currency'/></item>",$personalized_text);
	}
	
	
	### CUSTOMER AMOUNT_RECIURRING (USD)
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_RECURRING_AMOUNT'])) {
		$personalized_text = str_replace("AUTHORIZATION_RECURRING_AMOUNT","<item xml:lang='en-US'><ruleref uri='builtin:/grammar/currency'/></item>",$personalized_text);
	}
	
	### IF GATEWAY VARS ARE SET:
	
	
	logger3("authorization_template_original_text_to_grammar(): _SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']);
	//exit;
	
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME'])) {
	
		### GATEWAY MERCHANT DETAILS:
		$tmp_AUTHORIZATION_MERCHANT_NAME = trim($_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']);
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_NAME",$tmp_AUTHORIZATION_MERCHANT_NAME,$personalized_text);
		
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_CATEGORY",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_CATEGORY'],$personalized_text);
		
	} else { //normal:
		
		### BUSINESS DETAILS:
		$tmp_AUTHORIZATION_BUSINESS_NAME = trim($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME']);
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_NAME",$tmp_AUTHORIZATION_BUSINESS_NAME,$personalized_text);
		
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_CATEGORY",$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'],$personalized_text);
	}
	
	
	
	
	
	### CARD DETAILS:
	$personalized_text = str_replace("AUTHORIZATION_CARD_LAST4_DIGITS","<ruleref uri='builtin:/grammar/digits?length=4'/>",$personalized_text);
	$card_brand = first_digit_to_card_brand($_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_BRAND']);
	$personalized_text = str_replace("AUTHORIZATION_CARD_BRAND",$card_brand,$personalized_text);


	### vPASS UPDATE:
	// note $_SESSION['voice_authorization_api']['UPDATE_PIN'] will be set in api. 
	$personalized_text = str_ireplace("[speak your 12-digit update PIN]",$_SESSION['voice_authorization_api']['UPDATE_PIN'],$personalized_text);
	
	
	/// .com -> "dot com"
	$personalized_text = str_ireplace(".com"," dot com",$personalized_text);
	$personalized_text = str_ireplace(".org"," dot org",$personalized_text);
	$personalized_text = str_ireplace(".net"," dot net",$personalized_text);
	
	
	### FINAL PATCHES:
	$personalized_text = str_replace("...","",$personalized_text);
	$personalized_text = str_replace(";","",$personalized_text);
	$personalized_text = str_replace(";","",$personalized_text);
	$personalized_text = str_replace(",","",$personalized_text);
	$personalized_text = str_replace(".","",$personalized_text);
	$personalized_text = str_replace("\\n"," ",$personalized_text);
	$personalized_text = str_replace("\\r"," ",$personalized_text);
	$personalized_text = str_replace("
"," ",$personalized_text);
	
	//$personalized_text = str_replace("\n"," ",$personalized_text);
	//$personalized_text = str_replace("\r"," ",$personalized_text);
	
	
	
	

	$originate_grammar = "";
	
	$originate_grammar .= "<?xml version='1.0' encoding ='iso-8859-1'?>";
	$originate_grammar .= "<!DOCTYPE grammar PUBLIC '-//W3C//DTD GRAMMAR 1.0//EN' 'http://www.w3.org/TR/speech-grammar/grammar.dtd'>";
	$originate_grammar .= "<grammar version='1.0' xmlns='http://www.w3.org/2001/06/grammar' xml:lang='en-GB' mode='voice' root='main_rule'>";
	$originate_grammar .= "<rule id='main_rule' scope='public'>";
	$originate_grammar .= "<one-of>";
	$originate_grammar .= "<item xml:lang='en-GB'>";
	
	
	$originate_grammar .= $personalized_text;
	
	
	$originate_grammar .= "</item>";
	$originate_grammar .= "<item xml:lang='en-US'>";
	
	
	$originate_grammar .= $personalized_text;
	
	
	$originate_grammar .= "</item>";
	$originate_grammar .= "</one-of>";	
	$originate_grammar .= "</rule>";
	$originate_grammar .= "</grammar>";
	
	logger3("authorization_template_original_text_to_grammar(): originate_grammar",$originate_grammar);
	return $originate_grammar;
	
	
	
	
	
	
	
	
	
	
}



function authorization_template_original_text_to_grammar_ATT($original_text) {
	
	logger3("authorization_template_original_text_to_grammar(): original_text",$original_text);
	logger3("authorization_template_original_text_to_grammar(): _SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);
	
	$personalized_text = "";
	$personalized_text = $original_text;
	
	### REPLACE SINGLE DIGITS WITH WORDS:
	$personalized_text = str_replace(" 1 "," one ",$personalized_text);
	$personalized_text = str_replace(" 2 "," two ",$personalized_text);
	$personalized_text = str_replace(" 3 "," three ",$personalized_text);
	$personalized_text = str_replace(" 4"," four ",$personalized_text);
	$personalized_text = str_replace(" 5 "," five ",$personalized_text);
	$personalized_text = str_replace(" 6 "," six ",$personalized_text);
	$personalized_text = str_replace(" 7 "," seven ",$personalized_text);
	$personalized_text = str_replace(" 8 "," eight ",$personalized_text);
	$personalized_text = str_replace(" 9 "," nine ",$personalized_text);
	$personalized_text = str_replace(" 10 "," ten ",$personalized_text);
	$personalized_text = str_replace(" 72 "," seventy two ",$personalized_text);
	$personalized_text = str_replace(" 100% "," one hundred percent ",$personalized_text);
	
	### CUSTOMER AUTHORZATION TIME
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TIME'])) {
		$personalized_text = str_replace("AUTHORIZATION_CUSTOMER_TIME","<ruleref uri='builtin:/grammar/date'/> at <ruleref uri='builtin:/grammar/time'/>",$personalized_text);
	}
	
	
	/// NAME=FIRSTNAME+LASTNAME
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) {
		$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'] = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
		
		if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'] .= " ". $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'];
		}
	}
	
	$personalized_text = str_replace("AUTHORIZATION_CUSTOMER_NAME",$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'],$personalized_text);
	
        ##PASSPHRASE
        if(isset($_SESSION['voice_authorization_api']['biometric_passphrase'])){                
            $personalized_text = str_replace("[your customer will be prompted for her/his secret passphrase]",$_SESSION['voice_authorization_api']['biometric_passphrase'],$personalized_text);
        }
        
        
	### CUSTOMER AMOUNT (USD)
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'])) {
		$personalized_text = str_replace("AUTHORIZATION_AMOUNT","<item xml:lang='en-US'><ruleref uri='builtin:/grammar/currency'/></item>",$personalized_text);
	}
	
	
	### CUSTOMER AMOUNT_RECIURRING (USD)
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_RECURRING_AMOUNT'])) {
		$personalized_text = str_replace("AUTHORIZATION_RECURRING_AMOUNT","<item xml:lang='en-US'><ruleref uri='builtin:/grammar/currency'/></item>",$personalized_text);
	}
	
	### IF GATEWAY VARS ARE SET:
	
	
	logger3("authorization_template_original_text_to_grammar(): _SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']);
	//exit;
	
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME'])) {
	
		### GATEWAY MERCHANT DETAILS:
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_NAME",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME'],$personalized_text);
		
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_CATEGORY",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_CATEGORY'],$personalized_text);
		
	} else { //normal:
		
		### BUSINESS DETAILS:
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_NAME",$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'],$personalized_text);
		
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_CATEGORY",$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'],$personalized_text);
	}
	

	
	
	### CARD DETAILS:
	$personalized_text = str_replace("AUTHORIZATION_CARD_LAST4_DIGITS","<ruleref uri='builtin:/grammar/digits?length=4'/>",$personalized_text);
	$card_brand = first_digit_to_card_brand($_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_BRAND']);
	$personalized_text = str_replace("AUTHORIZATION_CARD_BRAND",$card_brand,$personalized_text);
	
	### vPASS UPDATE:
	// note $_SESSION['voice_authorization_api']['UPDATE_PIN'] will be set in api. 
	$personalized_text = str_ireplace("[speak your 12-digit update PIN]",$_SESSION['voice_authorization_api']['UPDATE_PIN'],$personalized_text);

	### vPASS UPDATE:
	// note $_SESSION['voice_authorization_api']['RESET_PIN'] will be set in api. 
	$personalized_text = str_ireplace("[speak your 12-digit reset PIN]",$_SESSION['voice_authorization_api']['RESET_PIN'],$personalized_text);
	
	
	
	
	
	### FINAL PATCHES:
	$personalized_text = str_replace("...","",$personalized_text);
	$personalized_text = str_replace(";","",$personalized_text);
	$personalized_text = str_replace(";","",$personalized_text);
	$personalized_text = str_replace(",","",$personalized_text);
	$personalized_text = str_replace(".","",$personalized_text);
	$personalized_text = str_replace("\\n"," ",$personalized_text);
	$personalized_text = str_replace("\\r"," ",$personalized_text);
	$personalized_text = str_replace("
"," ",$personalized_text);
	
	//$personalized_text = str_replace("\n"," ",$personalized_text);
	//$personalized_text = str_replace("\r"," ",$personalized_text);
	
	
	
	

	$originate_grammar = "";
	

	$originate_grammar .= "<grammar xml:lang='en-US' root='main_rule'>";
	$originate_grammar .= "<rule id='main_rule' scope='public'>";
	$originate_grammar .= "<item>";
        //$originate_grammar .= "<item>";
	
	
	$originate_grammar .= $personalized_text;
	
        
	//$originate_grammar .= "</item>";
	$originate_grammar .= "</item>";
	$originate_grammar .= "</rule>";
	$originate_grammar .= "</grammar>";
	
	logger3("authorization_template_original_text_to_grammar_ATT(): originate_grammar",$originate_grammar);
	return $originate_grammar;
	
	
	
	
	
	
	
	
	
	
}





function MCC2TEXT($MCC) {
	
	### SERVICES
	if($MCC == "7995") return "gambling services";
	if($MCC == "7379") return "technical support services";
	if($MCC == "4818") return "telecommunication services";
	if($MCC == "7994") return "gaming services";
	if($MCC == "8999") return "professional consulting services";
	if($MCC == "5962") return "travel services";
	if($MCC == "7311") return "marketing services";
	if($MCC == "5967") return "digital download services";
	if($MCC == "8398") return "a non-profit donation";
	
	### PRODCUTS
	if($MCC == "7296") return "fashion products";
	if($MCC == "5732") return "electronic products";
	if($MCC == "5734") return "software products";
	if($MCC == "5122") return "nutraceuticals products";
	if($MCC == "0000") return "gateway";
}


//check if account has enough money and debit amount if already exists
function debit_money_from_account($account_hash,$amount){

	
    $tmp_account = account($account_hash);
    //test('tmp_account', $tmp_account);
    
    $tmp_balance = balance($tmp_account['accountid']);
    //test('tmp_balance', $tmp_balance);
    
    
    
	if(
	(stristr($_SESSION['template']['company']['text_name'],"v-sign.network")) &&
	(stristr($_SESSION['account']['business_subcategory'],"GATEWAY"))
	) { // SPECIAL GATEWAY BALANCE


		$balance = $tmp_balance['vSIGN_gateway'];
		$balance = $balance + $amount;


	} else { // NORMAL
		
	
    	$balance = $tmp_balance['account_balance'];
		
		
    	if(($balance - $amount) < 0) return "NOT_ENOUGH_MONEY";
		
    	//test('balance before', $balance);
    	//Update balance
    	$balance = $balance - $amount;
    	//test('balance after', $balance);
    }
		
    
    $query = "UPDATE balances SET account_balance = ". $balance." WHERE balanceid=". $tmp_balance['balanceid'] ." AND accountid=". $tmp_balance['accountid'] ."";    
    $tmp_update_balance = updateTHECASHIER($query);
    //test('query', $query);
    //test('tmp_update_balance', $tmp_update_balance);
    
	return "OK";
	
}



function vPASS_preferences($accountid) {
	return vSIGN($accountid);
}

function vSIGN($accountid) {
    $table_name = 'vSIGN';
    if(stristr($_SESSION['template']["company"]["text_name"],"vPASS")) {
        $table_name = 'vPASS_preferences'; 
    }
	$tmp_sql = "SELECT * FROM ". $table_name ." WHERE accountid = '". $accountid ."';";
	logger3("vSIGN(): tmp_sql",$tmp_sql);
	$sql_results = object2array(readTHECASHIER($tmp_sql));
	return $sql_results;
}


function first_digit_to_card_brand($first_digitof_card) {
	
	if($first_digitof_card == "3") {
		return "AMEX";
	} else 
	if($first_digitof_card == "4") {
		return "VISA";
	} else
	if($first_digitof_card == "5") {
		return "MasterCard";
	} else
	if($first_digitof_card == "6") {
		return "DISCOVER";
	} else {
		return  FALSE;
	}
}



function find_voip_rate($complete_phone_number,$voip_gateway='flowroute',$business_subcategory) {

	global $master_config_verisign_voip_rate_premium;
	
	//test("voip_gateway",$voip_gateway);
	
	//test("business_subcategory",$business_subcategory);
	
	if(stristr($business_subcategory,"GATEWAY")) {
	
	 	$rate = "0.50";
	 	//test("rate",$rate);
	 	///exit;
	 	return $rate;
	
	}
	
	
	while($complete_phone_number) {
	
		//test("complete_phone_number",$complete_phone_number);
		
		$tmp_sql = "SELECT * FROM $voip_gateway WHERE prefix = '". $complete_phone_number."';";
		$voip_details = readTHECASHIER($tmp_sql,"voip_rates");
		//test("voip_details",$voip_details);
		
		if(empty($voip_details->rate)) {
			$complete_phone_number = substr($complete_phone_number, 0, -1);
		} else {
			return $voip_details->rate * $master_config_verisign_voip_rate_premium;
		}	
	}
}


function log_biometric_registration_session() {

	//$_SESSION['']
	
	logger3("log_biometric_registration_session() _SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);

	$biometric_registration_session_id = "";
	$email_verification_hash = hash_me();
        if(isset($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'])){
           //$email_verification_hash = $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'];
        }
	$ACCOUNT_NUMBER = $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'];
	$SERVICE_PASSWORD = $_SESSION['voice_authorization_api']['SERVICE_PASSWORD'];
	$AUTHORIZATION_TEMPLATE = $_SESSION['voice_authorization_api']['AUTHORIZATION_TEMPLATE'];
	$CUSTOMER_SESSION_ID = $_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'];
	
	$AUTHORIZATION_CUSTOMER_FIRSTNAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
	$AUTHORIZATION_CUSTOMER_LASTNAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'];
	$AUTHORIZATION_CUSTOMER_NAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'];
	
	$emailaddress = $_SESSION['voice_authorization_api']['CUSTOMER_EMAILADDRESS'];
	$verified_status = "";
	$datetime_created = datetime();
	$datetime_updated = $datetime_created;
	
	
	$tmp_sql = "INSERT into biometric_registration_session
	
	(
	biometric_registration_session_id,
	email_verification_hash,
	ACCOUNT_NUMBER,
	SERVICE_PASSWORD,
	AUTHORIZATION_TEMPLATE,
	CUSTOMER_SESSION_ID,
	AUTHORIZATION_CUSTOMER_FIRSTNAME,
	AUTHORIZATION_CUSTOMER_LASTNAME,
	emailaddress,
	verified_status,
	datetime_created,
	datetime_updated
	)
	
	VALUES
	
	(
	'$biometric_registration_session_id',
	'$email_verification_hash',
	'$ACCOUNT_NUMBER',
	'$SERVICE_PASSWORD',
	'$AUTHORIZATION_TEMPLATE',
	'$CUSTOMER_SESSION_ID',
	'$AUTHORIZATION_CUSTOMER_FIRSTNAME',
	'$AUTHORIZATION_CUSTOMER_LASTNAME',
	'$emailaddress',
	'$verified_status',
	'$datetime_created',
	'$datetime_updated'
	)";
	
	logger3("log_biometric_registration_session(): tmp_sql",$tmp_sql);
	$insert_results = insertTHECASHIER($tmp_sql);
	logger3("log_biometric_registration_session(): insert_results",$insert_results);
	return $email_verification_hash;

}


function authorization_cancel_update($business_set_user_status_url="",$CUSTOMER_SESSION_ID="") {

	logger3("authorization_cancel_update(): business_set_user_status_url",$business_set_user_status_url);
	logger3("authorization_cancel_update(): CUSTOMER_SESSION_ID",$CUSTOMER_SESSION_ID);
	
	if(empty($CUSTOMER_SESSION_ID)) $CUSTOMER_SESSION_ID = $_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'];
	if(empty($CUSTOMER_SESSION_ID)) return "FAIL: NO URL";
	
	if($business_set_user_status_url) $tmp_url = $business_set_user_status_url;
	
	
	if(empty($tmp_url)) $tmp_url = $tmp_url = $_SESSION['voice_authorization_api']['vSIGN_account_details']['business_set_user_status_url'];

	logger3("authorization_cancel_update(): tmp_url",$tmp_url);
	
	if(empty($tmp_url)) {
	
		return "FAIL: NO URL";
	
	} else {
	
		if(stristr("http",$tmp_url)) $tmp_url = "http://".$tmp_url;
		$tmp_properties = "CUSTOMER_SESSION_ID=". $CUSTOMER_SESSION_ID;
		$tmp_properties .= "&CUSTOMER_SESSION_STATUS=CANCELED";                    
		
		logger3("authorization_cancel_update(): tmp_url: " , $tmp_url);
		logger3("authorization_cancel_update(): tmp_properties: " , $tmp_properties);

		$tmp_kurl = kurl($tmp_url,$tmp_properties);
		logger3("authorization_cancel_update(): tmp_kurl: " , $tmp_kurl); 
		return TRUE;
	}
}



function insert_new_usergaent_details($memberid="",$useragent_data="") {
	
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	if(empty($memberid)) return "FAILED - NO MEMBERID";
	
	if(empty($useragent_data)) $useragent_data = $_SERVER['HTTP_USER_AGENT'];
	if(empty($useragent_data)) return "FAILED - NO HTTP_USER_AGENT";
	
	
	$tmp_sql = "INSERT INTO member_useragent_history (
	`useragentid`,
	`memberid`,
	`useragent_data`,
	`datetime` 
	) VALUES (
	'". $blank_useragentid ."',
	'". $memberid ."',
	'". $useragent_data ."',
	'". datetime() ."'
	);
	";
	logger3("insert_current_usergaent_details(): tmp_sql",$tmp_sql);
	$insert_results = insertTHECASHIER($tmp_sql);
	logger3("insert_current_usergaent_details(): insert_results",$insert_results);
	return $insert_results;
	
}


function match_usergaent_details($memberid="",$useragent_data="") {
	
	
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	if(empty($memberid)) return "FAIL: NO MEMBERID";

	if(empty($useragent_data)) $useragent_data = $_SERVER['HTTP_USER_AGENT'];
	if(empty($useragent_data)) return "FAILED - NO HTTP_USER_AGENT";
	
	$tmp_sql = "SELECT useragent_data 
	FROM 
	member_useragent_history 
	WHERE
	memberid = '". $memberid ."' AND memberid != '' AND memberid != '0'
	ORDER BY datetime DESC 
	LIMIT 1
	;";
	
	logger3("match_current_usergaent_details(): tmp_sql",$tmp_sql);
	$known_useragent_data = getTHECASHIER($tmp_sql);
	logger3("match_current_usergaent_details(): useragent_data",$useragent_data);
	
	if($useragent_data == $known_useragent_data) {
	
		return "MATCH";
		
	} else {
		
		return "FAIL";
	}
	

}


function generate_vPASS_update_pin($MEMBER_BIOMETRIC_ID,$VOICE_AUTHORIZATION_CATEGORY,$voiceprintid) {
	
	$tmp_sql = "SELECT pin FROM vPASS_reset_pins WHERE MEMBER_BIOMETRIC_ID = '". $MEMBER_BIOMETRIC_ID ."' AND datetime_created > '". $tmp_48_hours_ago ."';";
	$already_exists = getTHECASHIER($tmp_sql);
	
	if(!empty($already_exists)) {
		
		$tmp_sql = "UPDATE vPASS_reset_pins SET datetime_created = '". datetime() ."' WHERE pin = '". $already_exists ."';";
		logger3("tmp_sql",$tmp_sql);
		$update_reults = updateTHECASHIER($tmp_sql);
		logger3("update_reults",$update_reults);
		return $already_exists;
		exit;
	}	
	
	
	$already_exists = "UNKNOWN";
	while(!empty($already_exists)) {
		$vPASS_update_pin = rand(100,999). "-". rand(100,999). "-". rand(100,999). "-". rand(100,999);
		$tmp_48_hours_ago = strtotime("-48 hours");
		$tmp_48_hours_ago = date("Y-m-d H:i:s",$tmp_48_hours_ago);
		$tmp_sql = "SELECT resetid FROM vPASS_reset_pins WHERE pin = '". $vPASS_update_pin ."' AND datetime_created > '". $tmp_48_hours_ago ."';";
		$already_exists = getTHECASHIER($tmp_sql);
	}

	$resetid = "";
	$memberid = "";
	$member_biometric_id = $MEMBER_BIOMETRIC_ID;
	$voiceprintid = $voiceprintid;
	$pin = $vPASS_update_pin;
	$category = $VOICE_AUTHORIZATION_CATEGORY;
	$datetime_created = datetime();
	$tmp_sql = "INSERT into vPASS_reset_pins (
		`resetid`,
		`memberid`,
		`member_biometric_id`,
		`voiceprintid`,
		`pin`,
		`category`,
		`datetime_created`
	) VALUES (
		'" . $resetid . "',
		'" . $memberid . "',
		'" . $member_biometric_id . "',
		'" . $voiceprintid . "',
		'" . $pin . "',
		'" . $category . "',
		'" . $datetime_created . "')
	;";
	logger3("tmp_sql",$tmp_sql);
	$vPASS_reset_pins_results = insertTHECASHIER($tmp_sql);
	return $vPASS_update_pin;
}



function audiofilename2voiceprintid($path_to_audio,$audio_file_name) {
	
	logger3("audiofilename2voiceprintid(): 000. path_to_audio",$path_to_audio);
	logger3("audiofilename2voiceprintid(): 000. audio_file_name",$audio_file_name);
	
	
	$tmp_audio_file_name = explode(".",$audio_file_name);
	
	if(!empty($tmp_audio_file_name[1])) {
		$audio_file_name = $tmp_audio_file_name[0];
	}
	
	
	$tmp_sql = "SELECT * FROM voicefiles WHERE 
				filename = '". $audio_file_name ."';
				";
	logger3("audiofilename2voiceprintid(): tmp_sql",$tmp_sql);
	
	$voicefiles_details = readTHECASHIER($tmp_sql);
	logger3("audiofilename2voiceprintid(): voicefiles_details",$voicefiles_details);
	
	
	
//	$tmp_sql = "SELECT DISTINCT voiceprintid FROM voiceprints WHERE voicefileid 
//				LIKE 
//				'". $voicefiles_details->voicefileid .",%'
//				,'%,". $voicefiles_details->voicefileid .",%'
//				,'%,". $voicefiles_details->voicefileid ."'
//				ORDER BY created ASC
//				LIMIT 1
//				;";
//	logger3("audiofilename2voiceprintid(): tmp_sql",$tmp_sql);
	
        
        
    $tmp_sql = "SELECT * FROM vMATCH_audio WHERE
        		audio_filename LIKE '%". $audio_file_name .".%';
        		";
        			
	logger3("audiofilename2voiceprintid(): tmp_sql",$tmp_sql);	
	$vMATCH_audio_details = readTHECASHIER($tmp_sql);
	logger3("audiofilename2voiceprintid(): vMATCH_audio_details",$vMATCH_audio_details);
	 
        
	$tmp_sql = "SELECT DISTINCT voiceprintid FROM voiceprints WHERE ";
    if($voicefiles_details->voicefileid) {
    	$tmp_sql .= "(voicefileids LIKE  '". $voicefiles_details->voicefileid .",%' OR voicefileids LIKE  '%,". $voicefiles_details->voicefileid .",%')";
    
    }
    else if($vMATCH_audio_details) {
            $tmp_sql .= "(vMATCH_audio_id = '".$vMATCH_audio_details->vMATCH_audio_id."' AND vMATCH_audio_id > '0')";
    }
    
    ///$tmp_sql .= " ORDER BY created ASC LIMIT 1;";
    $tmp_sql .= " ORDER BY created DESC LIMIT 1;";
    logger3("audiofilename2voiceprintid(): tmp_sql",$tmp_sql);
                
	$tmp_voiceprintid = getTHECASHIER($tmp_sql);
	logger3("audiofilename2voiceprintid(): tmp_voiceprintid",$tmp_voiceprintid);
	
	
	if(!empty($tmp_voiceprintid)) {
		
		$voiceprintid = $tmp_voiceprintid;
		logger3("audiofilename2voiceprintid(): 000_voiceprintid",$voiceprintid);
		
	} else { ### GENERATE A VOICEPRINT:
	
		$UUID = explode("_",$audio_file_name);
		if(!empty($UUID[1])) {
			$UUID = $UUID[0];
		} else {
			$UUID = $audio_file_name;
		}
        logger3("audiofilename2voiceprintid(): UUID",$UUID);
		$description = "Login";	
		logger3("audiofilename2voiceprintid(): path_to_audio",$path_to_audio);
		logger3("audiofilename2voiceprintid(): audio_file_name",$audio_file_name);
		logger3("audiofilename2voiceprintid(): description",$description);
		$voiceprintid = generate_voiceprint($path_to_audio,$audio_file_name,$description="Login");
		logger3("audiofilename2voiceprintid(): 111_voiceprintid",$voiceprintid);
	}
	
	logger3("audiofilename2voiceprintid(): 222_voiceprintid",$voiceprintid);
	return $voiceprintid;
	
}



function update_biometric_profiles($member_biometric_id,$voiceprintid) {

	logger3("update_biometric_profiles() member_biometric_id",$member_biometric_id);
	logger3("update_biometric_profiles() voiceprintid",$voiceprintid);
	
	$date_time = datetime();
	$tmp_sql = "INSERT into biometric_profiles (
	`biometric_profile_index_id`,
	`voiceprintid`,
	`member_biometric_id`,
	`datetime_created`,
	`datetime_updated`
	) VALUES (
	'" . $tmp_biometric_profile_index_id . "',
	'" . $voiceprintid . "',
	'" . $member_biometric_id . "',
	'" . $date_time . "',
	'" . $date_time . "'
	);";
	logger3("update_biometric_profiles() tmp_sql",$tmp_sql);
	$biometric_profile_index_id = insertTHECASHIER($tmp_sql);
	logger3("update_biometric_profiles() RETURN biometric_profile_index_id",$biometric_profiles_id);
	
	return $biometric_profile_index_id;
}



function check_biometrics_now($check_type, $filename, $voiceprintids, $tolerance, $return_format="") {
    global $logging;
    global $master_config_ibmsiv_host;
    global $master_config_testing_biometric_matching;

    # prepare session:
    logger3("
    
    
    
    
    
    
    
    START: check_biometrics_now()
    
    
    
    ", $a);
    logger3("### BUILD THE LOOK-UP SESSIONS...", $a);
    logger3('filename:', $filename);
    logger3('voiceprintids:', $voiceprintids);
    logger3("Check Type:", $check_type);
    logger3("Tolerance:", $tolerance);


    ### PREP VARS:
    $response = NULL;
    $response = array();
    $results = NULL;
    $results = array();


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


    $mh = curl_multi_init();


    $possible_duplicates = NULL;
    $possible_duplicates = array();
    $pd = 0;
    //$fn = 0;
    $master_counter = 0;
    //while (isset($filenames[$fn])) {
    //logger3("filenames[$fn]: ", $filenames[$fn]);


    ##############################################################################
    # prepare requests / handles:

    $i = 0;
    //while (isset($voiceprintids[$i])) {
	foreach($voiceprintids as $key => $voiceprintid) {
        //logger3("[i]: [", $i . "]", $a);
        logger3("voiceprintid: ", $voiceprintid);

        # set url:
        $siv_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/score";

        #set parameters for sv:
        logger3("mmmmmm_filename",$filename);
        
        $parameters = "voiceprint=". $voiceprintid ."&input-wave-uri=". $filename;
        
        logger3("SIV_URL", $siv_url . "?" . $parameters);



        # initialize:
        $ch[$master_counter] = curl_init();
        //logger3("ch[$vp]: ", $ch[$master_counter]);
        #set headers:
        curl_setopt($ch[$master_counter], CURLOPT_HEADER, 0);

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

        # dunno what this does:
        curl_setopt($ch[$master_counter], CURLOPT_RETURNTRANSFER, 1);

        #curl_setopt($ch, CURLOPT_VERBOSE, 1);
        # set path to server
        curl_setopt($ch[$master_counter], CURLOPT_URL, $siv_url);

        #set parameter values:
        curl_setopt($ch[$master_counter], CURLOPT_POSTFIELDS, $parameters);

        # set multi handle 
        curl_multi_add_handle($mh, $ch[$master_counter]);

        #update voiceid
        $master_counter++;
    }

    #update filname
    //$fn++;
    //}
    ##############################################################################
    # execute:

    $running = 1;
    while ($running > 0) {
        //logger3("running...", $running);
        curl_multi_exec($mh, $running);
    }


    ##############################################################################
    # get responses:
    logger3("### RAW (PER LOOKUP) RESULTS...", $a);

    # used to make final decsision:
    $duplicate_voiceprintids = NULL;
    $duplicate_voiceprintids = array();

    //$fn = 0;
    $master_counter = 0;
    //while (isset($filenames[$fn])) {
    $result = "DOES NOT MATCH";
    $i = 0;
    foreach($voiceprintids as $key => $voiceprintid) {

        //logger3("[vp]: [", $i . "]",$a);
        logger3("voiceprintids: ", $voiceprintids);

        $response[$key] = curl_multi_getcontent($ch[$master_counter]);
        logger3("response[$key]: ", $response[$key]);       

        $tmp_response = explode("name=\"result.score\" expr=\"'", $response[$key]);
        $tmp_response = explode("'\"/>", $tmp_response[1]);
        logger3("filename: ", $filename . " vs. voiceprintid[$key]: " . $voiceprintid . " = score: " . $tmp_response[0]);

		if($tmp_response[0] > $high_score) $high_score = $tmp_response[0];
		
		logger3("high_score",$high_score);
		
        if ($tmp_response[0] >= $tolerance) {
	        
            $result = "MATCHES";
        }
        else{
            //IF ALREADY FOUND A MATCHES, DONT REPLACE IT
            if($result!='MATCHES'){
                if(stristr($check_type,"Biometric Password Update")) {
                    $result = "INVALID";
                }
            }
        }

        # remove handle
        curl_multi_remove_handle($mh, $ch[$master_counter]);

        # update voicefileid
        $i++;
        $master_counter++;
    }
    # update filename
    //$fn++;
    //}
    ##############################################################################
    # all done / close session:
    curl_multi_close($mh);
    
    logger3("high_score",$high_score);
    
    if($return_format == "high_score") {
	    return $high_score;
    } else {
	    return $result;
    }
    
}




function vWAVE_api_sessions($action) {
	
	### LIST OF PAGES THIS IS ON:
	### 1. voice_authorizations.api
	### 2. vSIGN_api_version_WHITELABEL.gatei
	### 3. 
	
	
	### SET #############################################
	if(stristr($action,"SET")) {
		

		///////////////////////////////////////////////////
		/// START: LOG THE INCOMING SESSION:
		///////////////////////////////////////////////////
		
		$set_apiid  = "";
		$set_hash = $_SESSION['incoming_api_session']['hash'] = hash_me();
		
		if(empty($_SESSION['incoming_api_session']['service_name'])) {
			$set_service_name = $_SESSION['incoming_api_session']['service_name'] = $_SESSION['template']['company']['text_name'];
		} else {
			$set_service_name = $_SESSION['incoming_api_session']['service_name'];
		}
		
		if(empty($_SESSION['incoming_api_session']['freeswitch_uuid'])) {
			$set_freeswitch_uuid = $_SESSION['incoming_api_session']['freeswitch_uuid'] = "";
		} else {
			$set_freeswitch_uuid = $_SESSION['incoming_api_session']['freeswitch_uuid'];
		}
		
		if(empty($_SESSION['incoming_api_session']['API_VERSION'])) {
			$set_API_VERSION = $_SESSION['incoming_api_session']['API_VERSION'] = "";
		} else {
			$set_API_VERSION = $_SESSION['incoming_api_session']['API_VERSION'];
		}
		
		if(empty($_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_HASH'])) {
			$set_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_HASH'] = $_SESSION['incoming_api_session']['ACCOUNT_NUMBER'];
		} else {
			$set_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_HASH'];
		}
		
		if(empty($_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'])) {
			$set_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'] = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'];
		} else {
			$set_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'];
		}
		
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_SESSION_ID'])) {
			$set_CUSTOMER_SESSION_ID = $_SESSION['incoming_api_session']['CUSTOMER_SESSION_ID'] = "";
		} else {
			$set_CUSTOMER_SESSION_ID = $_SESSION['incoming_api_session']['CUSTOMER_SESSION_ID'];
		}
		
        if(empty($_SESSION['incoming_api_session']['VOICE_BIOMETRIC_MATCHING_SESSION_ID'])) {
			$set_VOICE_BIOMETRIC_MATCHING_SESSION_ID = $_SESSION['incoming_api_session']['VOICE_BIOMETRIC_MATCHING_SESSION_ID'] = "";
		} else {
			$set_VOICE_BIOMETRIC_MATCHING_SESSION_ID = $_SESSION['incoming_api_session']['VOICE_BIOMETRIC_MATCHING_SESSION_ID'];
		}


        if(empty($_SESSION['incoming_api_session']['CUSTOMER_USERNAME'])) {
			$set_CUSTOMER_USERNAME = $_SESSION['incoming_api_session']['CUSTOMER_USERNAME'] = "";
		} else {
			$set_CUSTOMER_USERNAME = $_SESSION['incoming_api_session']['CUSTOMER_USERNAME'];
		}
		
		
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_BIOMETRIC_ID'])) {
			$set_CUSTOMER_BIOMETRIC_ID = $_SESSION['incoming_api_session']['CUSTOMER_BIOMETRIC_ID'] = "";
		} else {
			$set_CUSTOMER_BIOMETRIC_ID = $_SESSION['incoming_api_session']['CUSTOMER_BIOMETRIC_ID'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_FULL_NAME'])) {
			$set_CUSTOMER_FULL_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FULL_NAME'] = "";
		} else {
			$set_CUSTOMER_FULL_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FULL_NAME'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_FIRST_NAME'])) {
			$set_CUSTOMER_FIRST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FIRST_NAME'] = "";
		} else {
			$set_CUSTOMER_FIRST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FIRST_NAME'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_LAST_NAME'])) {
			$set_CUSTOMER_LAST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_LAST_NAME'] = "";
		} else {
			$set_CUSTOMER_LAST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_LAST_NAME'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'])) {
			$set_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'] = "";
		} else {
			$set_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_CODE'])) {
			$set_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_CODE'] = "";
		} else {
			$set_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_NUMBER'])) {
			$set_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_NUMBER'] = "";
		} else {
			$set_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_NUMBER'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_EMAIL_ADDRESS'])) {
			$set_CUSTOMER_EMAIL_ADDRESS = $_SESSION['incoming_api_session']['CUSTOMER_EMAIL_ADDRESS'] = "";
		} else {
			$set_CUSTOMER_EMAIL_ADDRESS = $_SESSION['incoming_api_session']['CUSTOMER_EMAIL_ADDRESS'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_IP'])) {
			$set_CUSTOMER_IP = $_SESSION['incoming_api_session']['CUSTOMER_IP'] = "";
		} else {
			$set_CUSTOMER_IP = $_SESSION['incoming_api_session']['CUSTOMER_IP'];
		}
		
		if(empty($_SESSION['incoming_api_session']['AUTHORIZATION_CATEGORY'])) {
			$set_AUTHORIZATION_CATEGORY = $_SESSION['incoming_api_session']['AUTHORIZATION_CATEGORY'] = "";
		} else {
			$set_AUTHORIZATION_CATEGORY = $_SESSION['incoming_api_session']['AUTHORIZATION_CATEGORY'];
		}
		
		if(empty($_SESSION['incoming_api_session']['AUTHORIZATION_TEMPLATE'])) {
			$set_AUTHORIZATION_TEMPLATE = $_SESSION['incoming_api_session']['AUTHORIZATION_TEMPLATE'] = "";
		} else {
			$set_AUTHORIZATION_TEMPLATE = $_SESSION['incoming_api_session']['AUTHORIZATION_TEMPLATE'];
		}
		
		if(empty($_SESSION['incoming_api_session']['VOICE_SOURCE'])) {
			$set_VOICE_SOURCE = $_SESSION['incoming_api_session']['VOICE_SOURCE'] = "";
		} else {
			$set_VOICE_SOURCE = $_SESSION['incoming_api_session']['VOICE_SOURCE'];
		}
		
		if(empty($_SESSION['incoming_api_session']['VOICE_AUTHORIZATION_TEXT'])) {
			$set_VOICE_AUTHORIZATION_TEXT = $_SESSION['incoming_api_session']['VOICE_AUTHORIZATION_TEXT'] = "";
		} else {
			$set_VOICE_AUTHORIZATION_TEXT = $_SESSION['incoming_api_session']['VOICE_AUTHORIZATION_TEXT'];
		}
		

		
		
		if(empty($_SESSION['incoming_api_session']['grammar_filename'])) {
			$set_grammar_filename = $_SESSION['incoming_api_session']['grammar_filename'] = "";
		} else {
			$set_grammar_filename = $_SESSION['incoming_api_session']['grammar_filename'];
		}
		
		if(empty($_SESSION['incoming_api_session']['asr_results'])) {
			$set_asr_results = $_SESSION['incoming_api_session']['asr_results'] = "";
		} else {
			$set_asr_results = $_SESSION['incoming_api_session']['asr_results'];
		}
		
		if(empty($_SESSION['incoming_api_session']['authorization_attempt'])) {
			$set_authorization_attempt = $_SESSION['incoming_api_session']['authorization_attempt'] = "";
		} else {
			$set_authorization_attempt = $_SESSION['incoming_api_session']['authorization_attempt'];
		}
		
		if(empty($_SESSION['incoming_api_session']['AUTHORIZATION_STATUS'])) {
			$set_AUTHORIZATION_STATUS = $_SESSION['incoming_api_session']['AUTHORIZATION_STATUS'] = "";
		} else {
			$set_AUTHORIZATION_STATUS = $_SESSION['incoming_api_session']['AUTHORIZATION_STATUS'];
		}
		
		if(empty($_SESSION['incoming_api_session']['voice_authorizations_hash'])) {
			$set_voice_authorizations_hash = $_SESSION['incoming_api_session']['voice_authorizations_hash'] = "";
		} else {
			$set_voice_authorizations_hash = $_SESSION['incoming_api_session']['voice_authorizations_hash'];
		}
		
		if(empty($_SESSION['incoming_api_session']['memberid'])) {
			$set_memberid = $_SESSION['incoming_api_session']['memberid'] = "";
		} else {
			$set_memberid = $_SESSION['incoming_api_session']['memberid'];
		}
		
		if(empty($_SESSION['incoming_api_session']['datetime_created'])) {
			$set_datetime_created = $_SESSION['incoming_api_session']['datetime_created'] = datetime();
		} else {
			$set_datetime_created = $_SESSION['incoming_api_session']['datetime_created'];
		}
		
		if(empty($_SESSION['incoming_api_session']['datetime_updated'])) {
			$set_datetime_updated = $_SESSION['incoming_api_session']['datetime_updated'] = $set_datetime_created;
		} else {
			$set_datetime_updated = $_SESSION['incoming_api_session']['datetime_updated'];
		}
		

		$set_GATEWAY_MERCHANT_NAME = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_NAME'];
		$set_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_EMAILADDRESS'];
		$set_GATEWAY_MERCHANT_MID = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MID'];
		$set_GATEWAY_MERCHANT_MCC = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC'];
		
		
		

		#######
		####### START: voice_authorization_api  (gives data input priority OVER ['incoming_api_session'])
		#######
		
		if(isset($_SESSION['voice_authorization_api'])) {
			
			if(!empty($_SESSION['voice_authorization_api']['service_name'])) $set_service_name = $_SESSION['voice_authorization_api']['service_name'];
			
			if(!empty($_SESSION['voice_authorization_api']['freeswitch_uuid'])) $set_freeswitch_uuid = $_SESSION['voice_authorization_api']['freeswitch_uuid'];
			
			if(!empty($_SESSION['voice_authorization_api']['API_VERSION'])) $set_API_VERSION = $_SESSION['voice_authorization_api']['API_VERSION'];
			
			if(!empty($_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'];
			
			if(!empty($_SESSION['voice_authorization_api']['BUSINESS_ACCOUNT_HASH'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['voice_authorization_api']['BUSINESS_ACCOUNT_HASH'];
			
			if(!empty($_SESSION['voice_authorization_api']['BUSINESS_ACCOUNT_ID'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['voice_authorization_api']['BUSINESS_ACCOUNT_ID'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'])) $set_CUSTOMER_SESSION_ID = $_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_USERNAME'])) $set_CUSTOMER_USERNAME = $_SESSION['voice_authorization_api']['CUSTOMER_USERNAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'])) $set_CUSTOMER_BIOMETRIC_ID = $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_FULL_NAME'])) $set_CUSTOMER_FULL_NAME = $_SESSION['voice_authorization_api']['CUSTOMER_FULL_NAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) $set_CUSTOMER_FIRST_NAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'])) $set_CUSTOMER_LAST_NAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'])) $set_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_CODE'])) $set_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TELEPHONE_NUMBER'])) $set_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TELEPHONE_NUMBER'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'])) $set_CUSTOMER_EMAIL_ADDRESS = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_IP'])) $set_CUSTOMER_IP = $_SESSION['voice_authorization_api']['CUSTOMER_IP'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CATEGORY'])) $set_AUTHORIZATION_CATEGORY = $_SESSION['voice_authorization_api']['AUTHORIZATION_CATEGORY'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_TEMPLATE'])) $set_AUTHORIZATION_TEMPLATE = $_SESSION['voice_authorization_api']['AUTHORIZATION_TEMPLATE'];
			
			if(!empty($_SESSION['voice_authorization_api']['VOICE_SOURCE'])) $set_VOICE_SOURCE = $_SESSION['voice_authorization_api']['VOICE_SOURCE'];
			
			if(!empty($_SESSION['voice_authorization_api']['VOICE_AUTHORIZATION_TEXT'])) $set_VOICE_AUTHORIZATION_TEXT = $_SESSION['voice_authorization_api']['VOICE_AUTHORIZATION_TEXT'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MID'])) $set_GATEWAY_MID = $_SESSION['voice_authorization_api']['GATEWAY_MID'];
			
			if(!empty($_SESSION['voice_authorization_api']['grammar_filename'])) $set_grammar_filename = $_SESSION['voice_authorization_api']['grammar_filename'];
			
			if(!empty($_SESSION['voice_authorization_api']['asr_results'])) $set_asr_results = $_SESSION['voice_authorization_api']['asr_results'];
			
			if(!empty($_SESSION['voice_authorization_api']['authorization_attempt'])) $set_authorization_attempt = $_SESSION['voice_authorization_api']['authorization_attempt'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_STATUS'])) $set_AUTHORIZATION_STATUS = $_SESSION['voice_authorization_api']['AUTHORIZATION_STATUS'];
			
			if(!empty($_SESSION['voice_authorization_api']['voice_authorizations_hash'])) $set_voice_authorizations_hash = $_SESSION['voice_authorization_api']['voice_authorizations_hash'];
			
			if(!empty($_SESSION['voice_authorization_api']['memberid'])) $set_memberid = $_SESSION['voice_authorization_api']['memberid'];
			

				
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_NAME'])) $set_GATEWAY_MERCHANT_NAME = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_NAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_EMAILADDRESS'])) $set_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_EMAILADDRESS'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MID'])) $set_GATEWAY_MERCHANT_MID = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MID'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MCC'])) $set_GATEWAY_MERCHANT_MCC = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MCC'];
			
		
		
		}

		#######
		####### END: voice_authorization_api
		#######
		


		#######
		####### START: vWAVE_api_sessions  (gives data input priority OVER ALL)
		#######
		
		
		
		if(isset($_SESSION['vWAVE_api_sessions'])) {
			
			if(!empty($_SESSION['vWAVE_api_sessions']['service_name'])) $set_service_name = $_SESSION['vWAVE_api_sessions']['service_name'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['freeswitch_uuid'])) $set_freeswitch_uuid = $_SESSION['vWAVE_api_sessions']['freeswitch_uuid'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['API_VERSION'])) $set_API_VERSION = $_SESSION['vWAVE_api_sessions']['API_VERSION'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['ACCOUNT_NUMBER'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['vWAVE_api_sessions']['ACCOUNT_NUMBER'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['BUSINESS_ACCOUNT_HASH'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['vWAVE_api_sessions']['BUSINESS_ACCOUNT_HASH'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['BUSINESS_ACCOUNT_ID'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['vWAVE_api_sessions']['BUSINESS_ACCOUNT_ID'];
			
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_SESSION_ID'])) $set_CUSTOMER_SESSION_ID = $_SESSION['vWAVE_api_sessions']['CUSTOMER_SESSION_ID'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_USERNAME'])) $set_CUSTOMER_USERNAME = $_SESSION['vWAVE_api_sessions']['CUSTOMER_USERNAME'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_BIOMETRIC_ID'])) $set_CUSTOMER_BIOMETRIC_ID = $_SESSION['vWAVE_api_sessions']['CUSTOMER_BIOMETRIC_ID'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_FULL_NAME'])) $set_CUSTOMER_FULL_NAME = $_SESSION['vWAVE_api_sessions']['CUSTOMER_FULL_NAME'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) $set_CUSTOMER_FIRST_NAME = $_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CUSTOMER_LASTNAME'])) $set_CUSTOMER_LAST_NAME = $_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CUSTOMER_LASTNAME'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'])) $set_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_CODE'])) $set_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_NUMBER'])) $set_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_NUMBER'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_EMAIL_ADDRESS'])) $set_CUSTOMER_EMAIL_ADDRESS = $_SESSION['vWAVE_api_sessions']['CUSTOMER_EMAIL_ADDRESS'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_IP'])) $set_CUSTOMER_IP = $_SESSION['vWAVE_api_sessions']['CUSTOMER_IP'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CATEGORY'])) $set_AUTHORIZATION_CATEGORY = $_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CATEGORY'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['AUTHORIZATION_TEMPLATE'])) $set_AUTHORIZATION_TEMPLATE = $_SESSION['vWAVE_api_sessions']['AUTHORIZATION_TEMPLATE'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['VOICE_SOURCE'])) $set_VOICE_SOURCE = $_SESSION['vWAVE_api_sessions']['VOICE_SOURCE'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['VOICE_AUTHORIZATION_TEXT'])) $set_VOICE_AUTHORIZATION_TEXT = $_SESSION['vWAVE_api_sessions']['VOICE_AUTHORIZATION_TEXT'];
			
			### GATEWAY
			if(!empty($_SESSION['vWAVE_api_sessions']['GATEWAY_MID'])) $set_GATEWAY_MID = $_SESSION['vWAVE_api_sessions']['GATEWAY_MID'];
			
			### AUDIO
			if(!empty($_SESSION['vWAVE_api_sessions']['grammar_filename'])) $set_grammar_filename = $_SESSION['vWAVE_api_sessions']['grammar_filename'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['asr_results'])) $set_asr_results = $_SESSION['vWAVE_api_sessions']['asr_results'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['authorization_attempt'])) $set_authorization_attempt = $_SESSION['vWAVE_api_sessions']['authorization_attempt'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['AUTHORIZATION_STATUS'])) $set_AUTHORIZATION_STATUS = $_SESSION['vWAVE_api_sessions']['AUTHORIZATION_STATUS'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['voice_authorizations_hash'])) $set_voice_authorizations_hash = $_SESSION['vWAVE_api_sessions']['voice_authorizations_hash'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['memberid'])) $set_memberid = $_SESSION['vWAVE_api_sessions']['memberid'];
			

			if(!empty($_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_NAME'])) $set_GATEWAY_MERCHANT_NAME = $_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_NAME'];
				
			if(!empty($_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_EMAILADDRESS'])) $set_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_EMAILADDRESS'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_MID'])) $set_GATEWAY_MERCHANT_MID = $_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_MID'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_MCC'])) $set_GATEWAY_MERCHANT_MCC = $_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_MCC'];
				
			

		}
		
		#######
		####### END: vWAVE_api_sessions
		#######




		$tmp_sql = "INSERT INTO `vWAVE_api_sessions`
		(
			`apiid`,
			`hash`,
			`service_name`,
			`freeswitch_uuid`,
			`API_VERSION`,
			`BUSINESS_ACCOUNT_HASH`,
			`CUSTOMER_SESSION_ID`,
            `VOICE_BIOMETRIC_MATCHING_SESSION_ID`,
			`CUSTOMER_BIOMETRIC_ID`,
			`CUSTOMER_USERNAME`,
			`CUSTOMER_FULL_NAME`,
			`CUSTOMER_FIRST_NAME`,
			`CUSTOMER_LAST_NAME`,
			`CUSTOMER_TELEPHONE_COUNTRY_ISO3`,
			`CUSTOMER_TELEPHONE_COUNTRY_CODE`,
			`CUSTOMER_TELEPHONE_NUMBER`,
			`CUSTOMER_EMAIL_ADDRESS`,
			`CUSTOMER_IP`,
			`AUTHORIZATION_CATEGORY`,
			`AUTHORIZATION_TEMPLATE`,
			`VOICE_SOURCE`,
			`VOICE_AUTHORIZATION_TEXT`,
			`GATEWAY_MERCHANT_NAME`,
			`GATEWAY_MERCHANT_EMAILADDRESS`,
			`GATEWAY_MERCHANT_MID`,
			`GATEWAY_MERCHANT_MCC`,
			`grammar_filename`,
			`asr_results`,
			`authorization_attempt`,
			`AUTHORIZATION_STATUS`,
			`voice_authorizations_hash`,
			`memberid`,
			`datetime_created`,
			`datetime_updated`
		) VALUES (
			'". $set_apiid ."',
			'". $set_hash ."',
			'". $set_service_name .".()',
			'". $set_freeswitch_uuid ."',
			'". $set_API_VERSION ."',
			'". $set_BUSINESS_ACCOUNT_HASH ."',
			'". $set_CUSTOMER_SESSION_ID ."',
            '". $set_VOICE_BIOMETRIC_MATCHING_SESSION_ID ."',
			'". $set_CUSTOMER_BIOMETRIC_ID ."',
			'". $set_CUSTOMER_USERNAME ."',
			'". $set_CUSTOMER_FULL_NAME ."',
			'". $set_CUSTOMER_FIRST_NAME ."',
			'". $set_CUSTOMER_LAST_NAME ."',
			'". $set_CUSTOMER_TELEPHONE_COUNTRY_ISO3 ."',
			'". $set_CUSTOMER_TELEPHONE_COUNTRY_CODE ."',
			'". $set_CUSTOMER_TELEPHONE_NUMBER ."',
			'". $set_CUSTOMER_EMAIL_ADDRESS ."',
			'". $set_CUSTOMER_IP ."',
			'". $set_AUTHORIZATION_CATEGORY ."',
			'". $set_AUTHORIZATION_TEMPLATE ."',
			'". $set_VOICE_SOURCE ."',
			'". addslashes($set_VOICE_AUTHORIZATION_TEXT) ."',
			'". $set_GATEWAY_MERCHANT_NAME ."',
			'". $set_GATEWAY_MERCHANT_EMAILADDRESS ."',
			'". $set_GATEWAY_MERCHANT_MID ."',
			'". $set_GATEWAY_MERCHANT_MCC ."',
			'". $set_grammar_filename ."',
			'". $set_asr_results ."',
			'". $set_authorization_attempt ."',
			'". $set_AUTHORIZATION_STATUS ."',
			'". $set_voice_authorizations_hash ."',
			'". $set_memberid ."',
			'". $set_datetime_created ."',
			'". $set_datetime_updated ."'
		);
		";
		
		logger3("tmp_sql",$tmp_sql);
		$_SESSION['incoming_api_session']['apiid'] = $insert_results = insertTHECASHIER($tmp_sql);
		logger3("vWAVE_api_sessions_set_apiid",$_SESSION['incoming_api_session']['apiid']);
		return $_SESSION['incoming_api_session']['apiid'];
		
		///////////////////////////////////////////////////
		/// END: LOG THE INCOMING SESSION:
		///////////////////////////////////////////////////
	}
	
	
	
	### UPDATE #############################################
	if(stristr($action,"UPDATE")) {
		
		
		$update_apiid = $_SESSION['incoming_api_session']['apiid'];
		$update_hash = $_SESSION['incoming_api_session']['hash'];
		$update_service_name = $_SESSION['incoming_api_session']['service_name'];
		$update_freeswitch_uuid = $_SESSION['incoming_api_session']['freeswitch_uuid'];
		$update_API_VERSION = $_SESSION['incoming_api_session']['API_VERSION'];
		$update_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_HASH'];
		if(!empty($_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'])) $update_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'];
		$update_CUSTOMER_SESSION_ID = $_SESSION['incoming_api_session']['CUSTOMER_SESSION_ID'];
		$update_CUSTOMER_BIOMETRIC_ID = $_SESSION['incoming_api_session']['CUSTOMER_BIOMETRIC_ID'];
		$update_CUSTOMER_USERNAME = $_SESSION['incoming_api_session']['CUSTOMER_USERNAME'];
		$update_CUSTOMER_FULL_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FULL_NAME'];
		$update_CUSTOMER_FIRST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FIRST_NAME'];
		$update_CUSTOMER_LAST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_LAST_NAME'];
		$update_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
		$update_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
		$update_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_NUMBER'];
		$update_CUSTOMER_EMAIL_ADDRESS = $_SESSION['incoming_api_session']['CUSTOMER_EMAIL_ADDRESS'];
		$update_CUSTOMER_IP = $_SESSION['incoming_api_session']['CUSTOMER_IP'];
		$update_AUTHORIZATION_CATEGORY = $_SESSION['incoming_api_session']['AUTHORIZATION_CATEGORY'];
		$update_AUTHORIZATION_TEMPLATE = $_SESSION['incoming_api_session']['AUTHORIZATION_TEMPLATE'];
		$update_VOICE_SOURCE = $_SESSION['incoming_api_session']['VOICE_SOURCE'];
		$update_VOICE_AUTHORIZATION_TEXT = $_SESSION['incoming_api_session']['VOICE_AUTHORIZATION_TEXT'];
		$update_grammar_filename = $_SESSION['incoming_api_session']['grammar_filename'];
		$update_asr_results = $_SESSION['incoming_api_session']['asr_results'];
		$update_authorization_attempt = $_SESSION['incoming_api_session']['authorization_attempt'];
		$update_AUTHORIZATION_STATUS = $_SESSION['incoming_api_session']['AUTHORIZATION_STATUS'];
		$update_voice_authorizations_hash = $_SESSION['incoming_api_session']['voice_authorizations_hash'];
		$update_memberid = $_SESSION['incoming_api_session']['memberid'];
		$update_datetime_created = $_SESSION['incoming_api_session']['datetime_created'];
		$update_datetime_updated = $_SESSION['incoming_api_session']['datetime_updated'] = datetime();
		
		### GATEWAY:
		$update_GATEWAY_MERCHANT_NAME = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_NAME'];
		$update_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_EMAILADDRESS'];
		$update_GATEWAY_MERCHANT_MID = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MID'];
		$update_GATEWAY_MERCHANT_MCC = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC'];
		
		#######
		####### START: voice_authorization_api  (gives data input priority OVER ['incoming_api_session'])
		#######
		
		if(isset($_SESSION['voice_authorization_api'])) {
			
			if(!empty($_SESSION['voice_authorization_api']['apiid'])) $update_apiid = $_SESSION['voice_authorization_api']['apiid'];
			
			if(!empty($_SESSION['voice_authorization_api']['service_name'])) $update_service_name = $_SESSION['voice_authorization_api']['service_name'];
			
			if(!empty($_SESSION['voice_authorization_api']['freeswitch_uuid'])) $update_freeswitch_uuid = $_SESSION['voice_authorization_api']['freeswitch_uuid'];
			
			if(!empty($_SESSION['voice_authorization_api']['API_VERSION'])) $update_API_VERSION = $_SESSION['voice_authorization_api']['API_VERSION'];
			
			if(!empty($_SESSION['voice_authorization_api']['BUSINESS_ACCOUNT_HASH'])) $update_BUSINESS_ACCOUNT_HASH = $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'])) $update_CUSTOMER_SESSION_ID = $_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'])) $update_CUSTOMER_BIOMETRIC_ID = $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_FULL_NAME'])) $update_CUSTOMER_FULL_NAME = $_SESSION['voice_authorization_api']['CUSTOMER_FULL_NAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) $update_CUSTOMER_FIRST_NAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'])) $update_CUSTOMER_LAST_NAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'])) $update_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_CODE'])) $update_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TELEPHONE_NUMBER'])) $update_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TELEPHONE_NUMBER'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'])) $update_CUSTOMER_EMAIL_ADDRESS = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_IP'])) $update_CUSTOMER_IP = $_SESSION['voice_authorization_api']['CUSTOMER_IP'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CATEGORY'])) $update_AUTHORIZATION_CATEGORY = $_SESSION['voice_authorization_api']['AUTHORIZATION_CATEGORY'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_TEMPLATE'])) $update_AUTHORIZATION_TEMPLATE = $_SESSION['voice_authorization_api']['AUTHORIZATION_TEMPLATE'];
			
			if(!empty($_SESSION['voice_authorization_api']['VOICE_SOURCE'])) $update_VOICE_SOURCE = $_SESSION['voice_authorization_api']['VOICE_SOURCE'];
			
			if(!empty($_SESSION['voice_authorization_api']['VOICE_AUTHORIZATION_TEXT'])) $update_VOICE_AUTHORIZATION_TEXT = $_SESSION['voice_authorization_api']['VOICE_AUTHORIZATION_TEXT'];
			
			if(!empty($_SESSION['voice_authorization_api']['grammar_filename'])) $update_grammar_filename = $_SESSION['voice_authorization_api']['grammar_filename'];
			
			if(!empty($_SESSION['voice_authorization_api']['asr_results'])) $update_asr_results = $_SESSION['voice_authorization_api']['asr_results'];
			
			if(!empty($_SESSION['voice_authorization_api']['authorization_attempt'])) $update_authorization_attempt = $_SESSION['voice_authorization_api']['authorization_attempt'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_STATUS'])) $update_AUTHORIZATION_STATUS = $_SESSION['voice_authorization_api']['AUTHORIZATION_STATUS'];
			
			if(!empty($_SESSION['voice_authorization_api']['voice_authorizations_hash'])) $update_voice_authorizations_hash = $_SESSION['voice_authorization_api']['voice_authorizations_hash'];
			
			if(!empty($_SESSION['voice_authorization_api']['memberid'])) $update_memberid = $_SESSION['voice_authorization_api']['memberid'];
			
			# GATEWAY:
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_NAME'])) $update_GATEWAY_MERCHANT_NAME = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_NAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_EMAILADDRESS'])) $update_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_EMAILADDRESS'];

			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MID'])) $update_GATEWAY_MERCHANT_MID = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MID'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MCC'])) $update_GATEWAY_MERCHANT_MCC = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MCC'];
			
		}
		
		#######
		####### END: voice_authorization_api
		#######


		#######
		####### START: vWAVE_api_sessions  (gives data input priority OVER ALL)
		#######
		
		//test("functions_shared_SESSION_vWAVE_api_sessions",$_SESSION['vWAVE_api_sessions']);
		
		if(isset($_SESSION['vWAVE_api_sessions'])) {
			
			if(!empty($_SESSION['vWAVE_api_sessions']['apiid'])) $update_apiid = $_SESSION['vWAVE_api_sessions']['apiid'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['service_name'])) $update_service_name = $_SESSION['vWAVE_api_sessions']['service_name'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['freeswitch_uuid'])) $update_freeswitch_uuid = $_SESSION['vWAVE_api_sessions']['freeswitch_uuid'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['API_VERSION'])) $update_API_VERSION = $_SESSION['vWAVE_api_sessions']['API_VERSION'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['BUSINESS_ACCOUNT_HASH'])) $update_BUSINESS_ACCOUNT_HASH = $_SESSION['vWAVE_api_sessions']['ACCOUNT_NUMBER'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_SESSION_ID'])) $update_CUSTOMER_SESSION_ID = $_SESSION['vWAVE_api_sessions']['CUSTOMER_SESSION_ID'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_BIOMETRIC_ID'])) $update_CUSTOMER_BIOMETRIC_ID = $_SESSION['vWAVE_api_sessions']['CUSTOMER_BIOMETRIC_ID'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_FULL_NAME'])) $update_CUSTOMER_FULL_NAME = $_SESSION['vWAVE_api_sessions']['CUSTOMER_FULL_NAME'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) $update_CUSTOMER_FIRST_NAME = $_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CUSTOMER_LASTNAME'])) $update_CUSTOMER_LAST_NAME = $_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CUSTOMER_LASTNAME'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'])) $update_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_CODE'])) $update_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_NUMBER'])) $update_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['vWAVE_api_sessions']['CUSTOMER_TELEPHONE_NUMBER'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_EMAIL_ADDRESS'])) $update_CUSTOMER_EMAIL_ADDRESS = $_SESSION['vWAVE_api_sessions']['CUSTOMER_EMAIL_ADDRESS'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['CUSTOMER_IP'])) $update_CUSTOMER_IP = $_SESSION['vWAVE_api_sessions']['CUSTOMER_IP'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CATEGORY'])) $update_AUTHORIZATION_CATEGORY = $_SESSION['vWAVE_api_sessions']['AUTHORIZATION_CATEGORY'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['AUTHORIZATION_TEMPLATE'])) $update_AUTHORIZATION_TEMPLATE = $_SESSION['vWAVE_api_sessions']['AUTHORIZATION_TEMPLATE'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['VOICE_SOURCE'])) $update_VOICE_SOURCE = $_SESSION['vWAVE_api_sessions']['VOICE_SOURCE'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['VOICE_AUTHORIZATION_TEXT'])) $update_VOICE_AUTHORIZATION_TEXT = $_SESSION['vWAVE_api_sessions']['VOICE_AUTHORIZATION_TEXT'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['grammar_filename'])) $update_grammar_filename = $_SESSION['vWAVE_api_sessions']['grammar_filename'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['asr_results'])) $update_asr_results = $_SESSION['vWAVE_api_sessions']['asr_results'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['authorization_attempt'])) $update_authorization_attempt = $_SESSION['vWAVE_api_sessions']['authorization_attempt'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['AUTHORIZATION_STATUS'])) $update_AUTHORIZATION_STATUS = $_SESSION['vWAVE_api_sessions']['AUTHORIZATION_STATUS'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['voice_authorizations_hash'])) $update_voice_authorizations_hash = $_SESSION['vWAVE_api_sessions']['voice_authorizations_hash'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['memberid'])) $update_memberid = $_SESSION['vWAVE_api_sessions']['memberid'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_NAME'])) $update_GATEWAY_MERCHANT_NAME = $_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_NAME'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_EMAILADDRESS'])) $update_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_EMAILADDRESS'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_MID'])) $update_GATEWAY_MERCHANT_MID = $_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_MID'];
			
			if(!empty($_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_MCC'])) $update_GATEWAY_MERCHANT_MCC = $_SESSION['vWAVE_api_sessions']['GATEWAY_MERCHANT_MCC'];
			
			
		}
		
		#######
		####### END: vWAVE_api_sessions
		#######
		
		
		if(empty($update_service_name)) $update_service_name = $_SESSION['template']['company']['text_name'];
		if(empty($update_CUSTOMER_IP)) $update_CUSTOMER_IP = $_SERVER['REMOTE_ADDR'];
		
		
		$tmp_sql = "UPDATE `vWAVE_api_sessions` SET
		`service_name` = '". $update_service_name .".()',
		`freeswitch_uuid` = '". $update_freeswitch_uuid ."',
		`API_VERSION` = '". $update_API_VERSION ."',
		`BUSINESS_ACCOUNT_HASH` = '". $update_BUSINESS_ACCOUNT_HASH ."',
		`CUSTOMER_SESSION_ID` = '". $update_CUSTOMER_SESSION_ID ."',
		`CUSTOMER_BIOMETRIC_ID` = '". $update_CUSTOMER_BIOMETRIC_ID ."',
		`CUSTOMER_FULL_NAME` = '". $update_CUSTOMER_FULL_NAME ."',
		`CUSTOMER_FIRST_NAME` = '". $update_CUSTOMER_FIRST_NAME ."',
		`CUSTOMER_LAST_NAME` = '". $update_CUSTOMER_LAST_NAME ."',
		`CUSTOMER_TELEPHONE_COUNTRY_ISO3` = '". $update_CUSTOMER_TELEPHONE_COUNTRY_ISO3 ."',
		`CUSTOMER_TELEPHONE_COUNTRY_CODE` = '". $update_CUSTOMER_TELEPHONE_COUNTRY_CODE ."',
		`CUSTOMER_TELEPHONE_NUMBER` = '". $update_CUSTOMER_TELEPHONE_NUMBER ."',
		`CUSTOMER_EMAIL_ADDRESS` = '". $update_CUSTOMER_EMAIL_ADDRESS ."',
		`CUSTOMER_IP` = '". $update_CUSTOMER_IP ."',
		`AUTHORIZATION_CATEGORY` = '". $update_AUTHORIZATION_CATEGORY ."',
		`AUTHORIZATION_TEMPLATE` = '". $update_AUTHORIZATION_TEMPLATE ."',
		`VOICE_SOURCE` = '". $update_VOICE_SOURCE ."',
		`VOICE_AUTHORIZATION_TEXT` = '". addslashes($update_VOICE_AUTHORIZATION_TEXT) ."',
		
		`GATEWAY_MERCHANT_NAME` = '". $update_GATEWAY_MERCHANT_NAME ."',
		`GATEWAY_MERCHANT_EMAILADDRESS` = '". $update_GATEWAY_MERCHANT_MAILADDRESS ."',
		`GATEWAY_MERCHANT_MID` = '". $update_GATEWAY_MERCHANT_MID ."',
		`GATEWAY_MERCHANT_MCC` = '". $update_GATEWAY_MERCHANT_MCC ."',
		
		`grammar_filename` = '". $update_grammar_filename ."',
		`asr_results` = '". $update_asr_results ."',
		`authorization_attempt` = '". $update_authorization_attempt ."',
		`AUTHORIZATION_STATUS` = '". $update_AUTHORIZATION_STATUS ."',
		`voice_authorizations_hash` = '". $update_voice_authorizations_hash ."',
		`memberid` = '". $update_memberid ."',
		`datetime_updated` = '". $update_datetime_updated ."'
		 WHERE
		 apiid = '". $update_apiid ."'
		 ;";
		///test("tmp_sql",$tmp_sql);
		$update_results = updateTHECASHIER($tmp_sql);
		//test("vWAVE_api_sessions_update_results",$update_results);
		
	}

}

function is_mobile_device() {
    global $master_config_root_path;
    require_once($master_config_root_path . "shared/Mobile_Detect.php");        
    $detect = new Mobile_Detect;

    //if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone'))
    //return true;
    
    
    
    $is_device = $detect->isMobile();
    // if($is_device) {
	//     if(stristr($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
	// 		$is_device = 1;
	// 	}
    // }
    return $is_device;
    //exit;
}

function what_device() {
	

    global $master_config_root_path;
    require_once($master_config_root_path . "shared/Mobile_Detect.php");        
    $detect = new Mobile_Detect;
    

    if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone')) return "iPhone";
	if(strstr($_SERVER['HTTP_USER_AGENT'],'iPad')) return iPad;
	
	$is_device = $detect->isMobile();
	
	if($is_device == 1) return "Android";
	
	return "Desktop";
	
}


function get_audio_from_url($remote_url, $target_path=''){
    global $master_config_root_path;
    $target_path = $master_config_root_path."authorizations/audio/";
    if(empty($target_path)) $target_path = $default_path;
    $filename_without_ext = hash_me();
    
    $content = get_headers($remote_url,1);
    $content = array_change_key_case($content, CASE_LOWER);
    if ($content['content-disposition']) {
        $tmp_name = explode('=', $content['content-disposition']);
        if ($tmp_name[1]) 
            $realfilename = trim($tmp_name[1],'";\'');
    } else  
    {
        $stripped_url = preg_replace('/\\?.*/', '', $remote_url);
        $realfilename = basename($stripped_url);
    } 
    $tmp_name = explode('.', $realfilename);
    $ext1 = $tmp_name[count($tmp_name)-1];
    $local_file_path = $target_path.$filename_without_ext.'.'.$ext1;
    
    $remote_file_contents = file_get_contents($remote_url );    
    logger3('local_file_path', $local_file_path);
    $audio_copied = file_put_contents($local_file_path, $remote_file_contents);
    if(file_exists($local_file_path)) return $filename_without_ext.'.'.$ext1;
    else return false;
}



function get_ATT_asr_confidence($filename, $returnFullResponse = false){
	$result = 0;
	if($returnFullResponse) $result = array();
	
	if(!is_file($filename)){
		logger3('File Not found', $filename);
		return $confidence_level;		
	} 
	
 	//ATT OAuth TokenID START
	$crl = curl_init();
	
	$headr = array();
	$headr[] = 'Accept: application/json';
	$headr[] = 'Content-Type: application/x-www-form-urlencoded';
	
	curl_setopt($crl, CURLOPT_URL, "https://api.att.com/oauth/token" );
	curl_setopt($crl, CURLOPT_POST, 1);
	curl_setopt($crl, CURLOPT_POSTFIELDS, "client_id=neievhiljxpujabllr3fcznrypitk1tq&client_secret=yguidj8omy6clrwyiniu2tllkxonpbha&grant_type=client_credentials&scope=SPEECH,STTC" ); // change APPID and APPSECRET to the values from your developer console
	curl_setopt($crl, CURLOPT_HTTPHEADER,$headr);
	curl_setopt ($crl, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt ($crl, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
	
	$result=curl_exec ($crl);	
	$decoded_json = json_decode($result, true);	
	$token_id = $decoded_json["access_token"];
	
	logger3('token_id', $token_id);
		
	curl_close($crl);
	//ATT OAuth TokenID END		
	
	//ATT START
	$crl2 = curl_init();
	
	$headr = array();
	$headr[] = 'Authorization: Bearer ' . $token_id;
	$headr[] = 'Accept: application/json';
	$headr[] = 'Content-Type: audio/wav';
	$headr[] = 'X-SpeechContext: SMS';
	
	curl_setopt($crl2, CURLOPT_URL, "https://api.att.com/speech/v3/speechToText" );
	curl_setopt($crl2, CURLOPT_POST, 1);
	$file = fopen($filename, 'r'); //change FILENAME to the name of your file
	$size = filesize($filename); //change FILENAME to the name of your file
	$fildata = fread($file,$size);
	curl_setopt($crl2, CURLOPT_POSTFIELDS, $fildata);
	curl_setopt($crl2, CURLOPT_HTTPHEADER,$headr);
	curl_setopt ($crl2, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt ($crl2, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($crl2, CURLOPT_RETURNTRANSFER, true);
	
	$result2=curl_exec ($crl2);	
	$decoded_json2 = json_decode($result2, true);
	logger3('filesize', $size);	
	logger3('result', $decoded_json2);	
	
	if(isset($decoded_json2["Recognition"]["NBest"][0])){	
		$result_text = $decoded_json2["Recognition"]["NBest"][0]["ResultText"];
		logger3('result_text', $result_text);
			
		$confidence_level = $decoded_json2["Recognition"]["NBest"][0]["Confidence"];
		logger3('confidence_level', $confidence_level);
		$result = $confidence_level;
		
		//return full response
		if($returnFullResponse){
			logger3("returnFullResponse", $returnFullResponse);
			$result = $decoded_json2["Recognition"]["NBest"][0];			
		}
	}
	curl_close($crl2);
	//ATT END
			
	return $result . "||" . $result_text;
}

function create_dns_a_record($business_name,$service_host="") {
	
	if(empty($service_host)) $service_host = 'video-conference.link';
	
	$business_name = trim($business_name);
	if(empty($business_name)){
		logger3('business_name', "DNS (A) record can't be empty.");
		return false;
	} 
	
	$output = shell_exec("/BANGK\!/www/test/video-conference/create_dns_a_record.sh '$business_name'");
	//test("output",$output);
	$output = substr($output, strpos($output, '; BIND data file for local loopback interface'));
	//logger3("output",$output);			
	
	$domain = $service_host;
	$sub_domain = $business_name . '.'.$domain.'';
	$a_record = $sub_domain . '.';
	$pos = stripos($output, $a_record);
	if ($pos !== false) {
		logger3($sub_domain, "DNS (A) record has successfully been created.");	
		
		return true;		
	}
	else {
		logger3($sub_domain, "Failed to create DNS record");		
	}
	return true;

}

function replace_dns_a_record($business_name_old, $business_name_new){
	$business_name_old = trim($business_name_old);
	$business_name_new = trim($business_name_new);
	if(empty($business_name_old)){
		logger3('business_name_old', "DNS (A) record can't be empty.");
		return false;
	} 
	if(empty($business_name_new)){
		logger3('business_name_new', "DNS (A) record can't be empty.");
		return false;
	} 
	
	$output = shell_exec("/BANGK\!/www/test/video-conference/replace_dns_a_record.sh '$business_name_old'  '$business_name_new'");
	//test("output",$output);	
	$output = substr($output, strpos($output, '; BIND data file for local loopback interface'));
	//logger3("output",$output);
	
	$domain = 'video-conference.link';
	$sub_domain = $business_name_new . '.'.$domain.'';
	$a_record = $sub_domain . '.';
	$pos = stripos($output, $a_record);
	if ($pos !== false) {
		logger3($sub_domain, "DNS (A) record has successfully been created.");	
		
		return true;		
	}
	else {
		logger3($sub_domain, "Failed to create DNS record");		
	}
	return true;

}


function whois($domain) {
	
	
	logger3("### ### ### 000 WHOIS",$domain);
	
	$exploded_domain = explode("/", $domain);
	
	if(!empty($exploded_domain[0])) $domain = $exploded_domain[0];
	
	logger3("### ### ### 1 WHOIS",$domain);

	/// CHECKK LOCAL FIRST
	$tmp_sql = "SELECT details FROM whois WHERE domain = '". $domain ."';";
	
	logger3("check whois tmp_sql",$tmp_sql);
	
	
	$local_whois_details = getTHECASHIER($tmp_sql,"peephole.online");
	
	logger3("check whois local_whois_details",$local_whois_details);
	
	
	if(!empty($local_whois_details)) {
		return $local_whois_details;
		exit;
	}
	
	
	
	
	
	
	/*************************************************************************
	php easy :: whois lookup script
	==========================================================================
	Author:      php easy code, www.phpeasycode.com
	Web Site:    http://www.phpeasycode.com
	Contact:     webmaster@phpeasycode.com
	*************************************************************************/
	
	//$domain = $_GET['domain'];
	
	// For the full list of TLDs/Whois servers see http://www.iana.org/domains/root/db/ and http://www.whois365.com/en/listtld/
	$whoisservers = array(
		"ac" => "whois.nic.ac", // Ascension Island
		// ad - Andorra - no whois server assigned
		"ae" => "whois.nic.ae", // United Arab Emirates
		"aero"=>"whois.aero",
		"af" => "whois.nic.af", // Afghanistan
		"ag" => "whois.nic.ag", // Antigua And Barbuda
		"ai" => "whois.ai", // Anguilla
		"al" => "whois.ripe.net", // Albania
		"am" => "whois.amnic.net",  // Armenia
		// an - Netherlands Antilles - no whois server assigned
		// ao - Angola - no whois server assigned
		// aq - Antarctica (New Zealand) - no whois server assigned
		// ar - Argentina - no whois server assigned
		"arpa" => "whois.iana.org",
		"as" => "whois.nic.as", // American Samoa
		"asia" => "whois.nic.asia",
		"at" => "whois.nic.at", // Austria
		"au" => "whois.aunic.net", // Australia
		// aw - Aruba - no whois server assigned
		"ax" => "whois.ax", // Aland Islands
		"az" => "whois.ripe.net", // Azerbaijan
		// ba - Bosnia And Herzegovina - no whois server assigned
		// bb - Barbados - no whois server assigned
		// bd - Bangladesh - no whois server assigned
		"be" => "whois.dns.be", // Belgium
		"bg" => "whois.register.bg", // Bulgaria
		"bi" => "whois.nic.bi", // Burundi
		"biz" => "whois.biz",
		"bj" => "whois.nic.bj", // Benin
		// bm - Bermuda - no whois server assigned
		"bn" => "whois.bn", // Brunei Darussalam
		"bo" => "whois.nic.bo", // Bolivia
		"br" => "whois.registro.br", // Brazil
		"bt" => "whois.netnames.net", // Bhutan
		// bv - Bouvet Island (Norway) - no whois server assigned
		// bw - Botswana - no whois server assigned
		"by" => "whois.cctld.by", // Belarus
		"bz" => "whois.belizenic.bz", // Belize
		"ca" => "whois.cira.ca", // Canada
		"cat" => "whois.cat", // Spain
		"cc" => "whois.nic.cc", // Cocos (Keeling) Islands
		"cd" => "whois.nic.cd", // Congo, The Democratic Republic Of The
		// cf - Central African Republic - no whois server assigned
		"ch" => "whois.nic.ch", // Switzerland
		"ci" => "whois.nic.ci", // Cote d'Ivoire
		"ck" => "whois.nic.ck", // Cook Islands
		"cl" => "whois.nic.cl", // Chile
		// cm - Cameroon - no whois server assigned
		"cn" => "whois.cnnic.net.cn", // China
		"co" => "whois.nic.co", // Colombia
		"com" => "whois.verisign-grs.com",
		"coop" => "whois.nic.coop",
		// cr - Costa Rica - no whois server assigned
		// cu - Cuba - no whois server assigned
		// cv - Cape Verde - no whois server assigned
		// cw - Curacao - no whois server assigned
		"cx" => "whois.nic.cx", // Christmas Island
		// cy - Cyprus - no whois server assigned
		"cz" => "whois.nic.cz", // Czech Republic
		"de" => "whois.denic.de", // Germany
		// dj - Djibouti - no whois server assigned
		"dk" => "whois.dk-hostmaster.dk", // Denmark
		"dm" => "whois.nic.dm", // Dominica
		// do - Dominican Republic - no whois server assigned
		"dz" => "whois.nic.dz", // Algeria
		"ec" => "whois.nic.ec", // Ecuador
		"edu" => "whois.educause.edu",
		"ee" => "whois.eenet.ee", // Estonia
		"eg" => "whois.ripe.net", // Egypt
		// er - Eritrea - no whois server assigned
		"es" => "whois.nic.es", // Spain
		// et - Ethiopia - no whois server assigned
		"eu" => "whois.eu",
		"fi" => "whois.ficora.fi", // Finland
		// fj - Fiji - no whois server assigned
		// fk - Falkland Islands - no whois server assigned
		// fm - Micronesia, Federated States Of - no whois server assigned
		"fo" => "whois.nic.fo", // Faroe Islands
		"fr" => "whois.nic.fr", // France
		// ga - Gabon - no whois server assigned
		"gd" => "whois.nic.gd", // Grenada
		// ge - Georgia - no whois server assigned
		// gf - French Guiana - no whois server assigned
		"gg" => "whois.gg", // Guernsey
		// gh - Ghana - no whois server assigned
		"gi" => "whois2.afilias-grs.net", // Gibraltar
		"gl" => "whois.nic.gl", // Greenland (Denmark)
		// gm - Gambia - no whois server assigned
		// gn - Guinea - no whois server assigned
		"gov" => "whois.nic.gov",
		// gr - Greece - no whois server assigned
		// gt - Guatemala - no whois server assigned
		"gs" => "whois.nic.gs", // South Georgia And The South Sandwich Islands
		// gu - Guam - no whois server assigned
		// gw - Guinea-bissau - no whois server assigned
		"gy" => "whois.registry.gy", // Guyana
		"hk" => "whois.hkirc.hk", // Hong Kong
		// hm - Heard and McDonald Islands (Australia) - no whois server assigned
		"hn" => "whois.nic.hn", // Honduras
		"hr" => "whois.dns.hr", // Croatia
		"ht" => "whois.nic.ht", // Haiti
		"hu" => "whois.nic.hu", // Hungary
		// id - Indonesia - no whois server assigned
		"ie" => "whois.domainregistry.ie", // Ireland
		"il" => "whois.isoc.org.il", // Israel
		"im" => "whois.nic.im", // Isle of Man
		"in" => "whois.inregistry.net", // India
		"info" => "whois.afilias.net",
		"int" => "whois.iana.org",
		"io" => "whois.nic.io", // British Indian Ocean Territory
		"iq" => "whois.cmc.iq", // Iraq
		"ir" => "whois.nic.ir", // Iran, Islamic Republic Of
		"is" => "whois.isnic.is", // Iceland
		"it" => "whois.nic.it", // Italy
		"je" => "whois.je", // Jersey
		// jm - Jamaica - no whois server assigned
		// jo - Jordan - no whois server assigned
		"jobs" => "jobswhois.verisign-grs.com",
		"jp" => "whois.jprs.jp", // Japan
		"ke" => "whois.kenic.or.ke", // Kenya
		"kg" => "www.domain.kg", // Kyrgyzstan
		// kh - Cambodia - no whois server assigned
		"ki" => "whois.nic.ki", // Kiribati
		// km - Comoros - no whois server assigned
		// kn - Saint Kitts And Nevis - no whois server assigned
		// kp - Korea, Democratic People's Republic Of - no whois server assigned
		"kr" => "whois.kr", // Korea, Republic Of
		// kw - Kuwait - no whois server assigned
		// ky - Cayman Islands - no whois server assigned
		"kz" => "whois.nic.kz", // Kazakhstan
		"la" => "whois.nic.la", // Lao People's Democratic Republic
		// lb - Lebanon - no whois server assigned
		// lc - Saint Lucia - no whois server assigned
		"li" => "whois.nic.li", // Liechtenstein
		// lk - Sri Lanka - no whois server assigned
		"lt" => "whois.domreg.lt", // Lithuania
		"lu" => "whois.dns.lu", // Luxembourg
		"lv" => "whois.nic.lv", // Latvia
		"ly" => "whois.nic.ly", // Libya
		"ma" => "whois.iam.net.ma", // Morocco
		// mc - Monaco - no whois server assigned
		"md" => "whois.nic.md", // Moldova
		"me" => "whois.nic.me", // Montenegro
		"mg" => "whois.nic.mg", // Madagascar
		// mh - Marshall Islands - no whois server assigned
		"mil" => "whois.nic.mil",
		// mk - Macedonia, The Former Yugoslav Republic Of - no whois server assigned
		"ml" => "whois.dot.ml", // Mali
		// mm - Myanmar - no whois server assigned
		"mn" => "whois.nic.mn", // Mongolia
		"mo" => "whois.monic.mo", // Macao
		"mobi" => "whois.dotmobiregistry.net",
		"mp" => "whois.nic.mp", // Northern Mariana Islands
		// mq - Martinique (France) - no whois server assigned
		// mr - Mauritania - no whois server assigned
		"ms" => "whois.nic.ms", // Montserrat
		// mt - Malta - no whois server assigned
		"mu" => "whois.nic.mu", // Mauritius
		"museum" => "whois.museum",
		// mv - Maldives - no whois server assigned
		// mw - Malawi - no whois server assigned
		"mx" => "whois.mx", // Mexico
		"my" => "whois.domainregistry.my", // Malaysia
		// mz - Mozambique - no whois server assigned
		"na" => "whois.na-nic.com.na", // Namibia
		"name" => "whois.nic.name",
		"nc" => "whois.nc", // New Caledonia
		// ne - Niger - no whois server assigned
		"net" => "whois.verisign-grs.net",
		"nf" => "whois.nic.nf", // Norfolk Island
		"ng" => "whois.nic.net.ng", // Nigeria
		// ni - Nicaragua - no whois server assigned
		"nl" => "whois.domain-registry.nl", // Netherlands
		"no" => "whois.norid.no", // Norway
		// np - Nepal - no whois server assigned
		// nr - Nauru - no whois server assigned
		"nu" => "whois.nic.nu", // Niue
		"nz" => "whois.srs.net.nz", // New Zealand
		"om" => "whois.registry.om", // Oman
		"org" => "whois.pir.org",
		// pa - Panama - no whois server assigned
		"pe" => "kero.yachay.pe", // Peru
		"pf" => "whois.registry.pf", // French Polynesia
		// pg - Papua New Guinea - no whois server assigned
		// ph - Philippines - no whois server assigned
		// pk - Pakistan - no whois server assigned
		"pl" => "whois.dns.pl", // Poland
		"pm" => "whois.nic.pm", // Saint Pierre and Miquelon (France)
		// pn - Pitcairn (New Zealand) - no whois server assigned
		"post" => "whois.dotpostregistry.net",
		"pr" => "whois.nic.pr", // Puerto Rico
		"pro" => "whois.dotproregistry.net",
		// ps - Palestine, State of - no whois server assigned
		"pt" => "whois.dns.pt", // Portugal
		"pw" => "whois.nic.pw", // Palau
		// py - Paraguay - no whois server assigned
		"qa" => "whois.registry.qa", // Qatar
		"re" => "whois.nic.re", // Reunion (France)
		"ro" => "whois.rotld.ro", // Romania
		"rs" => "whois.rnids.rs", // Serbia
		"ru" => "whois.tcinet.ru", // Russian Federation
		// rw - Rwanda - no whois server assigned
		"sa" => "whois.nic.net.sa", // Saudi Arabia
		"sb" => "whois.nic.net.sb", // Solomon Islands
		"sc" => "whois2.afilias-grs.net", // Seychelles
		// sd - Sudan - no whois server assigned
		"se" => "whois.iis.se", // Sweden
		"sg" => "whois.sgnic.sg", // Singapore
		"sh" => "whois.nic.sh", // Saint Helena
		"si" => "whois.arnes.si", // Slovenia
		"sk" => "whois.sk-nic.sk", // Slovakia
		// sl - Sierra Leone - no whois server assigned
		"sm" => "whois.nic.sm", // San Marino
		"sn" => "whois.nic.sn", // Senegal
		"so" => "whois.nic.so", // Somalia
		// sr - Suriname - no whois server assigned
		"st" => "whois.nic.st", // Sao Tome And Principe
		"su" => "whois.tcinet.ru", // Russian Federation
		// sv - El Salvador - no whois server assigned
		"sx" => "whois.sx", // Sint Maarten (dutch Part)
		"sy" => "whois.tld.sy", // Syrian Arab Republic
		// sz - Swaziland - no whois server assigned
		"tc" => "whois.meridiantld.net", // Turks And Caicos Islands
		// td - Chad - no whois server assigned
		"tel" => "whois.nic.tel",
		"tf" => "whois.nic.tf", // French Southern Territories
		// tg - Togo - no whois server assigned
		"th" => "whois.thnic.co.th", // Thailand
		"tj" => "whois.nic.tj", // Tajikistan
		"tk" => "whois.dot.tk", // Tokelau
		"tl" => "whois.nic.tl", // Timor-leste
		"tm" => "whois.nic.tm", // Turkmenistan
		"tn" => "whois.ati.tn", // Tunisia
		"to" => "whois.tonic.to", // Tonga
		"tp" => "whois.nic.tl", // Timor-leste
		"tr" => "whois.nic.tr", // Turkey
		"travel" => "whois.nic.travel",
		// tt - Trinidad And Tobago - no whois server assigned
		"tv" => "tvwhois.verisign-grs.com", // Tuvalu
		"tw" => "whois.twnic.net.tw", // Taiwan
		"tz" => "whois.tznic.or.tz", // Tanzania, United Republic Of
		"ua" => "whois.ua", // Ukraine
		"ug" => "whois.co.ug", // Uganda
		"uk" => "whois.nic.uk", // United Kingdom
		"us" => "whois.nic.us", // United States
		"uy" => "whois.nic.org.uy", // Uruguay
		"uz" => "whois.cctld.uz", // Uzbekistan
		// va - Holy See (vatican City State) - no whois server assigned
		"vc" => "whois2.afilias-grs.net", // Saint Vincent And The Grenadines
		"ve" => "whois.nic.ve", // Venezuela
		"vg" => "whois.adamsnames.tc", // Virgin Islands, British
		// vi - Virgin Islands, US - no whois server assigned
		// vn - Viet Nam - no whois server assigned
		// vu - Vanuatu - no whois server assigned
		"wf" => "whois.nic.wf", // Wallis and Futuna
		"ws" => "whois.website.ws", // Samoa
		"xxx" => "whois.nic.xxx",
		// ye - Yemen - no whois server assigned
		"yt" => "whois.nic.yt", // Mayotte
		"yu" => "whois.ripe.net");
	
	function LookupDomain($domain){
		global $whoisservers;
		$domain_parts = explode(".", $domain);
		$tld = strtolower(array_pop($domain_parts));
		$whoisserver = $whoisservers[$tld];
		if(!$whoisserver) {
			return "Error: No appropriate Whois server found for $domain domain!";
		}
		$result = QueryWhoisServer($whoisserver, $domain);
		if(!$result) {
			return "Error: No results retrieved from $whoisserver server for $domain domain!";
		}
		else {
			while(strpos($result, "Whois Server:") !== FALSE){
				preg_match("/Whois Server: (.*)/", $result, $matches);
				$secondary = $matches[1];
				if($secondary) {
					$result = QueryWhoisServer($secondary, $domain);
					$whoisserver = $secondary;
				}
			}
		}
		
		
		
		
		$tmp_sql = "INSERT INTO `whois`
					(`whoisid`, `domain`, `details`, `datetime`) 
					VALUES 
					(
					'". $whoisid ."',
					'". $domain ."',
					'". addslashes($result) ."',
					'". datetime() ."'
					);";
		logger3("whois tmp_sql",$tmp_sql);
		$insert_whois_results = insertTHECASHIER($tmp_sql,"peephole.online");
		logger3("whois insert_whois_results",$insert_whois_results);
				
		
		
		return "$domain domain lookup results from $whoisserver server:\n\n" . $result;
	}
	
	function LookupIP($ip) {
		$whoisservers = array(
			//"whois.afrinic.net", // Africa - returns timeout error :-(
			"whois.lacnic.net", // Latin America and Caribbean - returns data for ALL locations worldwide :-)
			"whois.apnic.net", // Asia/Pacific only
			"whois.arin.net", // North America only
			"whois.ripe.net" // Europe, Middle East and Central Asia only
		);
		$results = array();
		foreach($whoisservers as $whoisserver) {
			$result = QueryWhoisServer($whoisserver, $ip);
			if($result && !in_array($result, $results)) {
				$results[$whoisserver]= $result;
			}
		}
		$res = "RESULTS FOUND: " . count($results);
		foreach($results as $whoisserver=>$result) {
			$res .= "\n\n-------------\nLookup results for " . $ip . " from " . $whoisserver . " server:\n\n" . $result;
		}
		return $res;
	}
	
	function ValidateIP($ip) {
		$ipnums = explode(".", $ip);
		if(count($ipnums) != 4) {
			return false;
		}
		foreach($ipnums as $ipnum) {
			if(!is_numeric($ipnum) || ($ipnum > 255)) {
				return false;
			}
		}
		return $ip;
	}
	
	function ValidateDomain($domain) {
		if(!preg_match("/^([-a-z0-9]{2,100})\.([a-z\.]{2,8})$/i", $domain)) {
			return false;
		}
		return $domain;
	}
	
	function QueryWhoisServer($whoisserver, $domain) {
		$port = 43;
		$timeout = 10;
		$fp = @fsockopen($whoisserver, $port, $errno, $errstr, $timeout) or die("Socket Error " . $errno . " - " . $errstr);
		//if($whoisserver == "whois.verisign-grs.com") $domain = "=".$domain; // whois.verisign-grs.com requires the equals sign ("=") or it returns any result containing the searched string.
		fputs($fp, $domain . "\r\n");
		$out = "";
		while(!feof($fp)){
			$out .= fgets($fp);
		}
		fclose($fp);
	
		$res = "";
		if((strpos(strtolower($out), "error") === FALSE) && (strpos(strtolower($out), "not allocated") === FALSE)) {
			$rows = explode("\n", $out);
			foreach($rows as $row) {
				$row = trim($row);
				if(($row != '') && ($row{0} != '#') && ($row{0} != '%')) {
					$res .= $row."\n";
				}
			}
		}
		return $res;
	}
}

function check_and_fix_hostname_for_name($proposed_hostname) {
		
	//test("proposed_hostname",$proposed_hostname);
	
	$tmp_host_name = $proposed_hostname;
	//test("2tmp_host_name",$tmp_host_name);
	
	/// preg-replace approstrphy only
	$tmp_host_name = str_replace("'", "", $tmp_host_name);
	//test("4tmp_host_name",$tmp_host_name);
	
	
	/// preg-replace everything else
	$tmp_host_name = preg_replace('#[^A-Za-z0-9-.]#', '-', $tmp_host_name);
	//test("3tmp_host_name",$tmp_host_name);
	
	
	////////////////////////////////
	/// test for ending-hyphan once
	////////////////////////////////
	
	/// delete the last char if it is a hyphan:
	$tmp_host_name_exploded = str_split($tmp_host_name);
	//test("tmp_host_name_exploded",$tmp_host_name_exploded);
	
	$tmp_host_name_exploded_reversed = array_reverse($tmp_host_name_exploded);
	//test("tmp_host_name_exploded_reversed",$tmp_host_name_exploded_reversed);

	
	if($tmp_host_name_exploded_reversed[0] == "-") {
		// delete the "-" / first char
		
		// make it a reversed string
		$tmp_host_name_exploded_reversed_string = implode($tmp_host_name_exploded_reversed);
		
		//trim the string:
		$tmp_host_name_exploded_reversed_string_trimmmed =  $tmp_host_name_exploded_reversed_string = substr($tmp_host_name_exploded_reversed_string, 1);
		
		//explode the string:
		$tmp_host_name_exploded_reversed_string_exploded = str_split($tmp_host_name_exploded_reversed_string);
		
		//reverse te exmploded string
		$tmp_host_name_exploded_reversed_string_exploded_reversed = array_reverse($tmp_host_name_exploded_reversed_string_exploded);
		
		//implode the re-reverserion:
		$tmp_host_name = implode($tmp_host_name_exploded_reversed_string_exploded_reversed);
	}
	
	
	////////////////////////////////
	/// test for ending-hyphan TWICE
	////////////////////////////////
	
	/// delete the last char if it is a hyphan:
	$tmp_host_name_exploded = str_split($tmp_host_name);
	//test("tmp_host_name_exploded",$tmp_host_name_exploded);
	
	$tmp_host_name_exploded_reversed = array_reverse($tmp_host_name_exploded);
	//test("tmp_host_name_exploded_reversed",$tmp_host_name_exploded_reversed);

	
	if($tmp_host_name_exploded_reversed[0] == "-") {
		// delete the "-" / first char
		
		// make it a reversed string
		$tmp_host_name_exploded_reversed_string = implode($tmp_host_name_exploded_reversed);
		
		//trim the string:
		$tmp_host_name_exploded_reversed_string_trimmmed =  $tmp_host_name_exploded_reversed_string = substr($tmp_host_name_exploded_reversed_string, 1);
		
		//explode the string:
		$tmp_host_name_exploded_reversed_string_exploded = str_split($tmp_host_name_exploded_reversed_string);
		
		//reverse te exmploded string
		$tmp_host_name_exploded_reversed_string_exploded_reversed = array_reverse($tmp_host_name_exploded_reversed_string_exploded);
		
		//implode the re-reverserion:
		$tmp_host_name = implode($tmp_host_name_exploded_reversed_string_exploded_reversed);
	}
	
	
	////////////////////////////////
	/// test for ending-period ONCE
	////////////////////////////////
	
	/// delete the last char if it is a hyphan:
	$tmp_host_name_exploded = str_split($tmp_host_name);
	//test("tmp_host_name_exploded",$tmp_host_name_exploded);
	
	$tmp_host_name_exploded_reversed = array_reverse($tmp_host_name_exploded);
	//test("tmp_host_name_exploded_reversed",$tmp_host_name_exploded_reversed);

	
	
	if($tmp_host_name_exploded_reversed[0] == ".") {
		// delete the "-" / first char
		
		// make it a reversed string
		$tmp_host_name_exploded_reversed_string = implode($tmp_host_name_exploded_reversed);
		
		//trim the string:
		$tmp_host_name_exploded_reversed_string_trimmmed =  $tmp_host_name_exploded_reversed_string = substr($tmp_host_name_exploded_reversed_string, 1);
		
		//explode the string:
		$tmp_host_name_exploded_reversed_string_exploded = str_split($tmp_host_name_exploded_reversed_string);
		
		//reverse te exmploded string
		$tmp_host_name_exploded_reversed_string_exploded_reversed = array_reverse($tmp_host_name_exploded_reversed_string_exploded);
		
		//implode the re-reverserion:
		$tmp_host_name = implode($tmp_host_name_exploded_reversed_string_exploded_reversed);
	}
	
	
	////////////////////////////////
	/// test for ending-period TWICE
	////////////////////////////////
	

	/// delete the last char if it is a hyphan:
	$tmp_host_name_exploded = str_split($tmp_host_name);
	//test("tmp_host_name_exploded",$tmp_host_name_exploded);
	
	$tmp_host_name_exploded_reversed = array_reverse($tmp_host_name_exploded);
	//test("tmp_host_name_exploded_reversed",$tmp_host_name_exploded_reversed);


	
	if($tmp_host_name_exploded_reversed[0] == ".") {
		// delete the "-" / first char
		
		// make it a reversed string
		$tmp_host_name_exploded_reversed_string = implode($tmp_host_name_exploded_reversed);
		
		//trim the string:
		$tmp_host_name_exploded_reversed_string_trimmmed =  $tmp_host_name_exploded_reversed_string = substr($tmp_host_name_exploded_reversed_string, 1);
		
		//explode the string:
		$tmp_host_name_exploded_reversed_string_exploded = str_split($tmp_host_name_exploded_reversed_string);
		
		//reverse te exmploded string
		$tmp_host_name_exploded_reversed_string_exploded_reversed = array_reverse($tmp_host_name_exploded_reversed_string_exploded);
		
		//implode the re-reverserion:
		$tmp_host_name = implode($tmp_host_name_exploded_reversed_string_exploded_reversed);
	}
	
	
	
		
	
	
	//test("tmp_host_name",$tmp_host_name);
	return $tmp_host_name;


}	
	




function create_photoBANGK_record(
$path_to_record,
$filename,
$file_type,
$width_points,
$height_points,
$filesize_megs,
$price_online,
$price_wallpaper,
$price_print,
$key_words,
$member_hash,
$account_hash,
$photoBANGK_quick_link,
$photoBANGK_portfolio_hash
) {
	
	$photoBANGK_hash = hash_me();
	
	if(empty($photoBANGK_quick_link)) $photoBANGK_quick_link = make_photoBANGK_quick_link();
	
	$tmp_sql = "INSERT INTO `photoBANGK`
				(
					
				`photoBANGK_id`, 
				`path_to_record`, 
				`filename`,
				`file_type`, 
				`password`,
				
				`width_points`, 
				`height_points`, 
				`filesize_megs`,
				
				`price_online`,
				`price_wallpaper`,
				`price_print`,
				`key_words`,
				
				`member_hash`,
				`account_hash`,
				
				`photoBANGK_hash`,
				
				`quick_link`,
				
				`photoBANGK_portfolios_hash`,
				 
				`datetime_created`
				) VALUES (
					
				'". $_XXX_ ."',
				'". $path_to_record ."',
				'". $filename ."',
				'". $file_type ."',
				'". $password ."',
				
				'". $width_points ."',
				'". $height_points ."',
				'". $filesize_megs ."',
				
				'". $price_online ."',
				'". $price_wallpaper ."',
				'". $price_print ."',
				'". $key_words ."',
				
				'". $member_hash ."',
				'". $account_hash ."',
				
				'". $photoBANGK_hash ."',
				'". $photoBANGK_quick_link ."',
				'". $photoBANGK_portfolio_hash ."',
				'". datetime() ."'
				)";
	//test("tmp_sql",$tmp_sql);
	$insert_results = insertTHECASHIER($tmp_sql);
	//test("insert_results",$insert_results);
	if($insert_results > 0) { 
		return $photoBANGK_hash;
	} else {
		return false;
	}
	
}

function make_photoBANGK_quick_link() {

	$quick_link_accepted = false;
	while($quick_link_accepted == false) {
		
		$quick_link = host_prefix_maker($desired_random_string_length=9);
		
		$quick_link_exploded = str_split($quick_link, 3);
		
		
		$quick_link_proposed = $quick_link_exploded[0] . "-" . $quick_link_exploded[1] . "-" . $quick_link_exploded[2];
		
		
		$tmp_sql = "SELECT quick_link FROM photoBANGK WHERE quick_link = '". $quick_link_proposed ."';";
		$quick_link_already_exists = "";
		$quick_link_already_exists = getTHECASHIER($tmp_sql);
		if(empty($quick_link_already_exists)) {
			$quick_link_accepted = $quick_link_proposed;
		}
	
	}
	
	return $quick_link_accepted;
}



function make_paparaz_mode_quick_link($member_hash="",$account_hash="",$price_per_photo="",$price_lot_photos="",$device="") {

	$quick_link_accepted = false;
	
	while($quick_link_accepted == false) {
		
		$quick_link = host_prefix_maker($desired_random_string_length=9);
		
		$quick_link_exploded = str_split($quick_link, 3);
		
		
		$quick_link_proposed = $quick_link_exploded[0] . "-" . $quick_link_exploded[1] . "-" . $quick_link_exploded[2];
		
		
		$tmp_sql = "SELECT quick_link FROM paparaz_mode WHERE quick_link = '". $quick_link_proposed ."';";
		$quick_link_already_exists = "";
		$quick_link_already_exists = getTHECASHIER($tmp_sql);
		if(empty($quick_link_already_exists)) {
			
			/// SET PAPARAZ QUICK LINK
			$quick_link_accepted = $quick_link_proposed;
			
			$_XXXXX_paparaz_mode_id = "";
			$_XXXXX_hash = hash_me();
			$_XXXXX_member_hash = $member_hash;
			$_XXXXX_account_hash = $account_hash;
			$_XXXXX_quick_link = $quick_link_accepted;
			$_XXXXX_price_per_photo = $price_per_photo;
			$_XXXXX_price_lot_photos = $price_lot_photos;
			$_XXXXX_device = $device;
			$_XXXXX_datetime_created = datetime();
			$_XXXXX_datetime_updated = $_XXXXX_datetime_created;
			
			$tmp_sql = "INSERT INTO `paparaz_mode`
						(`paparaz_mode_id`
						, `hash`
						, `member_hash`
						, `account_hash`
						, `quick_link`
						, `price_per_photo`
						, `price_lot_photos`
						, `device`
						, `datetime_created`
						) VALUES (
						'". $_XXXXX_paparaz_mode_id ."'
						,'". $_XXXXX_hash ."'
						,'". $_XXXXX_member_hash ."'
						,'". $_XXXXX_account_hash ."'
						,'". $_XXXXX_quick_link ."'
						,'". $_XXXXX_price_per_photo ."'
						,'". $_XXXXX_price_lot_photos ."'
						,'". $_XXXXX_device ."'
						,'". $_XXXXX_datetime_created ."'
						);";
			logger3("tmp_sql",$tmp_sql);
			$insert_results = insertTHECASHIER($tmp_sql);
			logger3("insert_results",$insert_results);
			
			/// SET PROTFOLIO
			$_XXXXX_photoBANGK_portfolios_id = "";
			$_XXXXX_photoBANGK_portfolios_hash = hash_me();
			$_XXXXX_title = $quick_link_accepted;
			$_XXXXX_password = "";
			$_XXXXX_member_hash = $member_hash;
			$_XXXXX_account_hash = $account_hash;
			
			$tmp_sql = "INSERT INTO `photoBANGK_portfolios`
						(
						`photoBANGK_portfolios_id`
						, `photoBANGK_portfolios_hash`
						, `title`
						, `password`
						, `account_hash`
						, `member_hash`
						, `datetime_created`
						, `datetime_updated`
					
						) VALUES (
					
						'". $_XXXXX_photoBANGK_portfolios_id ."'
						,'". $_XXXXX_photoBANGK_portfolios_hash ."'
						,'". $_XXXXX_title ."'
						,'". $_XXXXX_password ."'
						,'". $_XXXXX_account_hash ."'
						,'". $_XXXXX_member_hash ."'
						,'". $_XXXXX_datetime_created ."'
						,'". $_XXXXX_datetime_updated ."'
						);";
			logger3("tmp_sql",$tmp_sql);
			$_XXXXX_photoBANGK_portfolios_id = insertTHECASHIER($tmp_sql);
			logger3("insert_results",$insert_results);
			
			
			
		}
	
	}
	
	$tmp_quick_link_accepted = strtoupper($quick_link_accepted);
	
	$return['portfolio_quick_link'] = $tmp_quick_link_accepted;
	$return['portfolio_id'] = $_XXXXX_photoBANGK_portfolios_id;
	$return['portfolio_hash'] = $_XXXXX_photoBANGK_portfolios_hash;
	
	echo json_encode($return);
	
	//NOTE: we need t create a cron script to delete any references after 72 of posted date.
	
}



function update_photoBANGK_record(
$photoBANGK_hash,
$path_to_record,
$filename,
$width_points,
$height_points,
$filesize_megs,
$price_online,
$price_wallpaper,
$price_print,
$key_words,
$member_hash,
$account_hash,
$photoBANGK_portfolios_hash
) {
	
	//$photo_hash = hash_me();
	$tmp_sql = "";
	$tmp_sql .= "UPDATE `photoBANGK` SET";
	

	if(!empty($path_to_record)) $tmp_sql .= " `path_to_record` = '". $path_to_record ."',";
	if(!empty($filename)) $tmp_sql .= " `filename` = '". $filename ."',";
	//if(!empty($filename)) $tmp_sql .= " `password` = '". $password ."',";
	if(!empty($width_points)) $tmp_sql .= " `width_points` = '". $width_points ."',";
	if(!empty($height_points)) $tmp_sql .= " `height_points` = '". $height_points ."',";
	if(!empty($filesize_megs)) $tmp_sql .= " `filesize_megs` = '". $filesize_megs ."',";
	
	if($price_online != '') $tmp_sql .= " `price_online`='". $price_online ."',";
	if($price_wallpaper != '') $tmp_sql .= " `price_wallpaper`='". $price_wallpaper ."',";
	if($price_print != '') $tmp_sql .= " `price_print`='". $price_print ."',";
	if(!empty($key_words)) $tmp_sql .= " `key_words`='". $key_words ."',";
	
	if(!empty($member_hash)) $tmp_sql .= " `member_hash` = '". $member_hash ."',";
	if(!empty($account_hash)) $tmp_sql .= " `account_hash` = '". $account_hash ."',";
	
	//if(!empty($photoBANGK_portfolios_id)) $tmp_sql .= " `photoBANGK_portfolios_id` = '". $photoBANGK_portfolios_id ."',";
	
	if(!empty($photoBANGK_portfolios_hash)) $tmp_sql .= " `photoBANGK_portfolios_hash` = '". $photoBANGK_portfolios_hash ."',";

	$tmp_sql .= " `datetime_updated` = '". datetime() ."'";
	
	$tmp_sql .= " WHERE photoBANGK_hash = '". $photoBANGK_hash ."';";
	
	///test("tmp_sql",$tmp_sql);
	
	$insert_results = updateTHECASHIER($tmp_sql);
	
	//test("insert_results",$insert_results);
	
	///	
	
	return $insert_results;
}

require $master_config_root_path . "shared/aws/aws-autoloader.php";
//S3 UPLOAD
use Aws\S3\S3Client;
use Aws\Credentials\Credentials;
use Aws\S3\Exception\S3Exception;

use Aws\S3\MultipartUploader;
use Aws\Exception\MultipartUploadException;

$credentials = new Aws\Credentials\Credentials($master_config_aws_key, $master_config_aws_secret);
$sharedConfig = [
    'region'  => 'us-west-2',
    'version' => 'latest',
    'credentials' => $credentials
];
$aws_sdk = new Aws\Sdk($sharedConfig);
$s3client = $aws_sdk->createS3();
//$master_config_aws_bucket;

function aws_s3_upload_old($file, $bucket = 'nsdbphotobangk'){
	global $s3client;
	try{
		if(is_file($file)){				
			$result = $s3client->putObject([
			    'ACL' => 'public-read',	   
			    'Bucket' => $bucket,
			    'Key' => $file,
			    'SourceFile' => $file,
			]);	
			unlink($file);			
		}
		//else echo 'File not found';		
	}
	catch(S3Exception $e){
		//echo 'AWS S3 Upload ERROR:', $e->getMessage();
	}
}

function aws_s3_upload($file_path, $bucket = 'nsdbphotobangk', $keep_source = false){
	global $master_config_aws_key, $master_config_aws_secret, $s3client;		
	
	try{
		if(is_file($file_path)){				
			$uploader = new MultipartUploader($s3client, $file_path, [
			    'bucket' => $bucket,
			    'key'    => basename($file_path),
			    'ACL'    => 'public-read',
			]);
			
			$result = $uploader->upload();						
			if(!$keep_source) unlink($file_path);
			return $result['ObjectURL'];			
		}
		else return false;		
	}
	catch(MultipartUploadException $e){
		//echo 'AWS S3 Upload ERROR:', $e->getMessage();
		logger3('AWS S3 Upload ERROR', $e->getMessage());
		return false;
	}
}

function format_photoBANGK_photo_extension($extension){
	logger3("format_photoBANGK_photo_extension(: extension",$extension);
	$new_extension = $extension;
	$path_parts = pathinfo($extension);
	logger3("format_photoBANGK_photo_extension(: path_parts",$path_parts);
	$tmp_extension = $path_parts['extension'];
	logger3("format_photoBANGK_photo_extension(: tmp_extension",$tmp_extension);
	if(empty($tmp_extension)) $tmp_extension = $extension;
	
	if(in_array(strtolower($tmp_extension), ["png", "gif"])){
		$new_extension = $tmp_extension;
	}
	else{ $new_extension = "jpg"; }
	return $new_extension;
}

function format_photoBANGK_video_extension($extension){
	logger3("format_photoBANGK_video_extension(: extension",$extension);
	$new_extension = $extension;
	$path_parts = pathinfo($extension);
	logger3("format_photoBANGK_video_extension(: path_parts",$path_parts);
	$tmp_extension = $path_parts['extension'];
	logger3("format_photoBANGK_video_extension(: tmp_extension",$tmp_extension);
	if(empty($tmp_extension)) $tmp_extension = $extension;
	
	/*
if(in_array(strtolower($tmp_extension), ["png", "gif"])){
		$new_extension = $tmp_extension;
	}
	else{ $new_extension = "jpg"; }
*/

	$new_extension = $tmp_extension;
	return $new_extension;
}

function calculate_image_dimension($type="social",$original_height="420",$original_width="800"){
	
	$new_dimension = array();
	$type = strtolower($type);
	$height = $original_height;
	$width = $original_width;
	
	switch($type){
		case 'thumb':
			$max_width = 250;
			$max_height = 135;
			break;
		
		case 'slideshow':
			$max_width = 1180;
			$max_height = 620;
			break;
		
		case 'gallery_preview':
			$max_width = 800;
			$max_height = 420;
			break;
			
		case 'social':
			$max_width = 470;
			$max_height = 247;
			if($height > $width){				
				$max_width = 316; //158
				$max_height = 474; //237
			}
			$new_dimension['max_width'] = $max_width;
			$new_dimension['max_height'] = $max_height;
			$new_dimension['new_width'] = $max_width;
			$new_dimension['new_height'] = $max_height;
			return $new_dimension;
			break;
		
		case 'wallpaper':
			$max_width = 2000;
			$max_height = 1400;
			break;
		case 'large_wallpaper':
			$max_width = 2600;
			$max_height = 1400;
			break;
			
		case strtolower('blast_BRAND_WATERMARK_PRICING_BIG_WALLPAPER'):
		case strtolower('blast_BRAND_WATERMARK_PRICING_NORMAL_WALLPAPER'):
		case strtolower('blast_BRAND_WATERMARK_WALLPAPER'):
		case strtolower('blast_BRANDING_ONLY_WALLPAPER'):
			$max_width = 2000;
			$max_height = 1400;
			break;
		case strtolower('blast_BRAND_WATERMARK_PRICING_BIG_TWITTER_WALLPAPER'):
		case strtolower('blast_BRAND_WATERMARK_PRICING_NORMAL_TWITTER_WALLPAPER'):	
		case strtolower('blast_BRAND_WATERMARK_TWITTER_WALLPAPER'):
		case strtolower('blast_BRANDING_ONLY_TWITTER_WALLPAPER'):	
			$max_width = 1350;
			$max_height = 1350;
			break;
		case strtolower('blast_BRAND_WATERMARK_PRICING_BIG_SOCIAL'):
		case strtolower('blast_BRAND_WATERMARK_PRICING_NORMAL_SOCIAL'):
		case strtolower('blast_BRAND_WATERMARK_PRICING_BIG_TWITTER_SOCIAL'):
		case strtolower('blast_BRAND_WATERMARK_PRICING_NORMAL_TWITTER_SOCIAL'):
		case strtolower('blast_BRAND_WATERMARK_TWITTER_SOCIAL'):
		case strtolower('blast_BRANDING_ONLY_TWITTER_SOCIAL'):
		case strtolower('blast_BRAND_WATERMARK_SOCIAL'):
		case strtolower('blast_BRANDING_ONLY_SOCIAL'):
			$max_width = 800;
			$max_height = 420;			
			break;
			
		case 'original':
			$max_width = $width;
			$max_height = $height;
			
			$new_dimension['max_width'] = $max_width;
			$new_dimension['max_height'] = $max_height;
			$new_dimension['new_width'] = $max_width;
			$new_dimension['new_height'] = $max_height;
			return $new_dimension;
			
			break;
		
		default:
	}		
	$new_dimension['max_width'] = $max_width;
	$new_dimension['max_height'] = $max_height;
	//test('$type', $type);	
	//test('$new_dimension', $new_dimension);	
	//exit;
	if($height > $width){
		$tmp_max_width = $max_width;
		$max_width = $max_height;
		$max_height = $tmp_max_width;
	}

	//SET NEW WIDTH and HEIGHT
	if(empty($max_width)) $max_width = $width;
	if(empty($max_height)) $max_height = $height;
	
	$new_width = intval($max_width);
	$new_height = intval($max_height);
	if($new_width<1) $new_width = $width;
	if($new_height<1) $new_height = $height;
	
	if($new_width >= $width) $new_width = $width;
	if($new_height >= $height) $new_height = $height;

	if($width != $new_height){
		if($width >= $height) {
			$ratio = $new_width / $width;
		    $new_height = $height * $ratio;						    
		}
		else{
			$ratio = $new_height / $height;
		    $new_width = $width * $ratio;
		}
	}
	//echo '<br>1. ' , $width, ' 2. ', $height, ' 3. ', $new_width, ' 4. ', $new_height, ' 5. ', $max_width, ' 6. ', $max_height;
	if($new_width > $max_width){
		$new_width = $max_width;
		$ratio = $new_width / $width;
		$new_height = $height * $ratio;
	}
	if($new_height > $max_height){
		$new_height = $max_height;
		$ratio = $new_height / $height;
		$new_width = $width * $ratio;
	}
	
	$new_dimension['new_width'] = $new_width;
	$new_dimension['new_height'] = $new_height;
	
	//echo '<br>1. ' , $width, ' 2. ', $height, ' 3. ', $new_width, ' 4. ', $new_height, ' 5. ', $max_width, ' 6. ', $max_height; exit;
	
	return $new_dimension;

}

function create_gallery_preview_image($prefix = 'gallery_preview_', $filename, $max_width, $max_height, $wartermarktext, $corner_text_array ){

	global $master_config_root_path;
	//$prefix = strtolower($prefix);
	$output = '';
	if(!empty($filename) && is_file($filename)) {
		$image_info = pathinfo($filename);
		$target_path = $image_info['dirname'] . '/';
		if(in_array(strtolower($image_info['extension']), ["png", "gif", "jpg", "jpeg", "tiff", "tif", "raw"])){		
			//$thumb_name = $prefix . $image_info['filename'] . '.' . $image_info['extension'];
			$new_extension = format_photoBANGK_photo_extension($image_info['extension']);
			$thumb_name = $prefix . $image_info['filename'] . '.' . $new_extension;
			$newFielName = $image_info['dirname'] .'/' . $thumb_name ;						
			$image_page1 = $target_path . 'image_page1_' . time() . '.' . $new_extension;
			
			try{
				// Create objects
				$image = new Imagick($filename);
				/*
$dimension = $image->getImageGeometry();	 	
				//$size=$image->getImageSize();			
				$width = $dimension['width'];
				$height = $dimension['height'];	
*/		
				//some images have multiple page, so take first page before generation thumb			
				foreach($image as $i=>$page) {			 				
					$image->writeImage($image_page1);
					break;					
				}
				$image->clear();
				
				$image = new Imagick($image_page1);
				$dimension = $image->getImageGeometry();	 	
				//$size=$image->getImageSize();			
				$width = $dimension['width'];
				$height = $dimension['height'];				
				
				extract(calculate_image_dimension(trim($prefix, '_'), $original_height=$height, $original_width=$width));
				
				if($prefix == 'social_'){					
					$image->cropThumbnailImage( $max_width, $max_height );
				}
				
				
				//$image = new Imagick();
				//$image->newImage($width, $height, new ImagickPixel('none'));
				
				//echo '<br>1. ' , $width, ' 2. ', $height, ' 3. ', $new_width, ' 4. ', $new_height, ' 5. ', $max_width, ' 6. ', $max_height; exit;			
				$image->thumbnailImage($new_width, 0);
				
				$watermark = new Imagick();
				// Watermark text
				$text = $wartermarktext;
				//$line_width = $width;// strlen($text) * 50;
				
				$font_name = 'Helvetica';
				
				$text_length = strlen($text);
				if($text_length<7) $text_length = 7;
				
				if($height > $width){
					$font_width = $new_height;
					$font_size = round(($font_width * 15 / 1000) * (($new_width * 2) / $new_height));
					if($prefix == 'social_'){
						$font_width = $new_width;
						$font_size = round(($font_width * 15 / 1000) * (($new_height * 2) / $new_width));
					}
				}
				else{
					$font_width = $new_width;
					//if($new_height > $new_width) $font_width = $new_height;
					//$font_size = round(($font_width * 3) / 100); // 2%
					$font_size = round(($font_width * 15 / 1000) * (($new_height * 2) / $new_width));
				}
				
				if($font_size<10) $font_size = 10;
				//test('font_size', $font_size);								
												
				$line_width = $new_width * $text_length / ( ($new_width/$font_size) * 1.2 );
				if($line_width>$new_width) $line_width = $new_width;
				
				$line_height = ($font_size * 2) + 35;
				//if($line_height<100) $line_height = 100;											
									
				// Create a new drawing palette
				$draw = new ImagickDraw();
				$watermark->newImage($line_width, $line_height, new ImagickPixel('none'));
				// Set font properties
				$draw->setFont($font_name);
				$draw->setFontSize( $font_size );
				$draw->setFillColor('grey');
				
				$opacity = $_GET['opa']?$_GET['opa']:.2;
				$draw->setFillOpacity($opacity);
				
				$textWidth = 0;
				$textHeight = 0;
				$textPadding = 0;
				$top_bar_height = 0;
				$bottom_bar_height = 0;
				$small_font_percent = 70;
				$font_size_social = $font_size * $small_font_percent / 100;
				if($prefix == 'social_'){
					$font_size_social = $font_size * 1.3;
				
					$draw->setFontSize( $font_size_social);	
					$metrics = $image->queryFontMetrics($draw, "You Can Buy This Photo!");
					if($metrics['textWidth'] > ($new_width/2)){
						//$font_size_social = round(($font_size_social * ($new_width/3)) / $metrics['textWidth']);
						//test('', $metrics);
						//test('', $font_size_social . ' ' . $metrics['textWidth'] . ' ' . $new_width/2);exit;
					}
				}
				
				$blast_BRAND_WATERMARK_PRICING_BIG_adjustment_percent = 1.75; //75% large
				
				if(!empty($corner_text_array) && is_array($corner_text_array)){	
					$draw->setFontSize( $font_size_social);	
					$metrics = $image->queryFontMetrics($draw, $text);
					//test('metrics', $metrics);
					//$textHeight = $metrics['textHeight'];
					$textWidth = $metrics['characterWidth'];
					$textHeight = $metrics['characterHeight'];
					$textPadding = $textHeight/2;
					if($prefix == 'social_'){
						//$textPadding = $textHeight/4;
						//$textPadding = $textHeight/1.5;
					}					
					
					if(!empty($corner_text_array['top_left']) || !empty($corner_text_array['top_right'])){
						$top_bar_height = ceil(($textHeight*2) + ($textPadding*4));
						//test('', '>'.$prefix.'<'); exit;
						
						if(stristr($prefix, 'blast_BRAND_WATERMARK_PRICING_BIG_') !== FALSE) {						
							$top_bar_height = $top_bar_height * $blast_BRAND_WATERMARK_PRICING_BIG_adjustment_percent;
						}
					}
					if(!empty($corner_text_array['bottom_left']) || !empty($corner_text_array['bottom_right'])){
						$bottom_bar_height = ceil(($textHeight * 2) + ($textPadding/2));
						//$bottom_bar_height = ceil($textHeight + $textPadding);
					}					
				}
				$draw->setFontSize( $font_size );
				//$textPadding = 0;
				//test('size', 'top_bar_height= ' . $top_bar_height . 'bottom_bar_height=' . $bottom_bar_height . 'new_widht' . $new_width . 'new_height=' . $new_height  ); exit;
				
				//if($watermark_position=='tile'){	
				if(!empty($text)){						
					// Position text at the top left of the watermark
					$draw->setGravity(Imagick::GRAVITY_NORTHWEST);				
					// Draw text on the watermark
					$watermark->annotateImage($draw, 10, 10, 0, $text);				
					$draw->setFillColor('#444444');
					$draw->setFillOpacity($opacity);
					$watermark->annotateImage($draw, 9, 9, 0, $text);					
					// Position text at the bottom right of the watermark
					$draw->setGravity(Imagick::GRAVITY_SOUTHEAST);	
					$draw->setFillColor('grey');
					$draw->setFillOpacity($opacity);		
					// Draw text on the watermark
					$watermark->annotateImage($draw, 5, 15, 0, $text);				
					$draw->setFillColor('#444444');
					$draw->setFillOpacity($opacity);
					$watermark->annotateImage($draw, 4, 14, 0, $text);	
					
					$vertical_start = $top_bar_height;
					if($prefix == 'social_'){
						$vertical_start = 0;
					}			
					// Repeatedly overlay watermark on image
					for ($w = 0; $w < $image->getImageWidth(); $w += $line_width) {
					    for ($h = $vertical_start; $h < $image->getImageHeight() - ($top_bar_height+$textPadding); $h += $line_height ) {
					        $image->compositeImage($watermark, Imagick::COMPOSITE_OVER, $w, $h);
					    }
					}
				}								
				
				if(!empty($corner_text_array) && is_array($corner_text_array)){	
					
					//$small_font_percent = 100;
					//$font_size = $font_size * $small_font_percent / 100;						
					$draw->setFontSize( $font_size );
					$metrics = $image->queryFontMetrics($draw, "TEST WATERMARK");
					$textHeight = $metrics['characterHeight'];
					//$bottom_bar_height = $textHeight*2;
					if($corner_text_array['action'] == 'download'){
						$bottom_bar_height = ceil($textHeight + $textPadding);
					}	
													
					$top_left_text = $corner_text_array['top_left'];
					$top_right_text = $corner_text_array['top_right'];
					$bottom_left_text = $corner_text_array['bottom_left'];
					$bottom_right_text = $corner_text_array['bottom_right'];
					$gallery_quick_link = $corner_text_array['gallery_quick_link'];										
									
					$opacity = 0.8;
					//$font_size = round($new_width * 10 / 900);
					$draw->setFontSize( $font_size );
															
					$top_bar = new Imagick();
					$top_bar->newImage($new_width, $top_bar_height, new ImagickPixel('#00000090')); // 90% opacity
					$bottom_bar = new Imagick();
					$bottom_bar->newImage($new_width, $bottom_bar_height , new ImagickPixel('#00000090')); // 90% opacity
					
					if(stristr($prefix, 'blast_BRAND_WATERMARK_PRICING_BIG_') !== FALSE) {
						$font_size_social = $font_size_social * $blast_BRAND_WATERMARK_PRICING_BIG_adjustment_percent;
						$textHeight = $textHeight * $blast_BRAND_WATERMARK_PRICING_BIG_adjustment_percent;
						$textPadding = $textPadding * $blast_BRAND_WATERMARK_PRICING_BIG_adjustment_percent;
					}
					if(!empty($top_left_text)){
						
						// Position text at the top left of the watermark
						$draw->setGravity(Imagick::GRAVITY_NORTHWEST);				
						$draw->setFont('/usr/share/fonts/helvetica/Helvetica75-Bold.ttf');
						$draw->setFillColor('white');
						//$draw->setFontSize( $font_size_social);
						$draw->setFontSize( $font_size_social * 110 / 100 );	//110%
						$draw->setFillOpacity($opacity);
						$top_bar->annotateImage($draw, $textPadding, $textPadding*2, 0, "You Can Buy This Photo!");
						$draw->setFont($font_name);
						//$draw->setFontSize( $font_size * $small_font_percent / 100 ); // 70%
						$draw->setFontSize( $font_size_social);
						$draw->setFont('Helvetica');
						if($prefix == 'social_'){
							$top_bar->annotateImage($draw, $textPadding, ($textPadding*2)+($textPadding*2), 0, "ROYALTY-FREE");
						}
						else{
							$top_bar->annotateImage($draw, $textPadding, ($textPadding*4)+($textPadding/2), 0, "ROYALTY-FREE");				
						}			
					}
					if(!empty($top_right_text)){						
						// Position text at the top right of the watermark
						$draw->setGravity(Imagick::GRAVITY_NORTHEAST);
						$draw->setFont('Helvetica');
						//$draw->setFont('/usr/share/fonts/helvetica/Helvetica75-Bold.ttf');
						$draw->setFillColor('white');
						//$draw->setFontSize( $font_size * $small_font_percent / 100 ); // 80%
						//$draw->setFontSize( $font_size );
						$draw->setFontSize( $font_size_social );
						if(!is_array($top_right_text)){							
							$top_bar->annotateImage($draw, $textPadding, $textPadding, 0, $top_right_text);
						}
						else{
							$tmp_price_max_length = 0;
							$tmp_price_width = 0;
							foreach($top_right_text as $key=>$value){
								//if(strlen($value) > $tmp_price_max_length) $tmp_price_max_length = strlen($value);
								$draw->setFont('/usr/share/fonts/helvetica/Helvetica75-Bold.ttf');
								//$draw->setFontSize( $font_size );
								//$draw->setFontSize( $font_size_social );
								$draw->setFontSize( $font_size_social * 1.0 );
								$metrics = $image->queryFontMetrics($draw, $value . " USD");					
								$nextTextWidth = $metrics['textWidth'];
								if($nextTextWidth > $tmp_price_width) $tmp_price_width = $nextTextWidth;
							}
							//$tmp_price_width = $tmp_price_max_length * $textWidth; 
							//if($tmp_price_width<80) $tmp_price_width = 80;
							
							$tmp_t_r_height = $textPadding;
							foreach($top_right_text as $key=>$value){	
								
								if(strtoupper($value) != 'FREE'){
									//$draw->setTextUnderColor('#ff0000');
									$draw->setFont('Helvetica');
									//$draw->setFont('/usr/share/fonts/helvetica/Helvetica75-Bold.ttf');
									$draw->setFillColor('white');
									//$draw->setFontSize( $font_size * $small_font_percent / 100 ); // 80%
									$draw->setFontSize( $font_size_social * 0.7 );									
									$top_bar->annotateImage($draw, $textPadding, $tmp_t_r_height, 0, "USD");
								}
								
								$draw->setFont('/usr/share/fonts/helvetica/Helvetica75-Bold.ttf');
								$draw->setFontSize( $font_size );						
								$draw->setFontSize( $font_size_social );	
								$draw->setFillColor('white');							
								$metrics = $image->queryFontMetrics($draw, "USD");					
								$nextTextWidth = $metrics['textWidth'];
								

								if(strtoupper($value) == 'FREE'){
									$draw->setFont('Helvetica');
									//$draw->setFont('/usr/share/fonts/helvetica/Helvetica75-Bold.ttf');
									$draw->setFillColor('white');
									//$draw->setFontSize( $font_size * $small_font_percent / 100 ); // 80%
									$draw->setFontSize( $font_size );
									$draw->setFontSize( $font_size_social );
								}
								else {
									$draw->setFont('/usr/share/fonts/helvetica/Helvetica75-Bold.ttf');
									$draw->setFillColor('white');
									$draw->setFontSize( $font_size );
									$draw->setFontSize( $font_size_social * 1.0 );
								}								
								$top_bar->annotateImage($draw, $nextTextWidth, $tmp_t_r_height, 0, $value );
								
								/*
$metrics = $image->queryFontMetrics($draw, $value);					
								$nextTextWidth = $nextTextWidth+$metrics['textWidth'];
								$tmp_price_width = $nextTextWidth;
*/
								
								
								$draw->setFont('Helvetica');
								//$draw->setFont('/usr/share/fonts/helvetica/Helvetica75-Bold.ttf');
								$draw->setFillColor('white');
								//$draw->setFontSize( $font_size * $small_font_percent / 100 ); // 80%
								$draw->setFontSize( $font_size_social );
								
								//$top_bar->annotateImage($draw, $tmp_price_width, $tmp_t_r_height, 0, strtoupper($key). ': ');
								$top_bar->annotateImage($draw, $tmp_price_width, $tmp_t_r_height, 0, ($key). ': ');
								$tmp_t_r_height += ($prefix == 'social_') ? $textHeight * 1.2 : $textHeight * 0.8;
							}
						}
												
					}
					//reset
					if(stristr($prefix, 'blast_BRAND_WATERMARK_PRICING_BIG_') !== FALSE) {
						$font_size_social = $font_size_social / $blast_BRAND_WATERMARK_PRICING_BIG_adjustment_percent;
						$textHeight = $textHeight / $blast_BRAND_WATERMARK_PRICING_BIG_adjustment_percent;
						$textPadding = $textPadding / $blast_BRAND_WATERMARK_PRICING_BIG_adjustment_percent;
					}
					
					if(!empty($bottom_left_text)){
						// Position text at the bottom-left of the image
						$draw->setGravity(Imagick::GRAVITY_NORTHWEST);
						$draw->setFont('/usr/share/fonts/helvetica/Helvetica75-Bold.ttf');	
						$draw->setFillColor('white');
						//$draw->setFontSize( $font_size * $small_font_percent / 100 );	//110%	
						$draw->setFontSize( $font_size  );
						if($corner_text_array['action'] == 'download'){
							//$draw->setFontSize( $font_size * $small_font_percent / 100 );	//110%
							$draw->setFontSize( $font_size * 1.1 );
							$bottom_bar->annotateImage($draw, $textPadding, $textPadding, 0, $bottom_left_text);
						}
						else{
							//$bottom_bar->annotateImage($draw, $textPadding, ($textPadding*2)+($textPadding/2), 0, $bottom_left_text);
							$bottom_bar->annotateImage($draw, $textPadding, $textPadding, 0, $bottom_left_text);
						}				
					}
					if(!empty($bottom_right_text)){
						
						// Position text at the bottom-right of the image
						$draw->setGravity(Imagick::GRAVITY_NORTHEAST);				
						$draw->setFont('Helvetica');
						$draw->setFillColor('white');
						$draw->setFontSize( $font_size * $small_font_percent / 100 ); // 70%
						if($corner_text_array['action'] == 'download'){
							//$draw->setFont('/usr/share/fonts/helvetica/HelveticaNeue-Medium.otf');
							$draw->setFont('Helvetica');
							//$draw->setFontSize( $font_size * $small_font_percent / 100 );	//80%
							$draw->setFontSize( $font_size  );
							$bottom_bar->annotateImage($draw, $textPadding, $textPadding, 0, "ZoomIN.gallery" . $gallery_quick_link);
						}
						else{
							/*
							$draw->setFontSize( $font_size * $small_font_percent / 100 );	//110%
							$footer_text1 = "e-commerce by:";
							$footer_text2= "photo.BANGK!";
							if($prefix == 'gallery_preview_' || $prefix == 'wallpaper_'){
								$footer_text1 = "Gallery URL:";
								$footer_text2= "photo.BANGK.com" . $gallery_quick_link;
							}
*/
							//$bottom_bar->annotateImage($draw, $textPadding, $textPadding*1.5, 0, $footer_text1);
							$draw->setFontSize( $font_size * 0.9  );
							$footer_text2= "ZoomIN.gallery" . $gallery_quick_link;	
							//$bottom_bar->annotateImage($draw, $textPadding, $textPadding+$textHeight, 0, $footer_text2 );
							$bottom_bar->annotateImage($draw, $textPadding, $textPadding, 0, $footer_text2 );	
						}
				}
					if(!empty($top_left_text) || !empty($top_right_text)){
						if($prefix == 'social_'){
							$image->compositeImage($top_bar, Imagick::COMPOSITE_OVER, 0, $new_height-$top_bar_height);
						}
						else{
							$image->compositeImage($top_bar, Imagick::COMPOSITE_OVER, 0, 0);
						}
					}
					if(!empty($bottom_left_text) || !empty($bottom_right_text)){
						if($prefix != 'social_'){
							$image->compositeImage($bottom_bar, Imagick::COMPOSITE_OVER, 0, $new_height-$bottom_bar_height);
						}
					}
				}
				
				if(in_array(strtolower($new_extension), ["png", "gif"])){
					$image->setImageFormat($new_extension);
				}
				else{
					$image->setCompression(Imagick::COMPRESSION_JPEG);
					$image->setCompressionQuality(80); 					
					//$image->sharpenimage($radius=10, $sigma=10, $channel="");
					
					$image->adaptiveSharpenImage(2,1);		
					// Set output image format
					$image->setImageFormat('jpg');
				}
				
				//$image->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
				//$image->setImageResolution(72,72);
				
				$image->writeImage($newFielName);		
				$image->destroy();
				
				@unlink($image_page1);
				
				$output = $thumb_name;
			}
			catch(Exception $e) {
				@unlink($image_page1);
			  	$output = 'FAIL: Creating preview image! ' . 'The exception was created on line: ' . $e->getLine() . '. ' . $e->getMessage();			  	
			  	//test('ERROR:', $e->getMessage());
			}			
		}
		else{
			$output = 'FAIL: ' . strtoupper($image_info['extension']) . ' is not suppoted!';	
		}				
	}
	else{
		$output = 'FAIL: File doesn\'t exits !';
	}	
	logger3('create_gallery_preview_image', $output);
	return  $output;
}

function _get_video_attributes($video_path) {
	global $master_config_ffmpeg_path;
	$ffmpeg = $master_config_ffmpeg_path;
	if(empty($ffmpeg)) $ffmpeg = '/usr/local/bin/ffmpeg';
    $command = $ffmpeg . ' -i ' . $video_path . ' -vstats 2>&1';
    $output = shell_exec($command);

    $regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/";
    if (preg_match($regex_sizes, $output, $regs)) {
        $codec = $regs [1] ? $regs [1] : null;
        $width = $regs [3] ? $regs [3] : null;
        $height = $regs [4] ? $regs [4] : null;
    }

    $regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
    if (preg_match($regex_duration, $output, $regs)) {
        $hours = $regs [1] ? $regs [1] : null;
        $mins = $regs [2] ? $regs [2] : null;
        $secs = $regs [3] ? $regs [3] : null;
        $ms = $regs [4] ? $regs [4] : null;
    }

    return array('codec' => $codec,
        'width' => $width,
        'height' => $height,
        'hours' => $hours,
        'mins' => $mins,
        'secs' => $secs,
        'ms' => $ms
    );
}

function _human_filesize($bytes, $decimals = 2) {
    $sz = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

function make_zipped_package_of_photos_from_shopping_cart(){
	
	global $master_config_root_path, $s3client;
	$account_hash = $_SESSION['gallery']['account']['hash'];
	
	$cart_photos = $_SESSION['gallery']['cart'];
	logger3("_SESSION['gallery']",$_SESSION['gallery']);
	logger3('cart_photos', $cart_photos);
	
	if(count($cart_photos)<1) return false;
	
	$target_path = $master_config_root_path . 'gateway/photoBANGK_tmp/downloads/' . $account_hash . '_' . time() . '/';	
	@mkdir($target_path, 0777);
	$zip_path = $master_config_root_path . 'www/downloads/' . hash_me() . ".zip";
	logger3("zip_path",$zip_path);
	
	$zip = new ZipArchive;
	if ($zip->open($zip_path, ZipArchive::CREATE)===TRUE) {
		
		foreach($cart_photos as $index=>$photo){
			$filename = $photo['filename'];
			$bucket = $photo['path_to_record'];			
			$file_path = $target_path . $filename;
			$wartermarktext = $photo['accountname'];
			try{
				$result = $s3client->getObject([
				    'Bucket' => $bucket, 
				    'Key' => $filename,
				    'SaveAs' => $file_path
				]);
												
				$gallery_preview_image_path = $file_path;
				if(trim($photo['photo_media']) == 'print'){
					$zip_filename = 'photoBANGK/' . basename($gallery_preview_image_path);					
					$zip->addFile($gallery_preview_image_path, $zip_filename);
				}
				else{
					try {
					 	$images = new Imagick($file_path);
					 	foreach($images as $i=>$image) {
					 		$gallery_preview_image_path = $target_path . substr($filename, 0, strrpos($filename, '.'))  . '.jpg';									
							$image->writeImage($gallery_preview_image_path);
							break;					
						}
						$images->clear();		
					}
					catch(Exception $e)
					{
					  	//echo $e->getMessage();
					}
				
				
					$corner_text_array = ["top_left" => "", "top_right" => '', "bottom_left" => $wartermarktext, "bottom_right" => "yes", "action"=>"download"];
					
					$corner_text_array['gallery_quick_link'] = !empty($photo['quick_link'])? '/' . $photo['quick_link'] : '';
					
					if(trim($photo['photo_media']) == 'print'){
						$max_width = ''; $max_height = ''; $prefix='';
						$corner_text_array = '';
					}
					
else if(trim($photo['photo_media']) == 'wallpaper'){
						$max_width = 2000; $max_height = 1400; $prefix = 'wallpaper_';
					}
					else { $max_width = 800; $max_height = 500; $prefix = 'gallery_preview_'; }

					
					/*
	$corner_text_array = ["top_left" => "yes", "top_right" => 'FREE', "bottom_left" => $wartermarktext, "bottom_right" => "yes"];
					
					$corner_text_array['top_right'] = [];
					if(!empty(trim($photo['price_online']))) $price = number_format($photo['price_online'], 2, '.', '');	
					if($price <= 0) $price = "FREE"; 
					$corner_text_array['top_right']['Social & Web'] = $price;
					
					if(!empty(trim($photo['price_wallpaper']))) $price = number_format($photo['price_wallpaper'], 2, '.', '');		
					if($price <= 0) $price = "FREE"; 
					$corner_text_array['top_right']['Wallpaper & Web'] = $price;
					
					if(!empty(trim($photo['price_print']))) $price = number_format($photo['price_print'], 2, '.', '');
					if($price <= 0) $price = "FREE";
					$corner_text_array['top_right']['Original'] = $price;
	*/
					
					$wartermarktext = '';
					
					if(trim($photo['photo_media']) == 'print'){						
						try {
						    // Get the object
						    $result = $s3client->getObject([
							    'Bucket' => $bucket, 
							    'Key' => $filename,
							    'SaveAs' => $file_path
							]);
							$zip_filename = 'photoBANGK/' . basename($file_path);	
							$zip->addFile($file_path, $zip_filename);
						} catch (S3Exception $e) {
						    //echo $e->getMessage() . "\n";
						}
					}
					else {
						$gallery_preview_image = create_gallery_preview_image($prefix, $gallery_preview_image_path, $max_width, $max_height, $wartermarktext, $corner_text_array );
					}
					if(!stristr($gallery_preview_image, 'FAIL')){	
						
						$zip_filename = 'photoBANGK/' . basename($gallery_preview_image_path);
						//logger3("zip_filename",$zip_filename);
						$zip->addFile($target_path.$gallery_preview_image, $zip_filename);
										
						//unlink($gallery_preview_image_path);
						//unlink($file_path);	
						//unlink($target_path.$gallery_preview_image);										
					}
				}																		
							
			}
			catch(S3Exception $e){
				//echo $e->getMessage() . "\n";				
			}
			//break;	    	
	    }
	    $zip->close();
	    
	    @recurseRmdir($target_path);
	    logger3("zip_path",$zip_path);
	    return $zip_path;
	}
	else{
		//echo 'ERROR: ZIP file can\'t be open.';
	}
	return false;
}

function download_zipped_photos($photo_hashes, $account_hash){
	
	global $master_config_root_path, $s3client;
	//$account_hash = $_SESSION['gallery']['account']['hash'];
	$tmp_account = account($account_hash);
	$hashs = trim($photo_hashes);
	$hashs = trim($photo_hashes, ',');
	$tmp_hashs = "'" . implode("','", explode(",", $hashs)) . "'";
		
	$tmp_query = "SELECT pb.`photoBANGK_id`, pb.`path_to_record`, pb.`filename`, pb.`width_points`, pb.`height_points`, pb.`filesize_megs`, pb.`price_online`, pb.`price_print`, pb.`price_wallpaper`, pb.`key_words`, pb.`account_hash`, pb.`member_hash`, pb.`photoBANGK_hash`, pb.`photoBANGK_portfolios_id`, pb.`photoBANGK_portfolios_hash`, pb.`photoBANGK_hash_parent`, pb.`status`, pb.`slideshow`, pb.`quick_link`, pb.`datetime_created`, pb.`datetime_updated`, a.accountname FROM photoBANGK as pb INNER JOIN accounts as a on a.hash = pb.account_hash WHERE pb.account_hash = '". $account_hash ."' AND status='Completed' AND photoBANGK_hash IN ($tmp_hashs) ORDER BY pb.photoBANGK_id DESC;";
	logger3('tmp_query', $tmp_query);
	$tmp_photos = readArrayTHECASHIER($tmp_query);
	logger3('tmp_photos', $tmp_photos);
	
	if(count($tmp_photos)>0){
		$target_path = $master_config_root_path . 'gateway/photoBANGK_tmp/downloads/' . $account_hash . '_' . time() . '/';	
		@mkdir($target_path, 0777);
		$zip_path = $master_config_root_path . 'www/downloads/photoBANGK_Gallery_Downloads_' . hash_me() . ".zip";
		logger3("zip_path",$zip_path);

		$zip = new ZipArchive;
		if ($zip->open($zip_path, ZipArchive::CREATE)===TRUE) {		
			foreach($tmp_photos as $photo){
				$filename = $photo['filename'];
				$bucket = $photo['path_to_record'];			
				$file_path = $target_path . $filename;
				$wartermarktext = $photo['accountname'];
				try{
					$result = $s3client->getObject([
					    'Bucket' => $bucket, 
					    'Key' => $filename,
					    'SaveAs' => $file_path
					]);
													
					$gallery_preview_image_path = $file_path;
					//ADD ORIGINAL PHOTO
					$zip_filename = 'photoBANGK/' . basename($gallery_preview_image_path);					
					$zip->addFile($gallery_preview_image_path, $zip_filename);
					
					try {
					 	$images = new Imagick($file_path);
					 	foreach($images as $i=>$image) {
					 		$gallery_preview_image_path = $target_path . substr($filename, 0, strrpos($filename, '.'))  . '.jpg';									
							$image->writeImage($gallery_preview_image_path);
							break;					
						}
						$images->clear();		
					}
					catch(Exception $e)
					{
					  	//echo $e->getMessage();
					}
				
					//ADD photofilename_BRANDING.jpg
					$corner_text_array = ["top_left" => "", "top_right" => '', "bottom_left" => $wartermarktext, "bottom_right" => "yes", "action"=>"download"];
					
					$corner_text_array['gallery_quick_link'] = !empty($photo['quick_link'])? '/' . $photo['quick_link'] : '';
					
					$max_width = 2000; $max_height = 1400; $prefix = 'BRANDING_';
					
					$gallery_preview_image = create_gallery_preview_image($prefix, $gallery_preview_image_path, $max_width, $max_height, "", $corner_text_array );
					if(!stristr($gallery_preview_image, 'FAIL')){
						$path_parts = pathinfo(basename($gallery_preview_image_path));
						$zip_filename = 'photoBANGK/' . $path_parts['filename'].'_BRANDING.'.$path_parts['extension'];					
						$zip->addFile($target_path.$gallery_preview_image, $zip_filename);
					}
					
					//ADD photofilename_BRANDING_WATERMARK.jpg
					$corner_text_array = ["top_left" => "", "top_right" => '', "bottom_left" => $wartermarktext, "bottom_right" => "yes", "action"=>"download"];
					
					$corner_text_array['gallery_quick_link'] = !empty($photo['quick_link'])? '/' . $photo['quick_link'] : '';
					
					$max_width = 2000; $max_height = 1400; $prefix = 'BRANDING_WATERMARK_';
					
					$gallery_preview_image = create_gallery_preview_image($prefix, $gallery_preview_image_path, $max_width, $max_height, $wartermarktext, $corner_text_array );
					if(!stristr($gallery_preview_image, 'FAIL')){
						$path_parts = pathinfo(basename($gallery_preview_image_path));
						$zip_filename = 'photoBANGK/' . $path_parts['filename'].'_BRANDING_WATERMARK.'.$path_parts['extension'];
						$zip->addFile($target_path.$gallery_preview_image, $zip_filename);
					}
					
					//ADD photofilename_BRANDING_WATERMARK_PRICING.jpg
					$corner_text_array = ["top_left" => "yes", "top_right" => '', "bottom_left" => $wartermarktext, "bottom_right" => "yes", "action"=>"download"];
					
					$corner_text_array['gallery_quick_link'] = !empty($photo['quick_link'])? '/' . $photo['quick_link'] : '';
					
					$corner_text_array['top_right'] = [];
					if(!empty(trim($photo['price_online']))) $price = number_format($photo['price_online'], 2, '.', '');	
					if($price <= 0) $price = "FREE"; 
					$corner_text_array['top_right']['Social & Web'] = $price;
					
					if(!empty(trim($photo['price_wallpaper']))) $price = number_format($photo['price_wallpaper'], 2, '.', '');		
					if($price <= 0) $price = "FREE"; 
					$corner_text_array['top_right']['Wallpaper & Web'] = $price;
					
					if(!empty(trim($photo['price_print']))) $price = number_format($photo['price_print'], 2, '.', '');
					if($price <= 0) $price = "FREE";
					$corner_text_array['top_right']['Original'] = $price;
					
					$max_width = 2000; $max_height = 1400; $prefix = 'BRANDING_WATERMARK_PRICING_';
					
					$gallery_preview_image = create_gallery_preview_image($prefix, $gallery_preview_image_path, $max_width, $max_height, $wartermarktext, $corner_text_array );
					if(!stristr($gallery_preview_image, 'FAIL')){
						$path_parts = pathinfo(basename($gallery_preview_image_path));
						$zip_filename = 'photoBANGK/' . $path_parts['filename'].'_BRANDING_WATERMARK_PRICING.'.$path_parts['extension'];
						$zip->addFile($target_path.$gallery_preview_image, $zip_filename);
					}								
				}
				catch(S3Exception $e){
					//echo $e->getMessage() . "\n";				
				}
			} //END OF FOREACH $tmp_photos
			$zip->close();	    
			@recurseRmdir($target_path);
			//sleep(1);
						
			$url_to_zip = "https://photo.bangk.com/downloads/" . basename($zip_path);
			$link_to_zip = "<a href='$url_to_zip'>$url_to_zip</a>";
				
			$tmp_member = member($tmp_account['creator_memberid']);
			bmail($bmail_to=$tmp_member['emailaddress'],$bmail_subject="photo.BANGK! Gallery Download LINK",$bmail_message=$link_to_zip);
		}//END OF ZIP OPEN
	}	
}

function compress_image($src, $dest , $quality) {
    $info = getimagesize($src);  
    if ($info['mime'] == 'image/jpeg') 
    {
        $image = imagecreatefromjpeg($src);
    }
    elseif ($info['mime'] == 'image/gif') 
    {
        $image = imagecreatefromgif($src);
    }
    elseif ($info['mime'] == 'image/png') 
    {
        $image = imagecreatefrompng($src);
    }
    else
    {
        die('Unknown image file format');
    }
  
    //compress and save file to jpg
    imagejpeg($image, $dest, $quality);
  
    //return destination file
    return $dest;
}

function delete_local_previews($filename){
	global $master_config_root_path;
	$target_path = $master_config_root_path . 'gateway/photoBANGK_tmp/blast/';	
	//DELETE LOCAL FILES START
	$prefixes = ['BRAND_WATERMARK_PRICING_BIG', 'BRAND_WATERMARK_PRICING_NORMAL', 'BRAND_WATERMARK_PRICING_BIG_SOCIAL', 'BRAND_WATERMARK_PRICING_NORMAL_SOCIAL', 'BRAND_WATERMARK_PRICING_BIG_WALLPAPER', 'BRAND_WATERMARK_PRICING_NORMAL_WALLPAPER', 'BRAND_WATERMARK_PRICING_BIG_TWITTER_SOCIAL', 'BRAND_WATERMARK_PRICING_NORMAL_TWITTER_SOCIAL', 'BRAND_WATERMARK_PRICING_BIG_TWITTER_WALLPAPER', 'BRAND_WATERMARK_PRICING_NORMAL_TWITTER_WALLPAPER', 'BRAND_WATERMARK', 'BRAND_WATERMARK_SOCIAL', 'BRAND_WATERMARK_WALLPAPER', 'BRAND_WATERMARK_TWITTER_SOCIAL', 'BRAND_WATERMARK_TWITTER_WALLPAPER', 'BRANDING_ONLY', 'BRANDING_ONLY_SOCIAL', 'BRANDING_ONLY_WALLPAPER', 'BRANDING_ONLY_TWITTER_SOCIAL', 'BRANDING_ONLY_TWITTER_WALLPAPER','BRAND_WATERMARK_WALLPAPER_TWITTER_WALLPAPER', 'BRANDING_ONLY_WALLPAPER_TWITTER_WALLPAPER', 'BRAND_WATERMARK_TWITTER_SOCIAL', 'BRANDING_ONLY_TWITTER_SOCIAL'];			
			
	$new_extension = format_photoBANGK_photo_extension($filename);			
	$filename_without_ext = substr($filename, 0, strrpos($filename, "."));
	
	foreach($prefixes as $prefix){
		//$prefix = 'blast_BRAND_WATERMARK_PRICING_BIG_';
		$prefix = 'blast_'. $prefix . '_';
		$local_preview = $prefix . $filename_without_ext  . '.' . $new_extension;
		@unlink($target_path . $local_preview);
	}
	
	//DELETE LOCAL FILES END
}


function recurseRmdir($dir) {
  $files = array_diff(scandir($dir), array('.','..'));
  foreach ($files as $file) {
    (is_dir("$dir/$file")) ? recurseRmdir("$dir/$file") : unlink("$dir/$file");
  }
  return rmdir($dir);
}



function affiliate_details($set_sponsor_accountid) {
	
	if(empty($set_sponsor_accountid)) $set_sponsor_accountid = $_COOKIE['sponsor_accountid'];
	
	$return = array();
	$tmp_sql = "SELECT * FROM accounts WHERE hash = '" . $set_sponsor_accountid . "';";
	$confirmed_sponsor_account = object2array(readTHECASHIER($tmp_sql));
	$return['name'] = $confirmed_sponsor_account['accountname'];
	$return['emailaddress'] = $confirmed_sponsor_account['emailaddress'];
	 
	if(empty($return['name'])) {
		$tmp_sql = "SELECT * FROM affiliates WHERE hash = '" . $set_sponsor_accountid . "';";
		$confirmed_sponsor_account = object2array(readTHECASHIER($tmp_sql));
		$return['name'] = $confirmed_sponsor_account['affiliate_name'];
		$return['emailaddress'] = $confirmed_sponsor_account['emailaddress'];
	}
	
	//test("confirmed_sponsor_account",$confirmed_sponsor_account);
	
	return 	$return;
}


function vsecuritynetwork() {
	return "<span style='color:#DD0000;'>v</span><span style='color:#000000;'>-security.network<span>";
}

function vsignnetwork() {
	return "<span style='color:#DD0000;'>v</span><span style='color:#000000;'>-sign.network<span>";
}

function vpassnetwork() {
	return "<span style='color:#DD0000;'>v</span><span style='color:#000000;'>-pass.network<span>";
}

function vmatchnetwork() {
	return "<span style='color:#DD0000;'>v</span><span style='color:#000000;'>-match.network<span>";
}

//$process_id = run_in_background("php background.php ARGV > log.logger");
function run_in_background($Command, $Priority = 0){
	logger3('$Command', $Command);
   if($Priority)
       $PID = shell_exec("nohup nice -n $Priority $Command 2> /dev/null & echo $!");
   else
       $PID = shell_exec("nohup $Command 2> /dev/null & echo $!");
       logger3('$PID', $PID);
   return($PID);
}
function is_process_running($PID){
   exec("ps $PID", $ProcessState);
   return(count($ProcessState) >= 2);
}

function color_inverse($color) {
    $color = str_replace('#', '', $color);
    if (strlen($color) != 6){ return '000000'; }
    $rgb = '';
    for ($x=0;$x<3;$x++){
        $c = 255 - hexdec(substr($color,(2*$x),2));
        $c = ($c < 0) ? 0 : dechex($c);
        $rgb .= (strlen($c) < 2) ? '0'.$c : $c;
    }
    return '#'.$rgb;
}



function stats() {
	
	
	$tmp_sql = "";
	
	
}


function name_string_to_array($name_string) {
	
	$name_string_trimmmed = trim($name_string);
	$name_string_exploded = explode(" ", $name_string_trimmmed);
	$return = array();
	
	$count = count($name_string_exploded);
	//test("count",$count);
	
	if(
	(stristr($name_string_exploded[0],"."))
	) {
		$return['salutation'] = $name_string_exploded[0];
	} else {
		$return['firstname'] = $name_string_exploded[0];
	}
	
	if(
	(count($name_string_exploded) == 2)
	) {
		
		$return['firstname'] = $name_string_exploded[0];
	
		$return['lastname'] = $name_string_exploded[1];
	}
	
	if(
	(count($name_string_exploded) == 3)
	) {
		$return['firstname'] = $name_string_exploded[0];
		$return['middlename'] = $name_string_exploded[1];
		$return['lastname'] = $name_string_exploded[2];
	}
	
	return $return;
}



function name_string_to_array_v2($name_string) {
	
	$name_string_trimmmed = trim($name_string);
	$name_string_exploded = explode(" ", $name_string_trimmmed);
	$return = array();
	
	$count = count($name_string_exploded);
	//test("count",$count);
	
	

	if($count == 1) {
		
		$return['first_name'] = $name_string_exploded[0];
		$return['middle_name'] = "";
		$return['first_name'] = "";
	}
	
	if($count == 2) {
		
		$return['first_name'] = $name_string_exploded[0];
		$return['middle_name'] = "";
		$return['first_name'] = $name_string_exploded[1];
	}
	
	if($count == 3) {
		$return['first_name'] = $name_string_exploded[0];
		$return['middle_name'] = $name_string_exploded[1];
		$return['first_name'] = $name_string_exploded[2];
	}
	
	
	if($count == 4) {
		$return['first_name'] = $name_string_exploded[0];
		$return['middle_name'] = $name_string_exploded[1] . " " . $name_string_exploded[2];
		$return['first_name'] = $name_string_exploded[3];
	}
	
	
	if($count == 4) {
		$return['first_name'] = $name_string_exploded[0];
		$return['middle_name'] = $name_string_exploded[1] . " " . $name_string_exploded[2] . " " . $name_string_exploded[3];
		$return['first_name'] = $name_string_exploded[4];
	}
	

	
	return $return;
}



function get_the_gallery_accounts($memberid) {
	
	
	$tmp_member_details = member($memberid);
	
	$x = 0;
	$photo_accounts = "";
	$photo_accounts = array();
	foreach($tmp_member_details['accounts']['business'] as $key => $accountid) {
		
		$tmp_sql = "";
		$tmp_sql = "SELECT * FROM accounts WHERE accountid = '". $accountid ."';";
		
		$account_details = "";
		$account_details = readTHECASHIER($tmp_sql);
		
		if(stristr($account_details->business_subcategory,"photography")) {
			
			$photo_accounts[$x] = $account_details->accountid;
			$x++;
			
		}
		
	}

	return $photo_accounts;
}





function country_code_to_ip_address($country_calling_code) {
	
	
	$customer_ip_address = "74.81.189.130";
	if($country_calling_code == "1") $customer_ip_address = "74.81.189.2"; // USA
	if($country_calling_code == "61") $customer_ip_address = "74.81.189.130"; // UAS
	if($country_calling_code == "51") $customer_ip_address = "74.81.189.193"; // ARG
	//if($country_calling_code == "1") $customer_ip_address = "74.81.189.201"; // CAN
	if($country_calling_code == "44") $customer_ip_addresss = "74.81.189.210"; // GBR
	if($country_calling_code == "852") $customer_ip_address = "74.81.189.217"; // HKG
	if($country_calling_code == "354") $customer_ip_address = "74.81.189.225"; // ISL
	if($country_calling_code == "952") $customer_ip_address = "74.81.189.232"; // ISR
	if($country_calling_code == "81") $customer_ip_address = "74.81.189.241"; // JPN
	if($country_calling_code == "27") $customer_ip_address = "74.81.189.249"; // ZAF
	
	return $customer_ip_address;
	
}


function country_to_ip($country="",$state="") {

	logger3("country_to_ip: country",$country);
	logger3("country_to_ip: state",$state);

	if(strtoupper($country) == "UK") $country = "GB";
	
	$state_iso2 = minimizeState($state);
	
	$tmp_sql = "SELECT RegionID FROM Regions WHERE Code = '". $state_iso2 ."';";
	logger3("tmp_sql",$tmp_sql);
	
	$region_id_array = arrayTHECASHIER($tmp_sql,"geobytes");
	logger3("region_id_array",$region_id_array);
	//exit;
	
	$count_regions = count($region_id_array);
	
	$region_id_string = "";
	foreach($region_id_array as $key => $region_id) {
		$region_id_string .= "'". $region_id ."',";
	}
	if($region_id_string) {
		$region_id_string = " AND RegionId IN(". trim($region_id_string,",") . ") ";
	}
	
	
	
	
	
	$tmp_sql = "SELECT CountryId FROM Countries WHERE ISO2 = '". $country ."' OR ISO3 = '". $country ."' OR country = '". $country ."';";
	
	//test("tmp_sql",$tmp_sql);
	
	$country_id = getTHECASHIER($tmp_sql,"geobytes");
	
	//test("country_id",$country_id);
	
	//$tmp_sql = "SELECT DISTINCT SubNetAddress FROM Subnets WHERE CountryId = '". $country_id ."';";


				
		
	$ip_is_set = false;
	while($ip_is_set == false)	{

		logger3("TOP OF LOOP... ip_is_set",$ip_is_set);
		
		# $region_array_key[0] = rand(0, $count_regions);
		# $region_array_key[1] = rand(0, $count_regions);
		# $region_array_key[2] = rand(0, $count_regions);
		# $region_array_key[3] = rand(0, $count_regions);
		# $region_array_key[4] = rand(0, $count_regions);
		# $region_array_key[5] = rand(0, $count_regions);
		# $region_array_key[6] = rand(0, $count_regions);
		# $region_array_key[7] = rand(0, $count_regions);
		# $region_array_key[8] = rand(0, $count_regions);
		# $region_array_key[9] = rand(0, $count_regions);
		
		
		logger3("region_array_key",$region_array_key);
		
		$tmp_sql = "";
		$tmp_sql .= "SELECT subnet_id FROM Subnets WHERE CountryId = '". $country_id ."'";
		
			# $tmp_sql .= " AND ";
			# $tmp_sql .= "(RegionId = '". $region_id_array[$region_array_key[0]] ."',";
			# $tmp_sql .= "RegionId = '". $region_id_array[$region_array_key[1]] ."',";
			# $tmp_sql .= "RegionId = '". $region_id_array[$region_array_key[2]] ."',";
			# $tmp_sql .= "RegionId = '". $region_id_array[$region_array_key[3]] ."',";
			# $tmp_sql .= "RegionId = '". $region_id_array[$region_array_key[4]] ."',";
			# $tmp_sql .= "RegionId = '". $region_id_array[$region_array_key[5]] ."',";
			# $tmp_sql .= "RegionId = '". $region_id_array[$region_array_key[6]] ."',";
			# $tmp_sql .= "RegionId = '". $region_id_array[$region_array_key[7]] ."',";
			# $tmp_sql .= "RegionId = '". $region_id_array[$region_array_key[8]] ."',";
			# $tmp_sql .= "RegionId = '". $region_id_array[$region_array_key[9]] ."')";
		
		$tmp_sql .= $region_id_string. "
		ORDER BY RAND()
		LIMIT 1
		";
		
		logger3("tmp_sql",$tmp_sql);
		
		
		
		
		$subnet_id = getTHECASHIER($tmp_sql,"geobytes");
		logger3("subnet_id",$subnet_id);
		
		
		$tmp_sql = "SELECT SubNetAddress FROM Subnets WHERE subnet_id = '". $subnet_id ."';";
		logger3("...tmp_sql",$tmp_sql);
		
		$subnet = getTHECASHIER($tmp_sql,"geobytes");
		logger3("subnet",$subnet);
	
		
	
		if($subnet) {
	
			$ip = $subnet . "." . rand(5, 250);
			$_SESSION['session']['geo'] = ""; // clears potential previous $_SESSION geodata; allows new IP lookup
			$geobytes = geobytes($ip);
			logger3("geobytes",$geobytes);
			
			
			# http://api.ipinfodb.com/v3/ip-country/?key=29deaa5fd72b32098fc20837483dd034f3fca9509e95d6c9dba4ec9f13425fe8&ip=74.125.45.100
			
			if(
			(!$geobytes['iso2']) &&
			(!$geobytes['iso3'])
			) {
				
				$tmp_kurl = kurl($tmp_url="http://api.ipinfodb.com/v3/ip-country/",$tmp_properties="key=29deaa5fd72b32098fc20837483dd034f3fca9509e95d6c9dba4ec9f13425fe8&ip=".$ip);	
			
				$tmp_kurl = explode(";",$tmp_kurl);
			
				logger3("tmp_kurl",$tmp_kurl);
			}
			
			logger3("geobytes",$geobytes);
			logger3("geobytes['iso3']",$geobytes['iso3']);
			logger3("country",$country);
			
			if(
			($geobytes['iso2'] == $country) ||
			($geobytes['iso3'] == $country) ||
			($tmp_kurl[3] == $country)
			) {
				
				$ip_is_set = true;
				
			}
		}
	}

	return $ip;
	
}



function affiliate_referral_tracking() {
	
	//
	// this function receives any incoming tracking campigns, and then set sponsor_accountid
	//
	
	$set_sponsor_accountid = "";
	
	/// legacy: sets tracking to NSDB for all "ads" (on google)
	if($_GET['ad']) {
		$tmp_sponsor_type = "CAMPAIGN";
		$tmp_campaign_name = trim($_GET['ad']);
		$_GET['key'] = "98765a9435d3aa2d25a719767d055421";
	}
	
	##### GET THE INCOMING VALUES:

	
	if($_GET['affiliate']) {
		$tmp_sponsor_type = "AFFILIATE";
		$set_sponsor_accountid = trim($_GET['affiliate']);
	}
	
	if(($_GET['sponsor']) || ($_GET['s'])) {
		$tmp_sponsor_type = "SPONSOR";
		$set_sponsor_accountid = trim($_GET['sponsor']);
	}
	
	if($_GET['key']) {
		$tmp_sponsor_type = "KEY";
		$set_sponsor_accountid = trim($_GET['key']);
	}
	
	
	
	if($_GET['campaign']) {
		$tmp_sponsor_type = "CAMPAIGN";
		$tmp_campaign_name = trim($_GET['campaign']);
	}
	
	
	if($_GET['cname']) {
		$tmp_sponsor_type = "CAMPAIGN";
		$tmp_campaign_name = trim($_GET['cname']);
	}
	
	if($_GET['c-name']) {
		$tmp_sponsor_type = "CAMPAIGN";
		$tmp_campaign_name = trim($_GET['c-name']);
	}

	
	if( ($_GET['referral']) || ($_GET['r']) ) {
		$tmp_sponsor_type = "REFERRAL";
		$set_sponsor_accountid = trim($_GET['referral']);
		$set_sponsor_terms = "";
	
	}
	
	if(!empty($_GET['coupon'])) {
		$tmp_sponsor_type = "COUPON";
		$set_sponsor_accountid = trim($_GET['coupon']);
		$set_sponsor_terms = "";
	
	}
	
	if(!empty($_GET['invite'])) {
		$tmp_sponsor_type = "INVITE";
		$set_sponsor_accountid = trim($_GET['invite']);
		$set_sponsor_terms = "";
	
	}
	
	if(!empty($_GET['ticket'])) {
		$tmp_sponsor_type = "TICKET";
		$set_sponsor_accountid = trim($_GET['ticket']);
		$set_sponsor_terms = "1GB";
	}
	
	
	
	// possible clear session make way for new
	if($set_sponsor_accountid) $_SESSION['tracking'] = "";


	if($set_sponsor_accountid){
		$confirmed_sponsor_account = affiliate_details($set_sponsor_accountid);
	} else {
		$confirmed_sponsor_account = FALSE;
	}
	
	
	
	

	
	### LOG THE INCOMING USER:
	//$_SESSION['tracking'] = "";
	if(
	(empty($_SESSION['tracking'])) &&
	($confirmed_sponsor_account)
	) {
	
		$_SESSION['tracking'] = "LOGGED";
	
		$tmp_trackingid = "";
		$tmp_spondor_accountid = $set_sponsor_accountid;
		//$tmp_campaign_name = "";
		$tmp_ip = $_SERVER['REMOTE_ADDR'];
		$tmp_ip_country_iso3 = $_SESSION['session']['geo']['iso3'];
		//test("_SESSION['session']['geo']",$_SESSION['session']['geo']);
		
		if(stristr($_SESSION['session']['geo']['city'],"ORANGE")) {
			$tmp_ip_country_iso3 = "n/a";
		}
		
		//test("_SESSION['session']['geo']",$_SESSION['session']['geo']);
		
		$tmp_HTTP_REFERER = $_SERVER['HTTP_REFERER'];
		
		$tmp_status = NULL;
		$tmp_datetime_created = datetime();
	
		$tmp_sql = "INSERT INTO `tracking`
					(`trackingid`
					, `sponsor_type`
					, `sponsor_accountid`
					, `campaign_name`
					, `ip`
					, `ip_country_iso3`
					, `HTTP_REFERER`
					, `status`
					, `datetime_created`
				) VALUES (
					'". $tmp_trackingid ."'
					,'". $tmp_sponsor_type ."'
					,'". $tmp_spondor_accountid ."'
					,'". $tmp_campaign_name ."'
					,'". $tmp_ip ."'
					,'". $tmp_ip_country_iso3 ."'
					,'". $tmp_HTTP_REFERER ."'
					,'". $tmp_status ."'
					,'". $tmp_datetime_created ."'
				)";
		//test("tmp_sql",$tmp_sql);
		$trackingid = insertTHECASHIER($tmp_sql,"ad_campaigns");
		
		//test("trackingid",$trackingid);
		setcookie("sponsor_accountid", $set_sponsor_accountid, time()+2592000, "/", ".".$_SESSION['template']['company']['domain'], 0); // expires after 30 days
	
	}
	
	return $confirmed_sponsor_account;

}







function bangk_nsdb_gmailer($to,$subject,$html_message) {
	

	require_once "Mail.php";
	require_once('Mail/mime.php');
	
	$from = '"BANGK! (Support)" <support@bangk.com>';
	$to = '<'. $to . '>';
	$subject = "$subject";
	$text ="n/a";
	$html = $html_message;
	
	$headers = array(
	    'From' => $from,
	    'To' => $to,
	    'Subject' => $subject,
	    'Content-Type' => 'text/html; charset=UTF-8' 
	);
	
	$mime_params = array(
	  'text_encoding' => '7bit',
	  'text_charset'  => 'UTF-8',
	  'html_charset'  => 'UTF-8',
	  'head_charset'  => 'UTF-8'
	);
	
	
	$mime = new Mail_mime();
	$mime->setTXTBody($text);
	$mime->setHTMLBody($html);
	$body = $mime->get($mime_params);
	$headers = $mime->headers($headers);
	
	
	
	$smtp = Mail::factory('smtp', array(
	        'host' => 'ssl://smtp.gmail.com',
	        'port' => '465',
	        'auth' => true,
	        'username' => 'bangk@nsdb.com',
	        'password' => 'P455w0rd!'
	    ));
	
	$mail = $smtp->send($to, $headers, $body);
	
	if (PEAR::isError($mail)) {
	    return($mail->getMessage());
	} else {
	    return('Message successfully sent!');
	}
	
	
	
}






function get_incoming_vars($test="") {
	
	global $_GET;
	global $_POST;
	$incoming_vars = "";
	$incoming_vars = array();
	if($_POST) $incoming_vars = $_POST;
	if(empty($incoming_vars)) $incoming_vars = $_GET;
	if($test) test("incoming_vars",$incoming_vars);
	return $incoming_vars;
}



function register_new_payment_customer_memeber() {
	
	global $master_config_authorization_voice;
	global $master_config_retry_fee_BLANK_FOR_PERSONAL_ACCOUNTS;
	global $master_config_personal_transaction_fee;
	
	
/*
$_SESSION['register_new_payment_customer_memeber']['firstname'];
$_SESSION['register_new_payment_customer_memeber']['middlename'];
$_SESSION['register_new_payment_customer_memeber']['lastnamename'];
$_SESSION['register_new_payment_customer_memeber']['emailaddress'];
$_SESSION['register_new_payment_customer_memeber']['telephone_country_code'];
$_SESSION['register_new_payment_customer_memeber']['telephone_number'];
$_SESSION['register_new_payment_customer_memeber']['ip_address'];
$_SESSION['register_new_payment_customer_memeber']['ip_address'];

$_SESSION['register_new_payment_customer_memeber']['password'];

$_SESSION['register_new_payment_customer_memeber']['date_date'];
$_SESSION['register_new_payment_customer_memeber']['birth_day'];
$_SESSION['register_new_payment_customer_memeber']['birth_month'];
$_SESSION['register_new_payment_customer_memeber']['birth_month'];
	
*/	
	
	
	$trim_incoming_emailaddress = trim($_SESSION['register_new_payment_customer_memeber']['emailaddress']);
	////
	

	
	
	$registration_datetime = $_SESSION['authorization']['timestamp'] = datetime();
	
	$_SESSION['session']['registration']['emailaddress'] = $trim_incoming_emailaddress;
	
	$_SESSION['session']['registration']['firstname'] = $_SESSION['register_new_payment_customer_memeber']['firstname'];
	$_SESSION['session']['registration']['middlename'] = $_SESSION['register_new_payment_customer_memeber']['middlename'];
	$_SESSION['session']['registration']['lastname'] = $_SESSION['register_new_payment_customer_memeber']['lastname'];
	
	/// if not first/last, then create one based on email address
	if(
		(!$_SESSION['session']['registration']['firstname']) &&
		(!$_SESSION['session']['registration']['lastname'])
	) {
		
		$tmp_email_user = explode("@",$trim_incoming_emailaddress);
		$_SESSION['session']['registration']['lastname'] = ucwords(strtolower(preg_replace("/[^a-zA-Z0-9]/", "", $tmp_email_user[1])));
		$_SESSION['session']['registration']['firstname'] = ucwords(strtolower(preg_replace("/[^a-zA-Z0-9]/", "", $tmp_email_user[0])));
		
	}
	
	
	//$_SESSION['session']['registration']['business_category'] = "SERVICES";
	///$_SESSION['session']['registration']['business_subcategory'] = "Photography";
	//$_SESSION['session']['registration']['business_type'] = "PDB";
	//$_SESSION['session']['registration']['business_name'] = strtolower($tmp_email_user[0]);
	
	
	
		################################################################################################
		################################################################################################
		################################################################################################
		################################################################################################
		################################################################################################
		################################################################################################
		### START :: REGISTER ACCOUNT:  PERSONAL
		################################################################################################
		
		###  FIRST, CREATE A MEMBER:
		$test_sql = "INSERT into members (
			`memberid`,
			`hash`,
			`sponsor_accountid`,
			`sponsor_terms`,
			`salutation`,
			`firstname`,
			`middlename`,
			`lastname`,
			`emailaddress`,
			`password`,
			`birthdate`,
			`country_iso3`,
			`timezone`,
			`authorization_voice`,
			`type`,
			`coupon_used_to_register`,
			`created`,
			`updated`) 
		
		VALUES ('" . $blank_memberid . "',
			'" . make_hash() . "',
			'" . $_COOKIE['sponsor_accountid'] . "',
			'" . $_COOKIE['sponsor_terms'] . "',
			
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['saluation']) . "',
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['firstname']) . "',
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['middlename']) . "',
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['lastname']) . "',
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['emailaddress']) . "',
			
			'" . $_SESSION['register_new_payment_customer_memeber']['password'] . "',
			
			'" . $_SESSION['register_new_payment_customer_memeber']['birth_year'] . "-" . $_SESSION['register_new_payment_customer_memeber']['birth_month'] . "-" . $_SESSION['register_new_payment_customer_memeber']['birth_day'] . "',
			'" . $_SESSION['register_new_payment_customer_memeber']['country_iso3'] . "',
			'" . $_SESSION['register_new_payment_customer_memeber']['offset'] . "',
			'" . $master_config_authorization_voice . "',
			'" . $blank_member_type . "',
			'" . $blank_coupon . "',
			'" . $registration_datetime . "',
			'" . $registration_datetime . "')";
		
		logger3("test_sql",$test_sql);
		$memberid = insertTHECASHIER($test_sql);
		logger3("memberid",$memberid);
		//exit;
		
		
		$tmp_full_name = $_SESSION['register_new_payment_customer_memeber']['firstname'] . " " . $_SESSION['register_new_payment_customer_memeber']['lastname'];
		
		
		### CREATE A PERSONAL ACCOUNT:
		$tmp_sql = "INSERT into accounts (
			`accountid`,
			`hash`,
			
			`accounttype`,
			`accountname`,
			
			`streetaddress1`,
			`streetaddress2`,
			
			`city`,
			`state`,
			
			`region`,
			`postalcode`,
			
			`country_iso3`,
			`dayphone`,
			
			`eveningphone`,
			`faxphone`,
			
			`mobilephone`,
			`customer_support_phone_number_1`,
			
			`emailaddress`,
			`agreement`,
			
			`currency_translation`,
			`currency_0_country`,
			
			`currency_0_iso3`,
			`currency_country_1`,
			
			`currency_code_1`,
			`currency_country_2`,
			
			`currency_code_2`,
			`product_type`,
			
			`transaction_fee_total`,
			`transaction_fee_my`,
			
			`retry_fee`,
			`sponsor_fee`,
			
			`status_payments`,
			`sponsor_accountid`,
			
			`sponsor_terms`,
			`data_GB`,
			
			`creator_memberid`,
			
			`created`,
			`updated`
		) VALUES (
			'" . $blank_accountid . "',
			'" . make_hash() . "',
			
			'Personal',
			'" . str_replace("'","\'",$tmp_full_name) . "',
			
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['streetaddress1']) . "',
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['streetaddress2']) . "',
			
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['city']) . "',
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['state']) . "',
			
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['region']) . "',
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['postalcode']) . "',
			
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['country_iso3']) . "',
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['dayphone']) . "',
			
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['eveningphone']) . "',
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['faxphone']) . "',
			
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['mobilephone']) . "',
			'".$_SESSION['register_new_payment_customer_memeber']['telephone_calling_code']."/".$_SESSION['register_new_payment_customer_memeber']['telephone_phone_number']."',
			
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['emailaddress']) . "',
			'" . str_replace("'","\'",$_SESSION['register_new_payment_customer_memeber']['agreement']) . "',
			
			'" .  $currency_translation . "',
			'USA',
			
			'USD',
			'" .  $_SESSION['register_new_payment_customer_memeber']['country_iso3'] . "',
			
			'" .  $currency_code . "',
			'" .  $blank_currency_country_2 . "',
			
			'" . $product_type_blank . "',
			'" . $product_type_blank . "',
			
			'" . $master_config_personal_transaction_fee . "',
			'" . $master_config_personal_transaction_fee . "',
			
			'" . $master_config_retry_fee_BLANK_FOR_PERSONAL_ACCOUNTS . "',		
			'" . $sponsor_fee_todo . "',
			
			'ON',
			'" . $_COOKIE['sponsor_accountid'] . "',
			
			'" . $_COOKIE['sponsor_terms'] . "',
			'1',
			
			'" . $memberid . "',
			'" . $registration_datetime . "',
			
			'" . $registration_datetime . "'
			);";
		logger3("tmp_sql",$tmp_sql);
		$accountid = $personal_accountid = insertTHECASHIER($tmp_sql);
		logger3("accountid",$accountid);
		
		
		
		### GET IPID:
		$tmp_query = "INSERT into ips (
			`ipid`,
			`memberid`,
			`ip`,
			`status`,
			`created`,
			`updated`
		) VALUES (
			'" . $ipid . "',
			'" . $memberid . "',
			'" . $REMOTE_ADDR . "',
			'Authorized',
			'" . $registration_datetime . "',
			'" . $registration_datetime . "')";			
		$ipid = insertTHECASHIER($tmp_query);
		
		
		
		$new_account_balance = "0.00";
		
		### NOW SET PERSONAL ACCOUNT BALANCE:
		$tmp_sql = "INSERT into balances 
					(
					`balanceid`,
					`platform`,
					`currency_iso3`,
					`accountid`,
					`account_balance`,
					`approved`,
					`sponsor_balance`,
					`available`,
					`created`) 
				VALUES 	
					(
					'" . $balanceid . "',
					'" . echo_platform() . "',
					'" . $_SESSION['template']['company']['currency1'] . "',
					'" . $accountid . "',
					'". $new_account_balance ."',
					'0.00',
					'0.00',
					'0.00',
					'" . $registration_datetime . "');";
		logger3("tmp_sql",$tmp_sql);	
		$balanceid = insertTHECASHIER($tmp_sql);
		logger3("balanceid",$balanceid);	
		
		
		### NOW TIE IT ALL TOGETHER AND SET THE PERMISSIONS:
		//$permissionsid = insertTHECASHIER("INSERT into permissions (`permissionsid`,`memberid`,`accountid`,`permissions`,`created`) VALUES ('" . $permissionsid . "','" . $memberid . "','" . $accountid . "','MASTER','" . $registration_datetime . "')");
		
		### SET PERMISSIONS: ############################
		$set_permissionsid = null;
		$set_hash = hash_me();
		$set_memberid = $memberid;
		$set_accountid = $accountid;
		$set_accounttype = "Personal";
		$set_permissions = "MASTER";
		$set_admin =null;
		$set_login_biometric_verification = "OFF";
		$set_status = "ACTIVE";
		$set_notification_firstname = null;
		$set_notification_lastname = null;
		$set_creator_memberid = $memberid;
		$set_created = null;
		$set_datetime_created = $registration_datetime;
		$set_datetime_updated = $registration_datetime;
		
		$tmp_sql = "INSERT into permissions (
			`permissionsid`,
			`hash`,
			`memberid`,
			`accountid`,
			`accounttype`,
			`permissions`,
			`admin`,
			`login_biometric_verification`,
			`status`,
			`notification_firstname`,
			`notification_lastname`,
			`creator_memberid`,
			`created`,
			`datetime_created`,
			`datetime_updated`
		) VALUES (
			'" . $set_permissionsid . "',
			'" . $set_hash . "',
			'" . $set_memberid . "',
			'" . $set_accountid . "',
			'" . $set_accounttype . "',
			'" . $set_permissions . "',
			'" . $set_admin . "',
			'" . $set_login_biometric_verification . "',
			'" . $set_status . "',
			'" . $set_notification_firstname . "',
			'" . $set_notification_lastname . "',
			'" . $set_creator_memberid . "',
			'" . $set_created . "',
			'" . $set_datetime_created . "',
			'" . $set_datetime_updated . "');";
		$permissionsid = insertTHECASHIER($tmp_sql);
		logger3("tmp_sql",$tmp_sql);
		logger3("permissionsid",$permissionsid);
		###################################################  
		
		
		### GET EMAILADDRESSID
		$tmp_emailaddress = $_SESSION['session']['registration']['emailaddress'];
		$tmp_memberid = $memberid;
		$tmp_accountid = $accountid;
		$tmp_status = "ACTIVE";
		$tmp_permissionsid = $permissionsid;
		$tmp_creator_memberid = $memberid;
		$set_datetime_created = $registration_datetime;
		$set_datetime_updated = $registration_datetime;
		
		$tmp_query = "INSERT into email_addresses (
			`emailaddressesid`,
			`emailaddress`,
			`memberid`,
			`accountid`,
			`status`,
			`permissionsid`,
			`creator_memberid`,
			`datetime_created`,
			`datetime_updated`
		) VALUES (
			'" . $tmp_emailaddressesid . "',
			'" . $tmp_emailaddress . "',
			'" . $tmp_memberid . "',
			'" . $tmp_accountid . "',
			'" . $tmp_status . "',
			'" . $tmp_permissionsid . "',
			'" . $tmp_creator_memberid . "',
			'" . $set_datetime_created . "',
			'" . $set_datetime_updated . "');";	
		$emailaddressesid = insertTHECASHIER($tmp_query);
		
		
		
		### NOW UPDATE SESSIONS:
		#unset($preregister);
		$_SESSION['member'] = $member = member($memberid);
		$_SESSION['account'] = $account = account($accountid);
		
		### ############################################################
		### ### NOW SEND SOME EMAIL:
		### $email_receipt = "registration_personal_photobangk";
		### 
		### 
		### $dear_who = "";
		### $dear_who = $_SESSION['member']['salutation'] . " " . $_SESSION['member']['firstname'] . " " . $_SESSION['member']['lastname'];
		### $transaction_timestamp = $_SESSION['authorization']['timestamp'];
		### // include($_SESSION['template']['company']['file_path'] . "shared/email_receipts.shared");
		### ############################################################
		
		################################################################################################
		### END :: REGISTER ACCOUNT:  PERSONAL
		################################################################################################
		
		

		
		
	################################################################################################
	### START :: REGISTER ACCOUNT:  BUSINESS
	################################################################################################
	
	
	### E-BUSINESS SPECIFIC
	
	//$_SESSION['session']['registration']['business_category'] = "SERVICES"; // i.e., pc / tech support 
	//$_SESSION['session']['registration']['business_subcategory'] = $_SESSION['session']['registration']['business_subcategory']; // "7379"; // i.e., pc / tech support 
	
	
	
	
	$_SESSION['session']['registration']['city'] = $_SESSION['session']['geo']['city'];
	$_SESSION['session']['registration']['state'] = $_SESSION['session']['geo']['region'];
	$_SESSION['session']['registration']['region'] = $_SESSION['session']['geo']['region'];
	$_SESSION['session']['registration']['region'] = $_SESSION['session']['geo']['region'];
	$_SESSION['session']['registration']['postalcode'] = $_SESSION['session']['geo']['cityid'];
	$_SESSION['session']['registration']['country_iso3'] = $_SESSION['session']['geo']['iso3'];
	
	
	$_SESSION['session']['registration']['agreement'] = "YES";
	
	$_SESSION['session']['registration']['transaction_fee'] = $master_config_creditcard_fee_GSP;
	
	$tmp_local_currency = geo_data($_SESSION['session']['geo']['iso3'],"iso3","currency_code");
	
	$tmp_system_country = "USA";
	
	if(stristr($tmp_local_currency,$_SESSION['template']['company']['currency1'])) {
		$currency_tranlsation = "Off";
	} else {
		$currency_tranlsation = "On";
	}
	
	$currency_0_country = $tmp_system_country;
	$currency_0_iso3 = $_SESSION['template']['company']['currency1'];
	$country_iso3 = $_SESSION['session']['registration']['country_iso3'];
	$currency_code = $tmp_local_currency;
	$blank_currency_country_2 = "";
	$blank_currency_code_2 = "";
	
	$tmp_gateway_profile = $master_config_default_gateway;
	
	$data_GB = "1";	
	
	
	$always_do_this = true;
	if($always_do_this) {

		$gallery_GB = "";
		
		$gallery_photo_limit = $master_config_photoBANGK_registration_free_gallery;	
		$photoBANGK_background_color = ""; //$master_config_photoBANGK_background_color;
		$photoBANGK_highlight_color = ""; //$master_config_photoBANGK_highlight_color;
		$photoBANGK_frame_color = ""; //$master_config_photoBANGK_gallery_frame_color;
		$photoBANGK_frame_style = ""; //$master_config_photoBANGK_frame_style;
		$photoBANGK_frame_width = ""; //$master_config_photoBANGK_frame_width;
		$photoBANGK_frame_color = ""; //$master_config_photoBANGK_frame_color;
		$photoBANGK_text_color = ""; //$master_config_photoBANGK_text_color;
		$photoBANGK_style_background = ""; //$master_config_photoBANGK_style_background;
		$photoBANGK_style_bg_opacity = ""; //$master_config_photoBANGK_style_bg_opacity;
		$photoBANGK_style_text_color = ""; //$master_config_photoBANGK_style_text_color;
		$photoBANGK_font_size = ""; //$master_config_photoBANGK_font_size;
		$photoBANGK_font_family = ""; //$master_config_photoBANGK_font_family;
		$photoBANGK_font_weight = ""; //$master_config_photoBANGK_font_weight;


		
		if(!empty($_SESSION['session']['registration']['coupon'])) {
		
			$tmp_sql = "SELECT * FROM coupons WHERE coupon = '". $_SESSION['session']['registration']['coupon'] ."';";
			$coupon_details = readTHECASHIER($tmp_sql);
			
			if(
			($coupon_details->free_gallery_space > 0) &&
			(
			($coupon_details->expiration == "0") ||
			($coupon_details->expiration >= $coupon_details->used)
			)
			) {
				$gallery_photo_limit = $coupon_details->free_gallery_space;
				
				$new_used = $coupon_details->used + 1;
				$tmp_sql = "
				UPDATE coupons 
				SET 
				used = '$new_used',
				datetime_updated = '". $registration_datetime ."'
				WHERE coupon = '". $_SESSION['session']['registration']['coupon'] ."';
				";
				$coupon_update = updateTHECASHIER($tmp_sql);
			}

			
		}
	}
	
	
	
	$account_hash = $business_account_hash = hash_me();
	### CREATE A BUSINESS ACCOUNT:
	$tmp_sql = "INSERT into accounts (
		`accountid`,
		`hash`,
		
		`accounttype`,
		`business_category`,
		
		`business_subcategory`,
		`descriptor`,
		
		`accountname`,
		`business_type`,
		
		`department`,
		`streetaddress1`,
		
		`streetaddress2`,
		`city`,
		
		`state`,
		`region`,
		
		`postalcode`,
		`country_iso3`,
		
		`dayphone`,
		`eveningphone`,
		
		`faxphone`,
		`mobilephone`,
		
		`emailaddress`,
		`agreement`,
		
		`photoBANGK_background_color`,
		`photoBANGK_highlight_color`,
		
		`photoBANGK_frame_color`,
		`photoBANGK_text_color`,
		
		`photoBANGK_style_background`,
		`photoBANGK_style_bg_opacity`,
		`photoBANGK_style_text_color`,
		
		`photoBANGK_font_size`,
		`photoBANGK_font_family`,
		`photoBANGK_font_weight`,
		
		
		`currency_translation`,
		
		`currency_0_country`,
		`currency_0_iso3`,
		
		`currency_country_1`,
		`currency_code_1`,
		
		`currency_country_2`,
		`currency_code_2`,
		
		`product_type`,
		`transaction_fee_total`,
		
		`transaction_fee_my`,
		`retry_fee`,
		
		`gateway_profile`,
		
		`sponsor_fee`,
		
		`status_payments`,
		`sponsor_accountid`,
		
		`sponsor_terms`,
		`data_GB`,
		
		`gallery_GB`,
		`gallery_photo_limit`,
		
		`creator_memberid`,
		
		`created`,
		`updated`
	) VALUES (
		'" . $blank_accountid . "',
		'" . $business_account_hash . "',
		
		'Business',
		'" . addslashes($_SESSION['session']['registration']['business_category']) . "',
		
		'" . addslashes($_SESSION['session']['registration']['business_subcategory']) . "',
		'" . addslashes($_SESSION['session']['registration']['unique_descriptor']) . "',
		
		'" . addslashes($_SESSION['session']['registration']['business_name']) . "',
		'" . addslashes($_SESSION['session']['registration']['business_type']) . "',
		
		'" . addslashes($_SESSION['session']['registration']['department']) . "',
		'" . addslashes($_SESSION['session']['registration']['streetaddress_1']) . "',
		
		'" . addslashes($_SESSION['session']['registration']['streetaddress_2']) . "',
		'" . addslashes($_SESSION['session']['registration']['city']) . "',
		
		'" . addslashes($_SESSION['session']['registration']['state']) . "',
		'" . addslashes($_SESSION['session']['registration']['region']) . "',
		
		'" . addslashes($_SESSION['session']['registration']['postalcode']) . "',
		'" . addslashes($country_iso3) . "',
		
		'" . addslashes($_SESSION['session']['registration']['phone_primary']) . "',
		'" . addslashes($_SESSION['session']['registration']['phone_secondary']) . "',
		
		'" . addslashes($_SESSION['session']['registration']['phone_fax']) . "',
		'" . addslashes($_SESSION['session']['registration']['mobilephone']) . "',
		
		'" . addslashes($_SESSION['session']['registration']['business_customer_support_emailaddress']) . "',
		'" . addslashes($_SESSION['session']['registration']['agreement']) . "',
		
		'". $photoBANGK_background_color ."',
		'". $photoBANGK_highlight_color ."',
		
		'". $photoBANGK_frame_color ."',
		'". $photoBANGK_text_color ."',
		
		
		'". $photoBANGK_style_background ."',
		'". $photoBANGK_style_bg_opacity ."',
		'". $photoBANGK_style_text_color ."',

		
		
		
		
		
		'". $photoBANGK_font_size ."',
		'". $photoBANGK_font_family ."',
		
		'". $photoBANGK_font_weight ."',
		'" . $currency_tranlsation . "',
		
		'" . $currency_0_country . "',
		'" . $currency_0_iso3 . "',
		
		'" . $country_iso3 . "',
		'" . $currency_code . "',
		
		'" . $blank_currency_country_2 . "',
		'" . $blank_currency_code_2 . "',
		
		'" . $blank_product_type . "',
		'" . $_SESSION['session']['registration']['transaction_fee'] . "',
		
		'" . $_SESSION['session']['registration']['transaction_fee'] . "',
		'" . $master_config_retry_fee . "',
		
		'" . $tmp_gateway_profile . "',
		'" . $tmp_sponsor_fee . "',
		'ON',
		
		'" . $_SESSION['member']['sponsor_accountid'] . "',
		'" . $_SESSION['member']['sponsor_terms'] . "',
		
		'" . $data_GB . "',
		'" . $gallery_GB . "',
		'" . $gallery_photo_limit . "',
		
		'" . $_SESSION['member']['memberid'] . "',
		'" . $registration_datetime . "',
		
		'" . $registration_datetime . "'
		);";
	$tmp_accountid = $business_accountid = insertTHECASHIER($tmp_sql);
	logger3("tmp_sql",$tmp_sql);
	logger3("tmp_accountid",$tmp_accountid);
	//exit;
	
	
	### SET OPENING ACCOUNT BALANCE
	$new_account_balance = "0.00";
	
	
	### NOW SET AN ACCOUNT BALANCE:
	$tmp_sql = "INSERT into balances (
		`balanceid`,
		`platform`,
		`currency_iso3`,
		`accountid`,
		`account_balance`,
		`approved`,
		`sponsor_balance`,
		`available`,
		`created`
	) VALUES (
		'" . $blank_balanceid . "',
		'" . echo_platform() . "',
		'" . $_SESSION['template']['company']['currency1'] . "',
		'" . $tmp_accountid . "',
		'". $new_account_balance ."',
		'0.00',
		'0.00',
		'0.00',
		'" . $registration_datetime . "');";
	logger3("tmp_sql",$tmp_sql);
	$tmp_balanceid = insertTHECASHIER($tmp_sql);
	logger3("tmp_balanceid",$tmp_balanceid);
	
	
	
	### SET PERMISSIONS: ############################
	
	$set_permissionsid = "";
	$set_hash = make_hash();
	$set_memberid = $_SESSION['member']['memberid'];
	$set_accountid = $tmp_accountid;
	$set_accounttype = "Business";
	$set_permissions = "MASTER";
	$set_admin = "";
	$set_login_biometric_verification = "OFF";
	$set_status = "ACTIVE";
	$set_notification_firstname = "";
	$set_notification_lastname = "";
	$set_creator_memberid = $_SESSION['member']['memberid'];
	$set_created = ""; // legacy
	$set_datetime_created = $registration_datetime;
	$set_datetime_updated = $registration_datetime;
	
	$tmp_sql = "INSERT into permissions (
		`permissionsid`,
		`hash`,
		`memberid`,
		`accountid`,
		`accounttype`,
		`permissions`,
		`admin`,
		`login_biometric_verification`,
		`status`,
		`notification_firstname`,
		`notification_lastname`,
		`creator_memberid`,
		`created`,
		`datetime_created`,
		`datetime_updated`
	) VALUES (
		'" . $set_permissionsid . "',
		'" . $set_hash . "',
		'" . $set_memberid . "',
		'" . $set_accountid . "',
		'" . $set_accounttype . "',
		'" . $set_permissions . "',
		'" . $set_admin . "',
		'" . $set_login_biometric_verification . "',
		'" . $set_status . "',
		'" . $set_notification_firstname . "',
		'" . $set_notification_lastname . "',
		'" . $set_creator_memberid . "',
		'" . $set_created . "',
		'" . $set_datetime_created . "',
		'" . $set_datetime_updated . "');";
	$permissionsid = insertTHECASHIER($tmp_sql);
	logger3("tmp_sql",$tmp_sql);
	logger3("permissionsid",$permissionsid);
	
	
	
	### SET IDS: ############################
	
	$set_idid = "";
	$set_hash = make_hash();
	//$set_filename = addslashes($_SESSION['session']['registration']['government_id']['filename']);
	$set_memberid = $_SESSION['member']['memberid'];
	$set_accountid = $tmp_accountid;
	$set_status = ($_SESSION['session']['registration']['do_this_later_checkbox']=='yes') ? "Active" : "Later";
	$set_datetime_created = $registration_datetime;
	$set_datetime_updated = $registration_datetime;
	
	# COPY ID FILE:
	//$tmp_extension = explode(".",$_SESSION['session']['registration']['government_id']['filename']);
	$count_extension = count($tmp_extension) - 1;
	$file_extension = $tmp_extension[$count_extension];
	$new_filename = $set_hash . "." . $file_extension;
	//copy("ids/" . $_SESSION['session']['registration']['government_id']['filename'],"ids/" . $new_filename);
	
	$tmp_sql = "INSERT into ids (
		`idid`,
		`hash`,
		`filename`,
		`memberid`,
		`accountid`,
		`status`,
		`datetime_created`,
		`datetime_updated`
	) VALUES (
		'" . $set_idid . "',
		'" . $set_hash . "',
		'" . $set_filename . "',
		'" . $set_memberid . "',
		'" . $set_accountid . "',
		'" . $set_status . "',
		'" . $set_datetime_created . "',
		'" . $set_datetime_updated . "');";
	$idid = insertTHECASHIER($tmp_sql);
	logger3("tmp_sql",$tmp_sql);
	logger3("idid",$idid);
	###################################################
	
	
	
	
	### NOW UPDATE SESSIONS:
	$tmp_memberid = $_SESSION['member']['memberid']; //$memberid;
	$_SESSION['member'] = $member = "";
	$_SESSION['member'] = $member = member($tmp_memberid);
	//logger3("_SESSION['member']",$_SESSION['member']);
	
	$tmp_accountid = $personal_accountid;
	$_SESSION['account'] = $account = "";
	$_SESSION['account'] = $account = account($tmp_accountid); // shoudl be no account
	//logger3("_SESSION['account']",$_SESSION['account']);
	
	
		
	### NOW CREATE AN EMAIL ACCOUNT FOR THE BUSINESS ACCOUNT:
	logger3("business_accountid",$business_accountid);
	make_a_new_business_email_account($business_accountid=$business_accountid);
	
	
	### now set the account business address if empty (i.e., not required for registration):
	if(empty($_SESSION['session']['registration']['business_customer_support_emailaddress'])) {
		
		$tmp_account_details = account($business_accountid);
	
		$tmp_sql = "UPDATE accounts SET emailaddress = '". $tmp_account_details[email_account_address] ."' WHERE accountid = '$business_accountid';";
		updateTHECASHIER($tmp_sql);
	}
	
	
	
	### BUSINESS LINE MAKER:
	business_line_extension_maker($business_accountid=$business_accountid,$DID_to_check="");
	
	
	
	
	//exit;
	
	
	
	############################################################
	### NOW SEND SOME EMAIL:
	############################################################
	### TO NEW: ACCOUNT HOLDER
	############################################################
	
	### $gallery_URL = "https://photo.BANGK.com/". $_SESSION['session']['registration']['business_customer_support_emailaddress'];
	### 
	### 
	### if(!$_SESSION['session']['registration']['business_customer_support_emailaddress']) {
	###   $tmp_account_details = account($business_accountid);
	###   $gallery_URL = "https://photo.BANGK.com/". $tmp_account_details['emailaddress'];
	### }
	### 
	### $email_receipt = "registration_business_photobangk";
	### $dear_who = "";
	### if($_SESSION['member']['salutation']) {
	###   $dear_who = $_SESSION['member']['salutation'] . " ";
	### }
	### $dear_who = $dear_who . $_SESSION['member']['firstname'] . " " . $_SESSION['member']['lastname'];
	### $transaction_timestamp = $_SESSION['authorization']['timestamp'];
	### // include($_SESSION['template']['company']['file_path'] . "shared/email_receipts.shared");



	
	
	
}


function validateAge($birthday, $age = 18)
{
    // $birthday can be UNIX_TIMESTAMP or just a string-date.
    if(is_string($birthday)) {
        $birthday = strtotime($birthday);
    }

    // check
    // 31536000 is the number of seconds in a 365 days year.
    if(time() - $birthday < $age * 31536000)  {
        return false;
    }

    return true;
}





function convert_file_to_PDF($existing_path_to_filename,$converted_path_to_PDF_filename) {
	
	logger3(0,0);
	logger3("existing_path_to_filename",$existing_path_to_filename);
	logger3("converted_path_to_PDF_filename",$converted_path_to_PDF_filename);

	///PNG
	if(stristr($existing_path_to_filename,".png")) {
		$file_to_convert = imagecreatefrompng($existing_path_to_filename);
	} else
	
	///JPG
	if(
		(stristr($existing_path_to_filename,".jpg")) 
		|| (stristr($existing_path_to_filename,".jpeg")) 
	) {
		$file_to_convert = imagecreatefromjpeg($existing_path_to_filename);
	} else
	
	///BMP
	if(
		(stristr($existing_path_to_filename,".bmp"))
	) {
		$file_to_convert = imagecreatefromwbmp($existing_path_to_filename);
	} else
	
	///GIF
	if(
		(stristr($existing_path_to_filename,".gif"))
	) {
		$file_to_convert = imagecreatefromgif($existing_path_to_filename);
	} else
	
	///PDF -- DO NOT CONVERT -- JUST RENAME THE FILE IF NECESSARY:
	if(
		(stristr($existing_path_to_filename,".pdf"))
	) {
		
		if($existing_path_to_filename == $converted_path_to_PDF_filename) {
			return;
		} else {
			$current = file_get_contents($existing_path_to_filename);
			file_put_contents($converted_path_to_PDF_filename, $current);
			return;
		}

	}
	
	logger3(1,0);
	$converted_file_data = new Imagick();
	
	ob_start();
	imagepng($file_to_convert);
	$image_data = ob_get_contents();
	ob_end_clean();
	logger3(2,0);
	
	// Get image source data
	$converted_file_data->readimageblob($image_data);
	
	logger3(3,0);
	
	$converted_file_data->setImageCompression(imagick::COMPRESSION_JPEG);
	logger3(4,0);
    $converted_file_data->setImageCompressionQuality(80);
    logger3(5,0);
	$converted_file_data->setImageFormat('pdf');
	logger3(6,0);
	$file_name = $converted_path_to_PDF_filename;
	$file_data = $converted_file_data;
	file_put_contents($file_name,$file_data);
	
	logger3(7,0);
	///uncomment to display:
	//header("Content-Type: application/pdf");
	//echo $im;
}


function merge_multiple_pdf_douments($document_filename_array="",$merged_filename) {
	
	
	//$fileArray= array("name1.pdf","name2.pdf","name3.pdf","name4.pdf");
	
	$fileArray = $document_filename_array;
	
	//test("fileArray",$fileArray);
	
	//$datadir = "/BANGK!/authorizations/ids/";
	$datadir = "/var/www/html/test/";
	
	$merged_filename = str_ireplace(".pdf","",$merged_filename);
	
	//test("merged_filename",$merged_filename);
	
	$outputName = $datadir.$merged_filename.".pdf";
	
	//test("outputName",$outputName);
	
	$cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=". $outputName . " ";
	//Add each pdf file to the end of the command
	foreach($fileArray as $file) {
	    $cmd .= $file." ";
	}
	$result = shell_exec($cmd);
	
	
}





function insert_ip_record($member_hash) {
	
	$tmp_sql = "SELECT ip FROM ips 
				WHERE member_hash = '". $member_hash ."'
				AND ip = '". $_SERVER['REMOTE_ADDR'] ."'
				;";
	logger3("tmp_sql",$tmp_sql);
	
	$existing_ip = getTHECASHIER($tmp_sql);
	logger3("existing_ip",$existing_ip);
	
	if(!$existing_ip) {
		
		$registration_datetime = datetime();
		$memberid = getTHECASHIER("SELECT memberid FROM members WHERE hash = '". $member_hash ."';");
		
		### GET IPID:
		$tmp_query = "INSERT into ips (
			`ipid`,
			`memberid`,
			`member_hash`,
			`ip`,
			`status`,
			`created`,
			`updated`
		) VALUES (
			'" . $ipid . "',
			'" . $memberid . "',
			'" . $member_hash . "',
			'" . $_SERVER['REMOTE_ADDR'] . "',
			'',
			'" . $registration_datetime . "',
			'" . $registration_datetime . "')
			;";			
		$ipid = insertTHECASHIER($tmp_query);

	}
	
}


function call_threatmetrix(
							$threatmetrix_gateway_url=""
							,$org_id=""
							,$api_key=""
							,$session_id=""
							,$service_type=""
							,$event_type=""
							,$policy=""
							,$account_login=""
							,$password_hash=""
							,$account_number=""
							,$account_name=""
							,$account_email=""
							,$account_telephone=""
							,$account_address_street1=""
							,$account_address_street2=""
							,$account_address_city=""
							,$account_address_state=""
							,$account_address_country=""
							,$account_address_zip=""
							,$shipping_address_street1=""
							,$shipping_address_street2=""
							,$shipping_address_city=""
							,$shipping_address_state=""
							,$shipping_address_country=""
							,$shipping_address_zip=""
							,$cc_number_hash=""
							,$ssn_hash=""
							,$online_tld=""
							,$online_id_handle=""
							,$ach_routing_number=""
							,$ach_account_hash=""
							,$drivers_licence_number_hash=""
							,$local_attrib_1=""
							,$local_attrib_2=""
							,$local_attrib_3=""
							,$input_ip_address=""
) {
	
	
	
	### SET HASHES:
	if($password_hash) $password_hash = hash('sha512', $password_hash);
	if($cc_number_hash) $cc_number_hash = hash('sha512', $cc_number_hash);
	if($ssn_hash) $ssn_hash = hash('sha512', $ssn_hash);
	if($ach_account_hash) $ach_account_hash = hash('sha512', $ach_account_hash);
	if($drivers_licence_number_hash) $drivers_licence_number_hash = hash('sha512', $drivers_licence_number_hash);
	
	
	
	
	
	if(!$threatmetrix_gateway_url) $threatmetrix_gateway_url = "https://h-api.online-metrix.net/api/session-query";
	if(!$org_id) $org_id = "aohuqk6o";
	if(!$api_key) $api_key = "ezgonqbva6s44p68";
	if(!$session_id) $session_id = hash_me();
	if(!$service_type) $service_type = "session-policy";
	if(!$event_type) $event_type = "ACCOUNT_CREATION";
	if(!$policy) $policy = "";
	
	$url = $threatmetrix_gateway_url;
	//$parameters = "threatmetrix_gateway_url=". $threatmetrix_gateway_url;
	$parameters .= "org_id=". $org_id;
	$parameters .= "&api_key=". $api_key;
	$parameters .= "&session_id=". $session_id;
	$parameters .= "&service_type=". $service_type;
	$parameters .= "&event_type=". $event_type;
	$parameters .= "&policy=". $policy;
	$parameters .= "&account_login=". $account_login;
	$parameters .= "&password_hash=". $password_hash;
	$parameters .= "&account_number=". $account_number;
	$parameters .= "&account_name=". $account_name;
	$parameters .= "&account_email=". $account_email;
	$parameters .= "&account_telephone=". $account_telephone;
	$parameters .= "&account_address_street1=". $account_address_street1;
	$parameters .= "&account_address_street2=". $account_address_street2;
	$parameters .= "&account_address_city=". $account_address_city;
	$parameters .= "&account_address_state=". $account_address_state;
	$parameters .= "&account_address_country=". $account_address_country;
	$parameters .= "&account_address_zip=". $account_address_zip;
	$parameters .= "&shipping_address_street1=". $shipping_address_street1;
	$parameters .= "&shipping_address_street2=". $shipping_address_street2;
	$parameters .= "&shipping_address_city=". $shipping_address_city;
	$parameters .= "&shipping_address_state=". $shipping_address_state;
	$parameters .= "&shipping_address_country=". $shipping_address_country;
	$parameters .= "&shipping_address_zip=". $shipping_address_zip;
	$parameters .= "&cc_number_hash=". $cc_number_hash;
	$parameters .= "&ssn_hash=". $ssn_hash;
	$parameters .= "&online_tld=". $online_tld;
	$parameters .= "&online_id_handle=". $online_id_handle;
	$parameters .= "&ach_routing_number=". $ach_routing_number;
	$parameters .= "&ach_account_hash=". $ach_account_hash;
	$parameters .= "&drivers_licence_number_hash=". $drivers_licence_number_hash;
	$parameters .= "&local_attrib_1=". $local_attrib_1;
	$parameters .= "&local_attrib_2=". $local_attrib_2;
	$parameters .= "&local_attrib_3=". $local_attrib_3;
	$parameters .= "&input_ip_address=". $input_ip_address;


	//test("url",$url);
	//test("parameters",$parameters);



	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt ($ch, CURLOPT_POST, 1);
	curl_setopt ($ch, CURLOPT_POSTFIELDS, $parameters);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); 
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'GET');
	//curl_setopt($ch, CURLOPT_SSLVERSION,3);
	$data = curl_exec ($ch);
	//test("data",$data);
	
	$paramater_sets = explode("&",$data);
	//test("paramater_sets",$paramater_sets);
	
	$return_array = array();
	
	foreach($paramater_sets as $key => $val) {
		
		
		
		$tmp_parameter = "";
		$tmp_value = "";
		$value_set = explode("=",$val);
		$tmp_parameter = $value_set[0];
		$tmp_value = $value_set[1];
		$return_array[$tmp_parameter] = $tmp_value;
	}
	return $return_array;
}


function get_zip_code_details($zipcode) {
	$kurl_url = "https://maps.googleapis.com/maps/api/geocode/json";
	$kurl_parameters = "address=".$zipcode;
	$location_details = object2array(json_decode(kurl($kurl_url, $kurl_parameters, $kurl_post)));
	
	$return['raw'] = $return['raw'] = $location_details;
	$return['city'] = $location_details[results][0]->address_components[1]->long_name;
	//$return['state_iso2'] = $location_details[results][0]->address_components[3]->short_name;
	if(strlen($return['state_iso2']) > 2) {
		$return['state_iso2'] = $location_details[results][0]->address_components[4]->short_name;
	}
	
	//test("location_details",$location_details);
	//test("location_details[raw][results]",$location_details[results]);
	//test("location_details[raw]->results",$location_details[raw]->results);
	
	$return['raw'] = $location_details;
	//test("location_details",$location_details);
	
	//test("return",$return);
	
	$return['postal_code'] = $location_details[results][0]->address_components[0]->short_name;
	$return['city'] = $location_details[results][0]->address_components[1]->short_name;
	$return['state_iso2'] = $location_details[results][0]->address_components[2]->short_name;
	$return['country_iso2'] = $location_details[results][0]->address_components[3]->short_name;
	
	if(strlen($return['state_iso2']) > 2) {
		
		$return['postal_code'] = $location_details[results][0]->address_components[0]->short_name;
		$return['city'] = $location_details[results][0]->address_components[1]->short_name;
		$return['state_iso2'] = $location_details[results][0]->address_components[3]->short_name;
		$return['country_iso2'] = $location_details[results][0]->address_components[4]->short_name;
		
	}
	
	
	
	//test("return",$return);
	//exit;
	
	return $return;

}




function date_getFullTimeDifference( $start, $end )
{
	
	
	logger3("date_getFullTimeDifference-START",$start);
	logger3("date_getFullTimeDifference-END",$end);
	
		$uts['start']      =    strtotime( $start );
        $uts['end']        =    strtotime( $end );
        if( $uts['start']!==-1 && $uts['end']!==-1 )
        {
            if( $uts['end'] >= $uts['start'] )
            {
                $diff    =    $uts['end'] - $uts['start'];
                if( $years=intval((floor($diff/31104000))) )
                    $diff = $diff % 31104000;
                if( $months=intval((floor($diff/2592000))) )
                    $diff = $diff % 2592000;
                if( $days=intval((floor($diff/86400))) )
                    $diff = $diff % 86400;
                if( $hours=intval((floor($diff/3600))) )
                    $diff = $diff % 3600;
                if( $minutes=intval((floor($diff/60))) )
                    $diff = $diff % 60;
                $diff    =    intval( $diff );
                return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
            }
            else
            {
                echo "Ending date/time is earlier than the start date/time";
            }
        }
        else
        {
            echo "Invalid date/time data detected";
        }
}



function date_getFullTimeDifference_v2( $start, $end )
{
	
	
	logger3("date_getFullTimeDifference-START",$start);
	logger3("date_getFullTimeDifference-END",$end);
	
		$uts['start']      =    strtotime( $start );
        $uts['end']        =    strtotime( $end );
        if( $uts['start']!==-1 && $uts['end']!==-1 )
        {
            if( $uts['end'] >= $uts['start'] )
            {
                $diff    =    $uts['end'] - $uts['start'];
                if( $years=intval((floor($diff/31104000))) )
                    $diff = $diff % 31104000;
                if( $months=intval((floor($diff/2592000))) )
                    $diff = $diff % 2592000;
                if( $days=intval((floor($diff/86400))) )
                    $diff = $diff % 86400;
                if( $hours=intval((floor($diff/3600))) )
                    $diff = $diff % 3600;
                if( $minutes=intval((floor($diff/60))) )
                    $diff = $diff % 60;
                $diff    =    intval( $diff );
                return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
            }
            else
            {
                return "Ending date/time is earlier than the start date/time";
            }
        }
        else
        {
            return "Invalid date/time data detected";
        }
}


function make_pretty_time_difference_text($then) {
	
			$now = datetime();
			$FullTimeDifference_array = date_getFullTimeDifference($then,$now);
			//test("FullTimeDifference_array",$FullTimeDifference_array);
			$time_difference_text = "";
			//$time_difference_text .= "<span style='color:#F76064;'>";
			$time_difference_text .= " <i>~ ";

			if($FullTimeDifference_array['years'] != "0") {
				$time_difference_text .= " ";
				$time_difference_text .= $FullTimeDifference_array['years'] . "Years";
			}

			if($FullTimeDifference_array['months'] != "0") {
				$time_difference_text .= " ";
				$month_display_name = " Months";
				if($FullTimeDifference_array['months'] == "1") $month_display_name = " Month";
				$time_difference_text .= $FullTimeDifference_array['months'] . $month_display_name;
				//$time_difference_text .= " +";
			}

			if($FullTimeDifference_array['months'] == "0") {
				if($FullTimeDifference_array['days'] != "0") {
					$time_difference_text .= " ";
					$time_difference_text .= $FullTimeDifference_array['days'] . " Days";
				}
			}
			
			if($FullTimeDifference_array['months'] == "0") {
				if($FullTimeDifference_array['days'] == "0") {
					$time_difference_text .= " ";
					$display_hour = "Hours";
					if($FullTimeDifference_array['hours'] == 1) $display_hour = "Hour";
					$time_difference_text .= $FullTimeDifference_array['hours'] . " $display_hour";
				}
			}
			
			if($FullTimeDifference_array['months'] == "0") {
				if($FullTimeDifference_array['days'] == "0") {
					if($FullTimeDifference_array['hours'] == "0") {
						$time_difference_text .= " ";
						$time_difference_text .= $FullTimeDifference_array['minutes'] . " Minutes";
					}
				}
			}
			
			$time_difference_text .= " Ago</i>";
			return $time_difference_text;
	
}






function shorten_string($string, $wordsreturned) {
	
	/*  Returns the first $wordsreturned out of $string.  If string
	contains fewer words than $wordsreturned, the entire string
	is returned.
	*/
	
	$retval = $string;      //  Just in case of a problem
	 
	$array = explode(" ", $string);
	if (count($array)<=$wordsreturned)
	/*  Already short enough, return the whole thing
	*/
	{
	$retval = $string;
	}
	else
	/*  Need to chop of some words
	*/
	{
	array_splice($array, $wordsreturned);
	$retval = implode(" ", $array)." ...";
	}
	return $retval;
}


function merge2arrays($array1,$array2) {

	return array_unique(array_merge($array1,$array2), SORT_REGULAR);
}




function truncate_title($string, $length, $dots = "...") {
    return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}


function truncate_title_v2($string, $length, $dots = "...") {
	
	//test("string",$string);
	//test("length",$length);
	//test("dots",$dots);
	
	$string_length = strlen($string);
	
	$dots_length = strlen($dots);
	
	
	if($string_length > $length) {
		$final_length = $length - $dots_length1;
		$string = substr($string,0,$final_length) . $dots;
	}
	
    return $string;
}


function get_youtube_channel_ID($url){
  $html = file_get_contents($url);
  preg_match("'<meta itemprop=\"channelId\" content=\"(.*?)\"'si", $html, $match);
  if($match && $match[1]);
  return $match[1];
}



function object_to_array_v2($obj, $arr="") {
	
	
	return json_decode(json_encode($obj), true);
	
	
	/*
	if(!is_object($obj) && !is_array($obj)){
		$arr = $obj;
		return $arr;
	}

	foreach ($obj as $key => $value)
	{
		if (!empty($value))
		{
			$arr[$key] = array();
			object_to_array_v2($value, $arr[$key]);
		}
		else
		{
			$arr[$key] = $value;
		}
	}
	return $arr;
	*/
	
}





function google_api_key_to_use() {

	
	$google_api_key[0] = "AIzaSyBefIJHn6NImLcvU3-ztn6e9G7d436pcqA"; // shea.writer@payyap.network
	$google_api_key[1] = "AIzaSyAMCM54E09kQo8REMFFkh83zt80vFQR3VM"; // shea.writer@nsdb.com
	$google_api_key[2] = "AIzaSyDuOKGmq0ePksqrlsIwEST91hEvQ8r8GVw"; // api@tube-to-text.com
	$google_api_key[3] = "AIzaSyB9WKtdNXDEtXGjIwnD5KBADQ44gsFkKGc"; // support@thelottery.com
	$google_api_key[4] = "AIzaSyDNddTn08LnlOw3umeCqQQaiuBZ-mqVlvQ"; // tubetotext@gmail.com
	$google_api_key[5] = "AIzaSyCPWxU0agtp-qZL0LuqKwufaMenPF1lQP8"; // nsdb.ptyltd2@gmail.com
	$google_api_key[6] = "AIzaSyAgo4VBt5aWk5-0X41IpXdvTIWhNoN_J14"; // api@transcriber.wiki
	$google_api_key[7] = "AIzaSyBeubyakrjtML7V46G8ZsKSOJQkQ3PcPDk"; // payyap.ProPay@gmail.com
	$google_api_key[8] = "AIzaSyApKPCilyOlCdwtHrHAiZxXdlNId-QFKw4"; // payyap.customer.service@gmail.com
	$google_api_key[9] = "AIzaSyD-Uv-RZuoDJIkejgH6bg7qzX8C2WkwlfA"; // shea.writer@bangk.com
	$google_api_key[10] = "AIzaSyBsWsYpEQEwIJCGuGE0r6UWreJ6FSo_Ezw"; // shea@bangk.com
	
	//$google_api_key[11] = ""; // _XXXXX_
	//$google_api_key[12] = ""; // _XXXXX_
	//$google_api_key[13] = ""; // _XXXXX_
	//$google_api_key[14] = ""; // _XXXXX_
	
	
	
	$rand_key = array_rand($google_api_key, 1);
	logger3("rand_key",$rand_key);
	//$rand_key = ;
	return $google_api_key[$rand_key];
}


function youtube_get_video_details($youtube_video_id) {
		
	/*
		$yourtube_details['datetime_published']
		$yourtube_details['title']
		$yourtube_details['channel_name']
		$yourtube_details['time']['seconds']
		$yourtube_details['time']['minutes']
		$yourtube_details['time']['hours']
		$yourtube_details['duration']['seconds']
			
		
	*/
	
	//test("youtube_video_id",$youtube_video_id);

	
	### GET THE EPSIDOE DETAILS
	$kurl_url = "https://www.googleapis.com/youtube/v3/videos/";
	$kurl_parameters = "part=snippet&id=" . trim($youtube_video_id) . "&key=" . google_api_key_to_use();
	
	$full_url = $kurl_url . "?" . $kurl_parameters;
	//test("full_url",$full_url);
	
	$response = file_get_contents($full_url);
	//test("response",$response);
	//exit;
	
	$decoded = json_decode($response, true);
	//test("decoded",$decoded);
	//exit;
	
	$yourtube_details['datetime_published'] = $youtube_datetime_published = $decoded[items][0][snippet][publishedAt];
	$yourtube_details['title'] = $youtube_title = $decoded[items][0][snippet][title]; 
	$yourtube_details['channel_name'] = $youtube_channel_name = $decoded[items][0][snippet][channelTitle];
	
	
	
	if(!$yourtube_details['datetime_published']) {
	
		return "Invalid Video ID";
		exit;
			
	}
	
	
	/// duration:
	$kurl_url = "https://www.googleapis.com/youtube/v3/videos";
	$kurl_parameters = "?";
	$kurl_parameters .= "id=". trim($youtube_video_id);
	$kurl_parameters .= "&";
	$kurl_parameters .= "part=contentDetails";
	$kurl_parameters .= "&";
	$kurl_parameters .= "key=". google_api_key_to_use();
	
	
	
	
	$full_url = $kurl_url . $kurl_parameters;
	//logger3("full_url",$full_url);
	
	$response = file_get_contents($full_url);
	//logger3("response",$response);
	
	
	$decoded = json_decode($response, true);
	//logger3("decoded",$decoded);
	//exit;
	

	$yourtube_details['datetime'] = $covtime =  covtime($decoded['items']['0']['contentDetails']['duration']);
	
	//test("covtime",$covtime);
	
	$yourtube_details['duration']['seconds'] = $decoded['items']['0']['contentDetails']['duration'];
	
	//$yourtube_details['duration']['seconds'] = strtotime($yourtube_details['duration']['seconds']);
	//test("yourtube_details['duration']['seconds']",$yourtube_details['duration']['seconds']);
	
	$yourtube_details['duration']['seconds'] = $decoded['items']['0']['contentDetails']['duration'];
	
	
	$youtube_duration_explode = explode(":", $covtime);
	
	$yourtube_details['time']['hours'] = $youtube_duration_hours = number_format($youtube_duration_explode[0],0);
	$yourtube_details['time']['minutes'] = $youtube_duration_minutes = number_format($youtube_duration_explode[1],0);
	$yourtube_details['time']['seconds'] = $youtube_duration_minutes = number_format($youtube_duration_explode[2],0);
	
	$yourtube_details['duration']['total_seconds'] = ($yourtube_details['time']['hours'] * 3600) + ($yourtube_details['time']['minutes'] * 60) + ($yourtube_details['time']['seconds']);
	
	return $yourtube_details;
	
}



function youtube_get_video_datetime($youtube_video_id) {
		
	/*
		$yourtube_details['datetime']
		$yourtube_details['total_seconds']
			
		
	*/
	
		
	/// duration:
	$kurl_url = "https://www.googleapis.com/youtube/v3/videos";
	$kurl_parameters = "?";
	$kurl_parameters .= "id=". trim($youtube_video_id);
	$kurl_parameters .= "&";
	$kurl_parameters .= "part=contentDetails";
	$kurl_parameters .= "&";
	$kurl_parameters .= "key=". google_api_key_to_use();
	
	
	
	
	$full_url = $kurl_url . $kurl_parameters;
	//logger3("full_url",$full_url);
	
	$response = file_get_contents($full_url);
	//logger3("response",$response);
	
	
	$decoded = json_decode($response, true);
	
	
	
	
	
	if(!empty($decoded['items']['0']['contentDetails']['duration'])) {
	
		$yourtube_details['datetime'] =  $covtime = covtime($decoded['items']['0']['contentDetails']['duration']);

		sscanf($covtime, "%d:%d:%d", $hours, $minutes, $seconds);
		$yourtube_details['duration']['seconds'] = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
		$yourtube_details['time']['hours'] = $hours;
		$yourtube_details['time']['minutes'] = $minutes;
		$yourtube_details['time']['seconds'] = $seconds;
	}
	
	return $yourtube_details;
	
}



function traffic_counter($domain="") {
	
	if(!$domain) $domain = $_SESSION['template']['company']['domain'];
	
	$_XXXXX_traffic_id = "";
	$_XXXXX_ip_address = $_SERVER['REMOTE_ADDR'];
	$_XXXXX_domain = $domain;
	$_XXXXX_page = $_SERVER['REQUEST_URI'];
	
	$getallheaders_details = getallheaders();
	//test("getallheaders_details",$getallheaders_details['User-Agent']);

	$_XXXXX_headers = addslashes($getallheaders_details['User-Agent']);
	$_XXXXX_datetime_created = datetime();
					
	$tmp_sql = "INSERT INTO `traffic`
				(
					`traffic_id`
					, `ip_address`
					, `domain`
					, `page`
					, `headers`
					, `datetime_created`
					) VALUES (
					'". $_XXXXX_traffic_id ."'
					,'". $_XXXXX_ip_address ."'
					,'". $_XXXXX_domain ."'
					,'". $_XXXXX_page ."'
					,'". $_XXXXX_headers ."'
					,'". $_XXXXX_datetime_created ."'
				)";
	$insert_results = insertTHECASHIER($tmp_sql,"transcriptions");
	
	return $insert_results;
}




function covtime($youtube_time){
		
		if(!$youtube_time) return "00:00:00";
		if($youtube_time == "") return "00:00:00";
		if($youtube_time == "0") return "00:00:00";
		if($youtube_time == "0:0:0") return "00:00:00";
		if($youtube_time == "00:00:00") return "00:00:00";
		
		$start = new DateTime('@0'); // Unix epoch
		$start->add(new DateInterval($youtube_time));
		return $start->format('H:i:s');
}   





function archive_is_curler($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, 0); 

	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;

}


//<input type="hidden" name="submitid" value="lxP+6e4KGEfgzNtZc0hgkkqby+EVLRd0Vrcowq1D4MF4K0vI4klOUKEnWr+iHNPU">

#STAGE 1:

function archive_is($url_to_archive) {

	$url = "https://archive.is";
	
	test("url",$url);
	//exit;
	
	$results = file_get_contents($url);
	
	//$results = archive_is($url,$parameters,$referrer);
	//test("results",$results);
	$results_exploded = explode('name="submitid" value="',$results);
	
	//test("results_exploded[1]",$results_exploded[1]);
	
	$results_exploded_again = explode('"',$results_exploded[1]);
	
	//test("results_exploded_again",$results_exploded_again[0]);
	
	$archive_sibmitid = $results_exploded_again[0];
	
	#STAGE 2:
	
	$url = "https://archive.is/submit/";
	$parameters = "";
	$parameters .= "url=" . $url_to_archive;
	$parameters .= "&submitid=";
	$parameters .= $archive_sibmitid;
	$parameters .= "&submit=save the page";
	$referrer = "";
	
	//$results = file_get_contents("http://tube-to-text.com/?transcription=4786a2934b57781e58ac7200301af80b");
	
	//test("results",$results);
	
	$results = archive_is_curler($url,$parameters,$referrer);
	//logger3("results",$results);
	
	
	$results_exploded = explode("Refresh: 0;url=",$results);
	
	$results_exploded_again = explode("Server:",$results_exploded[1]);
	
	$archive_url = explode("Server:",$results_exploded_again[0]);
	
	return $archive_url[0];
	
	//test("archive_url",$archive_url);
}





#############################################################################################
#############################################################################################
#############################################################################################
### GET ALL CHANNEL IDS FOR A USER:


function YOUTUBE_GET_ALL_PLAYLIST_IDS_PER_USER($youtube_username_or_channel_id) {
	
	$google_api_key = google_api_key_to_use();
	$youtube_username_or_channel_id = trim($youtube_username_or_channel_id);
	
	
	# //check youtube_channel_id FIRST:
	# $full_url = "https://www.googleapis.com/youtube/v3/search?part=id&id=". $youtube_username_or_channel_id ."&type=channel&key=".$google_api_key . "&maxResults=50";
	# 
	# //$response = file_get_contents($full_url);
	# $response = json_decode($response);
	# $response = object_to_array_v2($response);
	# //test("1-response",$response);
	# 
	# //test("youtube_username_or_channel_id",$youtube_username_or_channel_id);
	
	$playlistid_or_channelid = substr($youtube_username_or_channel_id, 0, 2);
	
	if($playlistid_or_channelid == "UC") { // TRY channelID
	//if(empty($response)) { 
		
		//$full_url = "https://www.googleapis.com/youtube/v3/playlists?key=". google_api_key_to_use() ."&part=id&channelId=". $youtube_channel_id;
		$full_url = "https://www.googleapis.com/youtube/v3/playlists?part=id&channelId=". $youtube_username_or_channel_id ."&key=". $google_api_key . "&maxResults=50";
		
		$response = file_get_contents($full_url);
		$response = json_decode($response);
		$response = object_to_array_v2($response);
		//test("2-response",$response);
		$URL_to_use = $full_url;
		$decode_mode = "channelID";
		
		
	} else { // TRY youtube_username
		
		$full_url = "https://www.googleapis.com/youtube/v3/search?part=id&q=". $youtube_username_or_channel_id ."&type=channel&key=". $google_api_key . "&maxResults=50";
		
		$response = file_get_contents($full_url);
		$response = json_decode($response);
		$response = object_to_array_v2($response);
		//test("2-response",$response);
		$URL_to_use = $full_url;
		$decode_mode = "username";
		
		
	}
	
	
	//exit;
	
	
	
	$nextPageToken = $response['nextPageToken'];
	////test("1. nextPageToken",$nextPageToken);
	//exit;
	
	$list_of_channels = array();
	$channel_key = 0;
	$first_page = true;
	$last_page = false;
	
	while(
		(!empty($nextPageToken)) 
		|| ($first_page == true)
		|| ($last_page == true)
	) {
		
		$first_page = false;
	
		foreach($response['items'] as $key => $details) {
			
			if(stristr($decode_mode,"channelID")) {
			
				$list_of_channels[$channel_key] = $details['id'];
			
			} else {
			
				$list_of_channels[$channel_key] = $details['id']['channelId'];
			}
			
			$channel_key++;
	
		}
		
		//test("list_of_channels",$list_of_channels);
		//exit;
	
		$response = "";
		$pagetoken_url = $full_url . "&pageToken=". $nextPageToken;
		
		$response = file_get_contents($pagetoken_url);
		$response = json_decode($response);
		$response = object_to_array_v2($response);
		$nextPageToken = $response['nextPageToken'];
		////test("2. nextPageToken",$nextPageToken);
		////test("30 list_of_channels",$list_of_channels);
		////test("channel_key",$channel_key);
		
		
		if($last_page == true) {
			$channel_ids_array = array_unique($list_of_channels);
			////test("200 channel_ids_array",$channel_ids_array);
			return $channel_ids_array;
		}
		
		if(
			(empty($nextPageToken))
			&& ($first_page == false)
		) {
			$last_page = true;
			////test("last_page",$last_page);
		}
		
		////test("nextPageToken",$nextPageToken);
		////test("second_page",$second_page);
		
		
		//exit;
		
		# if($channel_key > 10) {
		# 	////test("err",0);
		# 	exit;
		# }
		
		////test("nextPageToken",$nextPageToken);
		////test("first_page",$first_page);
		////test("last_page",$last_page);
	
	}
	
	$channel_ids_array = array_unique($list_of_channels);
	////test("10 channel_ids_array",$channel_ids_array);
	
	return $channel_ids_array;

}




### ...GET ALL CHANNEL IDS FOR A USER.
#############################################################################################
#############################################################################################
#############################################################################################


#############################################################################################
#############################################################################################
#############################################################################################
### YOUTUBE_DB_ALL_VIDEOS_PER_PLAYLIST:



function YOUTUBE_DB_ALL_VIDEOS_PER_PLAYLIST($playlistid_or_channelid="",$api_mode="") {
	
	
	/// SET API MODE:
	if(!$api_mode) $api_mode = "ADD NEW";
	if(stristr($api_mode,"UPDATE")) {
		$pages_to_display = 1;
		$maxResults = 10;
	
	} else if(stristr($api_mode,"ADD NEW")) { // ADD NEW // COMPLETE LOOKUP
		$pages_to_display = 1000000000;
		$maxResults = 50;		
	} else {
		return FALSE;
	}
	
	test("YOUTUBE_DB_ALL_VIDEOS_PER_PLAYLIST(playlistid_or_channelid)",$playlistid_or_channelid);
	test("api_mode",$api_mode);
	
	//if(!$pages_to_display) $pages_to_display = 1000000000;
	
	//exit;
	
	$google_api_key = google_api_key_to_use();
	
	
	///https://www.googleapis.com/youtube/v3/?part=snippet&order=datee&maxResults=20&key={API_KEY}

	$API_to_use = substr($playlistid_or_channelid, 0, 2);
	
	test("API_to_use",$API_to_use);
	
	if($API_to_use == "PL") $API_to_use = "PLAYLIST_ID";
	if($API_to_use == "UC") $API_to_use = "CHANNEL_ID";
	
	if($API_to_use == "CHANNEL_ID") {
		$full_url = "";
		//$full_url .= "https://www.googleapis.com/youtube/v3/playlistItems?key=". $google_api_key;
		$full_url .= "https://www.googleapis.com/youtube/v3/search?key=". $google_api_key;
		$full_url .= "&part=snippet";
		//$full_url .= "&playlistId=". $youtube_playlist_id;
		$full_url .= "&maxResults=". $maxResults;
		$full_url .= "&order=date";
		$full_url .= "&type=video";
		$full_url .= "&safeSearch=none";
		$full_url .= "&channelId=".$playlistid_or_channelid;
	
	}
	
	if($API_to_use == "PLAYLIST_ID") { /// PLAYLIST_ID
		
		$full_url = "";
		$full_url .= "https://www.googleapis.com/youtube/v3/playlistItems?key=". $google_api_key;
		//$full_url .= "https://www.googleapis.com/youtube/v3/search?key=". $google_api_key;
		$full_url .= "&part=snippet";
		$full_url .= "&playlistId=". $playlistid_or_channelid;
		$full_url .= "&maxResults=". $maxResults;
		//$full_url .= "&order=date";
		//$full_url .= "&type=video";
		$full_url .= "&safeSearch=none";
		//$full_url .= "&channelId=".$youtube_channelId;
	
	}
	
	
	test("full_url",$full_url);
	//exit;
		
	$response = file_get_contents($full_url);
	$response = json_decode($response);
	$response = object_to_array_v2($response);
	//test("response['pageInfo']",$response['pageInfo']);
	test("response",$response);
	//exit;
	
	#############################################
	### START WHILE: SET SOME EVARS:
	if(!empty($response['nextPageToken'])) {
				$next_page_token = $response['nextPageToken'];
	} else {
		$next_page_token = "";	
	}
	$is_there_a_next_page = TRUE; // first page is always on
	$page_number = 0;
	$record_number = 0;
	while($is_there_a_next_page == TRUE) {
		
		$page_number++;
		test("page_number",$page_number);
		
		foreach($response['items'] as $key => $details) {
			
			$record_number++;
			test("record_number",$record_number);
			
			
			
			$tmp_videoId = "";
			if($API_to_use == "PLAYLIST_ID") {
				if(!empty($details['snippet']['resourceId']['videoId'])) $tmp_videoId = $details['snippet']['resourceId']['videoId'];
			}
			
			
			if($API_to_use == "CHANNEL_ID") {
				if(!empty($details['id']['videoId'])) $tmp_videoId = $details['id']['videoId'];
			}
			
			
			
			$existing_record = "";
			$tmp_sql = "";
			$tmp_sql = "SELECT hash FROM transcriptions WHERE youtube_video_id = '". $tmp_videoId ."';";
			test("tmp_sql",$tmp_sql);
			$existing_record = getTHECASHIER($tmp_sql,"transcriptions");
			test("existing_record",$existing_record);
			
			//$existing_record = "";
			if(empty($existing_record)) {
			
				test("record does not exist","adding to database");
			
				$extra_youtube_details = youtube_get_video_datetime($youtube_video_id=$tmp_videoId); // youtube_get_video_details($details['snippet']['resourceId']['videoId']);
				
		/*		
				$extra_youtube_details['datetime_published']
				$extra_youtube_details['title']
				$extra_youtube_details['channel_name']
				$extra_youtube_details['time']['seconds']
				$extra_youtube_details['time']['minutes']
				$extra_youtube_details['time']['hours']
				$extra_youtube_details['duration']['seconds']
				$extra_youtube_details['datetime']
					
				
		*/		
				
				###################################
				$_XXXXX_transcription_id = "";
				$_XXXXX_hash = hash_me();
				$_XXXXX_url = "https://www.youtube.com/watch?v=". $tmp_videoId;
				$_XXXXX_youtube_video_id = $tmp_videoId;
				$_XXXXX_IBM_json_response = "";
				$_XXXXX_IBM_json_response_serialized = "";
				$_XXXXX_text = "";
				$_XXXXX_duration = $extra_youtube_details['datetime'];
				$_XXXXX_duration_seconds = $extra_youtube_details['duration']['seconds'];
				$_XXXXX_title = addslashes($details['snippet']['title']);
				$_XXXXX_channel_name = addslashes($details['snippet']['channelTitle']);
				$_XXXXX_youtube_channel_id = $details['snippet']['channelId'];
				$_XXXXX_youtube_playlist_id = $details['snippet']['playlistId'];
				$_XXXXX_description = addslashes($details['snippet']['description']);
				$_XXXXX_thumbnail_url = $details['snippet']['thumbnails']['default']['url'];
				$_XXXXX_keywords = "";
				$_XXXXX_requested_by_emailaddress = "harvester@Transcriber.wiki";
				$_XXXXX_status = "PENDING";
				$_XXXXX_archive_is = "YES";
				$_XXXXX_datetime_published = $details['snippet']['publishedAt'];;
				$_XXXXX_datetime_created = datetime();
				
				if(!empty($_XXXXX_channel_name)) $_SESSION['tube-to-text']['channelTitle'] = $_XXXXX_channel_name;
							
							
							
				$tmp_sql = "INSERT INTO `transcriptions`
							(
							`transcription_id`
							, `hash`
							, `url`
							, `youtube_video_id`
							, `IBM_json_response`
							, `IBM_json_response_serialized`
							, `text`
							, `duration`
							, `duration_seconds`
							, `title`
							, `channel_name`
							, `youtube_channel_id`
							, `youtube_playlist_id`
							, `description`
							, `thumbnail_url`
							, `keywords`
							, `requested_by_emailaddress`
							, `status`
							, `archive_is`
							, `datetime_published`
							, `datetime_created`
							) VALUES (
							'". $_XXXXX_transcription_id ."'
							,'". $_XXXXX_hash ."'
							,'". $_XXXXX_url ."'
							,'". $_XXXXX_youtube_video_id ."'
							,'". $_XXXXX_IBM_json_response ."'
							,'". $_XXXXX_IBM_json_response_serialized ."'
							,'". $_XXXXX_text ."'
							,'". $_XXXXX_duration ."'
							,'". $_XXXXX_duration_seconds ."'
							,'". $_XXXXX_title ."'
							,'". $_XXXXX_channel_name ."'
							,'". $_XXXXX_youtube_channel_id ."'
							,'". $_XXXXX_youtube_playlist_id ."'
							,'". $_XXXXX_description ."'
							,'". $_XXXXX_thumbnail_url ."'
							,'". $_XXXXX_keywords ."'
							,'". $_XXXXX_requested_by_emailaddress ."'
							,'". $_XXXXX_status ."'
							,'". $_XXXXX_archive_is ."'
							,'". $_XXXXX_datetime_published ."'
							,'". $_XXXXX_datetime_created ."'
							);";
				test("tmp_sql",$tmp_sql);
				//exit;
				
				
				$insert_response = insertTHECASHIER($tmp_sql,"transcriptions");
				test("insert_response",$insert_response);
				
				//exit;
				
				//$channel_key++;
				
			} else {
				
				/* end existing record check */
				test("record already exists","next...");
				
			}

		}
		//exit;
		
		/// one page exception
		if($pages_to_display == $page_number) {
			
			$is_there_a_next_page = FALSE;
			$next_page_token = "";
			
		} else {
		
			$is_there_a_next_page = FALSE;
			test("1_response['nextPageToken']",$response['nextPageToken']);
			if(!empty($next_page_token)) {
				
				$is_there_a_next_page = TRUE;
				
				//$is_there_a_next_page = TRUE;
				$response = "";
				#$full_url = "https://www.googleapis.com/youtube/v3/search?pageToken=". $nextPageToken . "&part=id&q=". $youtube_user_name ."&type=channel&key=".$google_api_key . "&maxResults=2";
				
				//https://www.youtube.com/watch?v=8Q4RvDSTbEk$full_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&pageToken=". $next_page_token . "&playlistId=". $youtube_playlist_id ."&key=".$google_api_key . "&maxResults=50";
				
				$second_stage_full_url = $full_url . "&pageToken=". $next_page_token;
				
				test("second_stage_full_url",$second_stage_full_url);
				//exit;
				
				$response = file_get_contents($second_stage_full_url);
				$response = json_decode($response);
				$response = object_to_array_v2($response);
				test("2_response['nextPageToken']",$response['nextPageToken']);
				//test("response['pageInfo']",$response['pageInfo']);
				if(!empty($response['nextPageToken'])) {
					
					$next_page_token = $response['nextPageToken'];
					
				} else {
					
					$next_page_token = "";
					
				}
				
				test("next_page_token",$next_page_token);
				
				//exit;
				
			}
		}
	}

	### ...END WHILE!
	#############################################

}




### ....YOUTUBE_DB_ALL_VIDEOS_PER_PLAYLIST!
#############################################################################################
#############################################################################################
#############################################################################################



#############################################################################################
#############################################################################################
#############################################################################################
### START: YOUTUBE GET CHANNEL ID From VIDEO ID:




function YOUTUBE_GET_CHANNELID_FROM_VIDEOID($youtube_video_id) {

	$google_api_key = google_api_key_to_use();
	
	//$full_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=". $youtube_playlist_id ."&key=".$google_api_key . "&maxResults=50";
	
	$full_url = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=". $youtube_video_id ."&key=". $google_api_key;
	//$full_url = "https://www.googleapis.com/youtube/v3/search?part=snippet&id=". $youtube_video_id ."&key=". $google_api_key;
	
	//test("full_url",$full_url);
		
	$response = file_get_contents($full_url);
	$response = json_decode($response);
	$response = object_to_array_v2($response);
	//test("response",$response);
	//exit;
	
	return $response['items'][0]['snippet']['channelId'];
	exit;
		

}





### ....YOUTUBE GET CHANNEL ID From VIDEO ID!
#############################################################################################
#############################################################################################
#############################################################################################



function getSessionKYC3($url,$parameters,$referrer) {
	
	$ch = curl_init();
	curl_setopt ( $ch, CURLOPT_URL, $url );

	//Create And Save Cookies
    $tmpfname = dirname(__FILE__).'/cookie.txt';
    curl_setopt( $ch, CURLOPT_COOKIEJAR, $tmpfname);
    curl_setopt( $ch, CURLOPT_COOKIEFILE, $tmpfname);
	
	curl_setopt ( $ch, CURLOPT_URL, $url );
	
	if(isset($parameters)){
		curl_setopt ( $ch, CURLOPT_POST, 1);	
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $parameters); 
	}
    curl_setopt( $ch, CURLOPT_HEADER, false);
    curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );

    // EXECUTE
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}




function BingWebSearch($query) {
    // Prepare HTTP request
    // NOTE: Use the key 'http' even if you are making an HTTPS request. See:
    // http://php.net/manual/en/function.stream-context-create.php
    
    //test("query",$query);
    
    if(!$url) $url = "https://api.cognitive.microsoft.com/bing/v7.0/search";
    //if(!$key) $key = "74861cb593fc4c20a17cf2b53a2e60bb"; // key 1
    //if(!$key) $key = "20da5997d9c242549e5aa7146a173487"; // key 2
    if(!$key) $key = "9e702441fdd34de1b39ba9724aec9af1"; // key 2
    
    //test("key",$key);
    //exit;
    
    $headers = "Ocp-Apim-Subscription-Key: $key\r\n";
    $options = array ('http' => array (
                          'header' => $headers,
                           'method' => 'GET'));

    // Perform the Web request and get the JSON response
    $context = stream_context_create($options);
    $result = file_get_contents($url . "?q=" . urlencode($query), false, $context);

	//test("context",$context);
	//test("result",$result);

	//exit;
	

    // Extract Bing HTTP headers
    $headers = array();
    foreach ($http_response_header as $k => $v) {
        $h = explode(":", $v, 2);
        if (isset($h[1]))
            if (preg_match("/^BingAPIs-/", $h[0]) || preg_match("/^X-MSEdge-/", $h[0]))
                $headers[trim($h[0])] = trim($h[1]);
    }

    return array($headers, $result);
}



function get_flagged_key_words_array($mode="SPIDER") {
	

	$terms_array = array();	
	
	/// NEGATIVES
	if(
		(!stristr($mode,"SPIDER"))
	) {
		
		$terms_array[] = "FRAUD NOT prevention";
		$terms_array[] = "BANKRUPT NOT whitepages";
		$terms_array[] = "CELEBRITY NOT net worth";
		
		
	}


	/// FRAUD
	
	$terms_array[] = "DEFAUD";
	
	$terms_array[] = "SCAM";
	$terms_array[] = "SUCKS";
	$terms_array[] = "RIPOFF";
	
	//legal
	$terms_array[] = "CHAPTER 7";
	$terms_array[] = "CHAPTER 11";
	
	$terms_array[] = "ARRESTED";
	$terms_array[] = " SUED ";
	$terms_array[] = "ACCUSED";
	$terms_array[] = "CONVICTED";
	$terms_array[] = "SUBPOENA";
	$terms_array[] = "DEBT";
	
	//gambling
	$terms_array[] = "GAMBLING";
	$terms_array[] = "CASINO";
	$terms_array[] = "POKER";
	
	
	//pharma
	$terms_array[] = "VIAGRA";
	
	//brands
	$terms_array[] = "ROLEX";
	
	//celebrity
	
	$terms_array[] = "ENDORSE NOT API";
	$terms_array[] = "VITAMIN";
	$terms_array[] = "SUPPLEMENT";
	$terms_array[] = "REPLICA";
	
	$terms_array[] = "FAKE";
	
	
	if(
		(stristr($mode,"SPIDER")) 
	) {
		
		# $terms_array[] = "FRAUD";
		$terms_array[] = "BANKRUPT";
		$terms_array[] = "CELEBRITY";
		$terms_array[] = "CRYPTO";
		$terms_array[] = "18+";
		$terms_array[] = "+18";
		
		//$terms_array[] = "PROTEIN";
		//$terms_array[] = "GHB";
		//$terms_array[] = "HORMONE";
		//$terms_array[] = "THERAPY";
		
		// financial
		# $terms_array[] = "Merchant";
		# $terms_array[] = "Processing";
		$terms_array[] = "payment gateway";
		$terms_array[] = "merchant account";
		
		/// generic
		$terms_array[] = "Aripiprazole";
		$terms_array[] = "Adalimumab";
		$terms_array[] = "Esomeprazole";
		$terms_array[] = "Rosuvastatin";
		$terms_array[] = "Etanercept";
		$terms_array[] = "Fluticasone";
		$terms_array[] = "Infliximab";
		$terms_array[] = "glargine";
		$terms_array[] = "Filgrastim";
		$terms_array[] = "Glatiramer";
		$terms_array[] = "Rituximab";
		$terms_array[] = "Tiotropium";
		$terms_array[] = "Sitagliptin";
		$terms_array[] = "Emtricitabine";
		$terms_array[] = "Duloxetine";
		$terms_array[] = "Bevacizumab";
		$terms_array[] = "Pregabalin";
		$terms_array[] = "Oxycodone";
		$terms_array[] = "Celecoxib";
		$terms_array[] = "Epoetin";
		$terms_array[] = "Tenofovir";
		$terms_array[] = "Valsartan";
		$terms_array[] = "detemir";
		$terms_array[] = "Imatinib";
		$terms_array[] = "Trastuzumab";
		$terms_array[] = "Lisdexamfetamine";
		$terms_array[] = "Ranibizumab";
		$terms_array[] = "Ezetimibe";
		$terms_array[] = "Ipratropium";
		$terms_array[] = "Budesonide";
		$terms_array[] = "Memantine";
		$terms_array[] = "aspart";
		$terms_array[] = "Rivaroxaban";
		$terms_array[] = "lispro";
		$terms_array[] = "Buprenorphine";
		$terms_array[] = "Sildenafil";
		$terms_array[] = "Quetiapine";
		$terms_array[] = "Methylphenidate";
		$terms_array[] = "Tadalafil";
		$terms_array[] = "Oseltamivir";
		$terms_array[] = "Amphetamine";
		
		/// brands:
		$terms_array[] = "Abilify";
		$terms_array[] = "Humira";
		$terms_array[] = "Nexium";
		$terms_array[] = "Crestor";
		$terms_array[] = "Enbrel";
		$terms_array[] = "Advair";
		$terms_array[] = "Remicade";
		$terms_array[] = "Lantus";
		$terms_array[] = "Neulasta";
		$terms_array[] = "Copaxone";
		$terms_array[] = "Rituxan";
		$terms_array[] = "Spiriva";
		$terms_array[] = "Januvia";
		$terms_array[] = "Lantus";
		$terms_array[] = "Atripla";
		$terms_array[] = "Cymbalta";
		$terms_array[] = "Avastin";
		$terms_array[] = "Lyrica";
		$terms_array[] = "OxyContin";
		$terms_array[] = "Celebrex";
		$terms_array[] = "Combivent";
		$terms_array[] = "Epogen";
		$terms_array[] = "Truvada";
		$terms_array[] = "Diovan";
		$terms_array[] = "Levemir";
		$terms_array[] = "Gleevec";
		$terms_array[] = "Herceptin";
		$terms_array[] = "Vyvanse";
		$terms_array[] = "Lucentis";
		$terms_array[] = "Zetia";
		
		$terms_array[] = "Symbicort";
		$terms_array[] = "Namenda";
		$terms_array[] = "NovoLog";
		$terms_array[] = "Xarelto";
		$terms_array[] = "FlexPen";
		$terms_array[] = "Humalog";
		$terms_array[] = "Suboxone";
		$terms_array[] = "Viagra";
		$terms_array[] = "Seroquel";
		$terms_array[] = "AndroGel";
		$terms_array[] = "Enoxaparin";
		$terms_array[] = "Ritalin";
		$terms_array[] = " Cialis ";
		$terms_array[] = "Lipitor";
		$terms_array[] = "Tamiflu";
		$terms_array[] = "Adderall";
	}


	return $terms_array;
	
}





function ibm_watson_news_search_function($search_term="",$whitelabel_business_account_hash="") {

	//test("search_term",$search_term);
	
	
	### get_flagged_key_words_array
	//$terms_array = get_flagged_key_words_array($mode="LITE");
	
	
	$tmp_sql = "SELECT * 
				FROM api_search_engine_results 
				WHERE api_service_name = 'ibm_watson_news'
				AND search_term = '". addslashes($search_term) ."'
				AND serialized_search_results != ''
				AND whitelabel_business_account_hash = '".$whitelabel_business_account_hash."'
				;";
	
	//test("tmp_sql",$tmp_sql);
	
	$api_search_engine_results = readTHECASHIER($tmp_sql,"intelitruth");
	
	
	
	
	//test("api_search_engine_results",$api_search_engine_results);
	
	//exit;
	
	//test("api_search_engine_results",$api_search_engine_results);
	
	/*
	
	if(!$api_search_engine_results) {
		
		//test("1",1);
		
		/// SET HIT COUNTER ONCE
		$hit = 0;
		
		foreach($terms_array AS $terms_array_key => $term) {
			
			//test("1",2);
		
			//$search_term = "taylor gourley";
			
			$results = BingWebSearch($search_term . " " . $term);
			//test("results",$results);
			$results_decooded = object_to_array_v2(json_decode($results[1]));
			//test("results_decooded",$results_decooded);
			//exit;
			
			foreach($results_decooded[webPages][value] AS $key => $details) {
				
				//test("details",$details);
				
				//exit;
			
				//test("1",3);
				
				if(
					(
						stristr($details[name],$search_term)
						&&
						(
							stristr($details[name],$term)
							||
							stristr($details[snippet],$term)
						)
					)
					||
					(
						stristr($details[name],$term)
						&&
						(
							stristr($details[name],$search_term)
							||
							stristr($details[snippet],$search_term)
						)
					)
					
					||
					(
						stristr($details[name],$term)
						&&
						stristr($details[name],$search_term)
					)		
			
					||
					(
						stristr($details[snippet],$term)
						&&
						stristr($details[snippet],$search_term)
					)	
					
				) {
					
					//test("2",1);
					
					//exit;
					
					$search_term_results[$hit][name] = str_ireplace($search_term,"<span style='background-color:#FEFFCA;'>".$search_term ."</span>" ,$results_decooded[webPages][value][$key][name]);
					
					$search_term_results[$hit][name] = str_ireplace($term,"<span style='color:#DD0000;'>".$term ."</span>" ,$search_term_results[$hit][name]);
					
					
					$search_term_results[$hit][url] = $results_decooded[webPages][value][$key][url];
					
			
					$search_term_results[$hit][snippet] = str_ireplace($search_term,"<span style='background-color:#FEFFCA;'>".$search_term ."</span>" ,$results_decooded[webPages][value][$key][snippet]);
					
					$search_term_results[$hit][snippet] = str_ireplace($term,"<span style='color:#DD0000;'>".$term ."</span>" ,$search_term_results[$hit][snippet]);
					
					$hit++;
					
					/// build the guage values:
					if(stristr($term,"FRAUD")) {
						$risk_score = $risk_score + 100;
					
					} else if(stristr($term,"SCAM")) {
						$risk_score = $risk_score + 100;
					
					} else if(stristr($term,"ARREST")) {
						$risk_score = $risk_score + 20;
					
					} else if(stristr($term,"CONVICT")) {
						$risk_score = $risk_score + 20;
					
					} else if(stristr($term,"BANKRUPT")) {
						$risk_score = $risk_score + 50;
					
					} else if(stristr($term,"RIPOFF")) {
						$risk_score = $risk_score + 100;
					
					} else if(stristr($term,"SUED")) {
						$risk_score = $risk_score + 100;
					
					} else if(stristr($term,"SUCKS")) {
						$risk_score = $risk_score + 100;
					
					} else {
						$risk_score = $risk_score + 50;
					}
					
					//test("risk_score",$risk_score);
					//exit;
					
					
				}
			}
		}
	
		//test("1",4);
		//exit;
	
		$api_search_engine_results = array_map("unserialize", array_unique(array_map("serialize", $search_term_results)));
		
		if($risk_score < 1) {
		  $risk_score = 0;
		  $api_search_engine_results[0]['name'] = "No Flags Found";
		}
		
		$_XXXXX_bing_search_results_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXXX_api_service_name = "BING Search Engine API";
		$_XXXXX_search_term = addslashes($search_term);
		$_XXXXX_serialized_search_results = serialize($api_search_engine_results);
		$_XXXXX_serialized_search_results = addslashes($_XXXXX_serialized_search_results);
		$_XXXXX_risk_score = $risk_score;
		$_XXXXX_datetime_created = datetime();
						
		$tmp_sql = "INSERT INTO `api_search_engine_results`
					(
						`search_results_id`
						, `hash`
						, `api_service_name`
						, `search_term`
						, `serialized_search_results`
						, `risk_score`
						, `datetime_created`
					) VALUES (
						'". $_XXXXX_bing_search_results_id ."'
						,'". $_XXXXX_hash ."'
						,'". $_XXXXX_api_service_name ."'
						,'". $_XXXXX_search_term ."'
						,'". $_XXXXX_serialized_search_results ."'
						,'". $_XXXXX_risk_score ."'
						,'". $_XXXXX_datetime_created ."'
					)";
		//test("tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
		//test("insert_results",$insert_results);
		
		/// then get the results
		$tmp_sql = "SELECT * 
				FROM api_search_engine_results 
				WHERE api_service_name = 'BING Search Engine API'
				AND hash = '". $_XXXXX_hash ."'
				;";
	
		//test("tmp_sql",$tmp_sql);
	
		$api_search_engine_results = readTHECASHIER($tmp_sql,"intelitruth");
		//test("api_search_engine_results",$api_search_engine_results);
		
		$return['api_search_engine_results'] = unserialize($api_search_engine_results->serialized_search_results);
		$return['risk_score'] = $api_search_engine_results->risk_score;
	
	
		
	} else {
		
		//test("api_search_engine_results",$api_search_engine_results);
		$return['api_search_engine_results'] = unserialize($api_search_engine_results->serialized_search_results);
		$return['risk_score'] = $api_search_engine_results->risk_score;

	}
	
	
	*/
	
	
	
	$api_search_engine_results = unserialize($api_search_engine_results->serialized_search_results);
	$api_search_engine_results = json_decode($api_search_engine_results);
	$return['api_search_engine_results'] = object_to_array_v2($api_search_engine_results);
	
	$return['risk_score'] = $api_search_engine_results->risk_score;
	
	//exit;
	return $return;


} // end ibm_watson_news_search_function





function bing_search_function($search_term) {

	//test("search_term",$search_term);
	
	
	### get_flagged_key_words_array
	$terms_array = get_flagged_key_words_array($mode="LITE");
	
	
	$tmp_sql = "SELECT * 
				FROM api_search_engine_results 
				WHERE api_service_name = 'BING Search Engine API'
				AND search_term = '". addslashes($search_term) ."'
				AND serialized_search_results != ''
				;";
	
	test("111-tmp_sql",$tmp_sql);
	
	$api_search_engine_results = readTHECASHIER($tmp_sql,"intelitruth");
	
	test("111-api_search_engine_results",$api_search_engine_results);
	
	//exit;
	
	//test("api_search_engine_results",$api_search_engine_results);
	$api_search_engine_results = "";
	
	if(!$api_search_engine_results) {
		
		test("1",1);
		
		/// SET HIT COUNTER ONCE
		$hit = 0;
		
		foreach($terms_array AS $terms_array_key => $term) {
			
			test($terms_array_key . "-term",$term);
			test("1",2);
		
			//$search_term = "taylor gourley";
			
			$results = BingWebSearch($search_term . " " . $term);
			test("results",$results);
			$results_decooded = object_to_array_v2(json_decode($results[1]));
			//test("results_decooded",$results_decooded);
			//exit;
			
			foreach($results_decooded[webPages][value] AS $key => $details) {
				
				//test("details",$details);
				
				//exit;
			
				//test("1",3);
				
				if(
					(
						stristr($details[name],$search_term)
						&&
						(
							stristr($details[name],$term)
							||
							stristr($details[snippet],$term)
						)
					)
					||
					(
						stristr($details[name],$term)
						&&
						(
							stristr($details[name],$search_term)
							||
							stristr($details[snippet],$search_term)
						)
					)
					
					||
					(
						stristr($details[name],$term)
						&&
						stristr($details[name],$search_term)
					)		
			
					||
					(
						stristr($details[snippet],$term)
						&&
						stristr($details[snippet],$search_term)
					)	
					
				) {
					
					//test("2",1);
					
					//exit;
					
					$search_term_results[$hit][name] = str_ireplace($search_term,"<span style='background-color:#FEFFCA;'>".$search_term ."</span>" ,$results_decooded[webPages][value][$key][name]);
					
					$search_term_results[$hit][name] = str_ireplace($term,"<span style='color:#DD0000;'>".$term ."</span>" ,$search_term_results[$hit][name]);
					
					
					$search_term_results[$hit][url] = $results_decooded[webPages][value][$key][url];
					
			
					$search_term_results[$hit][snippet] = str_ireplace($search_term,"<span style='background-color:#FEFFCA;'>".$search_term ."</span>" ,$results_decooded[webPages][value][$key][snippet]);
					
					$search_term_results[$hit][snippet] = str_ireplace($term,"<span style='color:#DD0000;'>".$term ."</span>" ,$search_term_results[$hit][snippet]);
					
					$hit++;
					
					/// build the guage values:
					if(stristr($term,"FRAUD")) {
						$risk_score = $risk_score + 100;
					
					} else if(stristr($term,"SCAM")) {
						$risk_score = $risk_score + 100;
					
					} else if(stristr($term,"ARREST")) {
						$risk_score = $risk_score + 20;
					
					} else if(stristr($term,"CONVICT")) {
						$risk_score = $risk_score + 20;
					
					} else if(stristr($term,"BANKRUPT")) {
						$risk_score = $risk_score + 50;
					
					} else if(stristr($term,"RIPOFF")) {
						$risk_score = $risk_score + 100;
					
					} else if(stristr($term,"SUED")) {
						$risk_score = $risk_score + 100;
					
					} else if(stristr($term,"SUCKS")) {
						$risk_score = $risk_score + 100;
					
					} else {
						$risk_score = $risk_score + 50;
					}
					
					//test("risk_score",$risk_score);
					//exit;
					
					
				}
			}
		}
	
		//test("1",4);
		//exit;
	
		$api_search_engine_results = array_map("unserialize", array_unique(array_map("serialize", $search_term_results)));
		
		if($risk_score < 1) {
		  $risk_score = 0;
		  $api_search_engine_results[0]['name'] = "No Flags Found";
		}
		
		global $api_search_engine_results_details;
		
		$_XXXXX_bing_search_results_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXXX_whitelabel_business_account_hash = $api_search_engine_results_details['whitelabel_business_account_hash'];
		$_XXXXX_api_service_name = "BING Search Engine API";
		$_XXXXX_search_term = addslashes($search_term);
		$_XXXXX_serialized_search_results = serialize($api_search_engine_results);
		$_XXXXX_serialized_search_results = addslashes($_XXXXX_serialized_search_results);
		$_XXXXX_risk_score = $risk_score;
		$_XXXXX_datetime_created = datetime();
		
		$_XXXXX_whitelabel_business_account_hash = $_SESSION['intelitruth']['whitelabel_business_account_details']['hash'];
		if(!$_XXXXX_whitelabel_business_account_hash) $_XXXXX_whitelabel_business_account_hash = $_SESSION['account']['hash'];
						
		$tmp_sql = "INSERT INTO `api_search_engine_results`
					(
						`search_results_id`
						, `hash`
						, `whitelabel_business_account_hash`
						, `api_service_name`
						, `search_term`
						, `serialized_search_results`
						, `risk_score`
						, `datetime_created`
					) VALUES (
						'". $_XXXXX_bing_search_results_id ."'
						,'". $_XXXXX_hash ."'
						,'". $_XXXXX_whitelabel_business_account_hash ."'
						,'". $_XXXXX_api_service_name ."'
						,'". $_XXXXX_search_term ."'
						,'". $_XXXXX_serialized_search_results ."'
						,'". $_XXXXX_risk_score ."'
						,'". $_XXXXX_datetime_created ."'
					)";
		test("tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
		test("insert_results",$insert_results);
		
		/// then get the results
		$tmp_sql = "SELECT * 
				FROM api_search_engine_results 
				WHERE api_service_name = 'BING Search Engine API'
				AND hash = '". $_XXXXX_hash ."'
				;";
	
		//test("tmp_sql",$tmp_sql);
	
		$api_search_engine_results = readTHECASHIER($tmp_sql,"intelitruth");
		//test("api_search_engine_results",$api_search_engine_results);
		
		$return['api_search_engine_results'] = unserialize($api_search_engine_results->serialized_search_results);
		$return['risk_score'] = $api_search_engine_results->risk_score;
	
	
		
	} else {
		
		//test("api_search_engine_results",$api_search_engine_results);
		$return['api_search_engine_results'] = unserialize($api_search_engine_results->serialized_search_results);
		$return['risk_score'] = $api_search_engine_results->risk_score;
		
		
	}
	
	//exit;
	return $return;


} // end bing_search_function





function bing_search_function_v2($api_search_engine_hash) {

	//test("search_term",$search_term);
	
	$tmp_sql = "SELECT *
				FROM api_search_engine_results
				WHERE hash = '". $api_search_engine_hash ."'
				;";
	$this_api_search_engine_results_details = readTHECASHIER($tmp_sql,"intelitruth"); 
	
	//test("this_api_search_engine_results_details",$this_api_search_engine_results_details);
	
	$search_term = $this_api_search_engine_results_details->search_term;
	
	
	### get_flagged_key_words_array
	$terms_array = get_flagged_key_words_array($mode="LITE");
	
	
		
	foreach($terms_array AS $terms_array_key => $term) {
		
		//test($terms_array_key . "-term",$term);
		//test("1",2);
	
		//$search_term = "taylor gourley";
		
		$results = BingWebSearch($search_term . " " . $term);
		//test("results",$results);
		$results_decooded = object_to_array_v2(json_decode($results[1]));
		//test("results_decooded",$results_decooded);
		//exit;
		
		foreach($results_decooded[webPages][value] AS $key => $details) {
			
			//test("details",$details);
			
			//exit;
		
			//test("1",3);
			
			if(
				(
					stristr($details[name],$search_term)
					&&
					(
						stristr($details[name],$term)
						||
						stristr($details[snippet],$term)
					)
				)
				||
				(
					stristr($details[name],$term)
					&&
					(
						stristr($details[name],$search_term)
						||
						stristr($details[snippet],$search_term)
					)
				)
				
				||
				(
					stristr($details[name],$term)
					&&
					stristr($details[name],$search_term)
				)		
		
				||
				(
					stristr($details[snippet],$term)
					&&
					stristr($details[snippet],$search_term)
				)	
				
			) {
				
				//test("2",1);
				
				//exit;
				
				$search_term_results[$hit][name] = $results_decooded[webPages][value][$key][name];
				$search_term_results[$hit][name] = str_ireplace($search_term , '<span style="background-color:#FEFFCA;">' . $search_term . '</span>' , $search_term_results[$hit][name]);
				$search_term_results[$hit][name] = str_ireplace($term , '<span style="color:#DD0000;">' . $term . '</span>' , $search_term_results[$hit][name]);
				$search_term_results[$hit][name] = str_ireplace("'" , "’" , $search_term_results[$hit][name]);
				
				
				
				$search_term_results[$hit][url] = $results_decooded[webPages][value][$key][url];
				$search_term_results[$hit][url] = str_ireplace("'","’" , $search_term_results[$hit][url]);
				
		
			
				$search_term_results[$hit][snippet] = $results_decooded[webPages][value][$key][snippet];
				$search_term_results[$hit][snippet] = str_ireplace($search_term , '<span style="background-color:#FEFFCA;">' . $search_term . '</span>' , $search_term_results[$hit][snippet]);
				$search_term_results[$hit][snippet] = str_ireplace($term , '<span style="color:#DD0000;">' . $term . '</span>' , $search_term_results[$hit][snippet]);
				$search_term_results[$hit][snippet] = str_ireplace("'" , "’" , $search_term_results[$hit][snippet]);
				
				
				
				
				$hit++;
				
				/// build the guage values:
				if(stristr($term,"FRAUD")) {
					$risk_score = $risk_score + 100;
				
				} else if(stristr($term,"SCAM")) {
					$risk_score = $risk_score + 100;
				
				} else if(stristr($term,"ARREST")) {
					$risk_score = $risk_score + 20;
				
				} else if(stristr($term,"CONVICT")) {
					$risk_score = $risk_score + 20;
				
				} else if(stristr($term,"BANKRUPT")) {
					$risk_score = $risk_score + 50;
				
				} else if(stristr($term,"RIPOFF")) {
					$risk_score = $risk_score + 100;
				
				} else if(stristr($term,"SUED")) {
					$risk_score = $risk_score + 100;
				
				} else if(stristr($term,"SUCKS")) {
					$risk_score = $risk_score + 100;
				
				} else {
					$risk_score = $risk_score + 50;
				}
				
				//test("risk_score",$risk_score);
				//exit;
				
				
			}
		}
		//if($risk_score > 0) break;
	}
	
	//test("1",4);
	//exit;
	
	//test("search_term_results",$search_term_results);
	
	$api_search_engine_results = array_map("unserialize", array_unique(array_map("serialize", $search_term_results)));
	
	//test("api_search_engine_results",$api_search_engine_results);
	
	
	
	if($risk_score < 1) {
	  $risk_score = 0;
	  $api_search_engine_results[0]['name'] = "No Flags Found";
	}
	
	//global $api_search_engine_results_details;
	
	$_XXXXX_bing_search_results_id = "";
	$_XXXXX_hash = hash_me();
	
	$_XXXXX_api_service_name = "BING Search Engine API";
	$_XXXXX_search_term = addslashes($search_term);
	
	$_XXXXX_serialized_search_results = $api_search_engine_results;
	//$_XXXXX_serialized_search_results = json_encode($api_search_engine_results);
	$_XXXXX_serialized_search_results = serialize($_XXXXX_serialized_search_results);
	$_XXXXX_serialized_search_results = addslashes($_XXXXX_serialized_search_results);
	
	$_XXXXX_risk_score = $risk_score;
	$_XXXXX_status = "COMPLETE";
	$_XXXXX_datetime_created = datetime();
	
	$_XXXXX_whitelabel_business_account_hash = $_SESSION['intelitruth']['whitelabel_business_account_details']['hash'];
	if(!$_XXXXX_whitelabel_business_account_hash) $_XXXXX_whitelabel_business_account_hash = $_SESSION['account']['hash'];
	if(!$_XXXXX_whitelabel_business_account_hash) $_XXXXX_whitelabel_business_account_hash = $this_api_search_engine_results_details->whitelabel_business_account_hash;
					
	$tmp_sql = "INSERT INTO `api_search_engine_results`
				(
					`search_results_id`
					, `hash`
					, `whitelabel_business_account_hash`
					, `api_service_name`
					, `search_term`
					, `serialized_search_results`
					, `risk_score`
					, `status`
					, `datetime_created`
				) VALUES (
					'". $_XXXXX_bing_search_results_id ."'
					,'". $_XXXXX_hash ."'
					,'". $_XXXXX_whitelabel_business_account_hash ."'
					,'". $_XXXXX_api_service_name ."'
					,'". $_XXXXX_search_term ."'
					,'". $_XXXXX_serialized_search_results ."'
					,'". $_XXXXX_risk_score ."'
					,'". $_XXXXX_status ."'
					,'". $_XXXXX_datetime_created ."'
				)";
	//test("999-tmp_sql",$tmp_sql);
	//$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
	//test("999-insert_results",$insert_results);
	
	/// then get the results
	$tmp_sql = "SELECT * 
			FROM api_search_engine_results 
			WHERE api_service_name = 'BING Search Engine API'
			AND hash = '". $_XXXXX_hash ."'
			;";
	
	//test("9999-tmp_sql",$tmp_sql);
	
	//$api_search_engine_results = readTHECASHIER($tmp_sql,"intelitruth");
	
	
	//$return['api_search_engine_results'] = object_to_array_v2($api_search_engine_results->serialized_search_results);
	//$return['risk_score'] = $api_search_engine_results->risk_score;
	
	
	$return['api_search_engine_results'] = $api_search_engine_results;
	$return['risk_score'] = $risk_score;
	
	
		
	//test("bing_search_function_v2(return)",$return);
	
	
	
	//exit;
	return $return;


} // end bing_search_function_v2








function search_two_dimentional_array($value,$array) {
    
	foreach($array as $key => $details) {
		
		if(array_search($value, $details)) return $key;
	
	}
}



function intelitruth_whitelabel_crm_brander($whitebael_businesss_account_hash,$string_to_brand) {
	
	
	$tmp_sql = "SELECT * 
				FROM accounts
				WHERE hash = '". $whitebael_businesss_account_hash ."'
				;";
	$whitebael_businesss_account_details = readTHECASHIER($tmp_sql);
	
	$string_to_brand = str_ireplace("_XXXXX_COMPANY_NAME_XXXXX_",$whitebael_businesss_account_details->accountname,$string_to_brand);
	$string_to_brand = str_ireplace("_XXXXX_COMPANY_TELEPHONE_SUPPORT_XXXXX_",$whitebael_businesss_account_details->customer_support_phone_number_1,$string_to_brand);
	$string_to_brand = str_ireplace("_XXXXX_COMPANY_EMAIL_SUPPORT_XXXXX_",$whitebael_businesss_account_details->emailaddress_customer_support,$string_to_brand);	
	$string_to_brand = str_ireplace("_XXXXX_COMPANY_URL_SUPPORT_XXXXX_",$whitebael_businesss_account_details->whitelabel_FAQ_url,$string_to_brand);
	$string_to_brand = str_ireplace("_XXXXX_COMPANY_URL_HOMEPAGE_XXXXX_",$whitebael_businesss_account_details->url,$string_to_brand);

	return $string_to_brand;
	
	
	
}




# function search_xml_file($path_to_xml_file,$search) {
# 	
# 	$file_data = simplexml_load_file($path_to_xml_file);
# 	$file_data = json_encode($file_data);
# 	$results = stristr($file_data,$search);
# 	return $results;
# }


function curl_get_page($url) {
	$ch = curl_init();
	$timeout = 5;
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
	$userAgent = 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0';
	curl_setopt( $ch, CURLOPT_USERAGENT, $userAgent );
	$data = curl_exec($ch);
	curl_close($ch);
	return $data;
}







function get_pulldown_options($whitelabel_business_account_hash,$pulldown_name) {
	
	logger3("get_pulldown_options(whitelabel_business_account_hash)",$whitelabel_business_account_hash);
	logger3("get_pulldown_options(pulldown_name)",$pulldown_name);
	
	$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
	$tmp_sql = "SELECT * 
				FROM pulldown_options
				WHERE whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
				ORDER BY datetime_updatad DESC
				LIMIT 1;";
	logger3("tmp_sql",$tmp_sql);
	$pulldown_options_results = readTHECASHIER($tmp_sql,"intelitruth");
	logger3("pulldown_options_results->pulldown_values",$pulldown_options_results->pulldown_values);
	$pulldown_options_results_unserialized = unserialize($pulldown_options_results->pulldown_values);
	logger3("pulldown_options_results_unserialized",$pulldown_options_results_unserialized);
	$pulldown_options_results_unserialized_jasondecoded = json_decode($pulldown_options_results_unserialized);
	logger3("pulldown_options_results_unserialized_jasondecoded",$pulldown_options_results_unserialized_jasondecoded);
	$pulldown_options_final_array = object_to_array_v2($pulldown_options_results_unserialized_jasondecoded);
	logger3("pulldown_options_final_array",$pulldown_options_final_array);
	
	if($pulldown_options_final_array[$pulldown_name]) {
		
		return $pulldown_options_final_array[$pulldown_name];
	
	} else {
		
		$_XXXXX_whitelabel_business_account_hash = "DEFAULT";
		$tmp_sql = "SELECT * 
				FROM pulldown_options
				WHERE whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
				ORDER BY datetime_updatad DESC
				LIMIT 1;";
		logger3("tmp_sql",$tmp_sql);
		$pulldown_options_results = readTHECASHIER($tmp_sql,"intelitruth");
		logger3("pulldown_options_results->pulldown_values",$pulldown_options_results->pulldown_values);
		$pulldown_options_results_unserialized = unserialize($pulldown_options_results->pulldown_values);
		logger3("pulldown_options_results_unserialized",$pulldown_options_results_unserialized);
		$pulldown_options_results_unserialized_jasondecoded = json_decode($pulldown_options_results_unserialized);
		logger3("pulldown_options_results_unserialized_jasondecoded",$pulldown_options_results_unserialized_jasondecoded);
		$pulldown_options_final_array = object_to_array_v2($pulldown_options_results_unserialized_jasondecoded);
		logger3("pulldown_options_final_array",$pulldown_options_final_array);
		
		if($pulldown_options_final_array[$pulldown_name]) {
		
			return $pulldown_options_final_array[$pulldown_name];
	
		} else {
			
			return "ERR";
		}
	}			
	
}




function get_pulldown_options_v2($whitelabel_business_account_hash,$pulldown_name="",$pulldown_version="") {
	
	
	
	global $master_config_DEFAULT_ONBOARDING_TIERS;
	
	
	logger3("get_pulldown_options() whitelabel_business_account_hash",$whitelabel_business_account_hash);
	logger3("get_pulldown_options() pulldown_name",$pulldown_name);
	logger3("get_pulldown_options() pulldown_version",$pulldown_version);
	
	
	
	
	$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
	
	
	if($pulldown_name) {
		$_XXXXX_pulldown_name = addslashes($pulldown_name);
		$ADD_pulldown_name = "AND pulldown_name = '". $_XXXXX_pulldown_name ."'";
	}
	
	/// NOTE:  onboarding_business_description = TIERS;
	/// NO "version" for TIERS -- ALWAYS THE SAME!
	
	$_XXXXX_pulldown_version = $pulldown_version;
	if(!$_XXXXX_pulldown_version) $_XXXXX_pulldown_version = "DEFAULT";
	
	if(
		($pulldown_version)
		&& ($pulldown_name != "onboarding_business_description") 
	) {
	
		$_XXXXX_pulldown_version = addslashes($pulldown_version);
		$ADD_version = "AND version = '". $_XXXXX_pulldown_version ."'";
	}
	
	
	
	
	
	
	
	$tmp_sql = "SELECT * 
				FROM pulldown_options
				WHERE whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
				$ADD_pulldown_name
				$ADD_version
				ORDER BY datetime_updatad DESC
				LIMIT 1;";
	logger3("100-tmp_sql",$tmp_sql);
	
	$pulldown_options_results = readTHECASHIER($tmp_sql,"intelitruth");
	
	if(!empty($pulldown_options_results)) { 
	
		$pulldown_options_results_array = object_to_array_v2($pulldown_options_results);
	
		logger3("get_pulldown_options_v2() pulldown_options_results_array",$pulldown_options_results_array);
	
	
		$pulldown_options_results_array['pulldown_data'] = object_to_array_v2(json_decode($pulldown_options_results_array['pulldown_data']));
	
		logger3("get_pulldown_options_v2() pulldown_options_results_array",$pulldown_options_results_array);
	
		$pulldown_options_results = object_to_array_v2($pulldown_options_results_array);
	
		//$pulldown_options_results['pulldown_data'] = $options_data_array;
	
		//$pulldown_options_results = object_to_array_v2($pulldown_options_results);
	
		logger3("100-pulldown_options_results",$pulldown_options_results);
	
		logger3("101-pulldown_options_results['title']",$pulldown_options_results['title']);
	
	
	} else {
	
	
		logger3("get_pulldown_options_v2() 1-pulldown_options_results['title']",$pulldown_options_results['title']);
	
		// if(empty($pulldown_options_results['title']) {
		
		logger3("get_pulldown_options_v2() 2-pulldown_options_results['title']",$pulldown_options_results['title']);
		
		$_XXXXX_pulldown_version = "DEFAULT";
		
		//$_XXXXX_pulldown_version = $master_config_DEFAULT_ONBOARDING_TIERS;
		
		$_XXXXX_add_version = "AND version = '". $_XXXXX_pulldown_version ."'";
		
		$tmp_sql = "SELECT * 
					FROM pulldown_options
					WHERE whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
					AND pulldown_name = '". $_XXXXX_pulldown_name ."'
					$_XXXXX_add_version
					AND form_name != 'DEFAULT'
					ORDER BY datetime_updatad DESC
					LIMIT 1;";
		logger3("200-tmp_sql",$tmp_sql);
		
		$pulldown_options_results = readTHECASHIER($tmp_sql,"intelitruth");
		
		if(!empty($pulldown_options_results)) {
		
			$pulldown_options_results_array = object_to_array_v2($pulldown_options_results);
			
			logger3("200-pulldown_options_results_array",$pulldown_options_results_array);
			
			$options_data_array['pulldown_data'] = object_to_array_v2(json_decode($pulldown_options_results_array['pulldown_data']));
			logger3("200-options_data_array",$options_data_array);
			
			$pulldown_options_results = object_to_array_v2($options_data_array);
			
			//$pulldown_options_results['pulldown_data'] = $options_data_array;
			
			//$pulldown_options_results = object_to_array_v2($pulldown_options_results['pulldown_data']);
			
			logger3("200-pulldown_options_results",$pulldown_options_results);	
		}	
	}
	
	
	logger3("get_pulldown_options_v2() pulldown_options_results",$pulldown_options_results);
	
	
	
	return $pulldown_options_results;
	
}





function consolodate_aml_searches_into_one_array_for_display($whitelabel_business_account_hash,$search_term) {
	
	if($search_term) $add_serach_term = "AND search_term = '". $search_term ."'";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'European_Union_Financial_Sanctions_List'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'OSFI_Anti_Terrorism_Financing_List_entities'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'OSFI_Anti_Terrorism_Financing_List_persons'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'PEP LIST'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	//test("tmp_sql",$tmp_sql);
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	//test("results",$results);
	
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Unverified List (UVL) [Section 744.15]'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Unverified List (UVL) [Supplement No. 6]'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'denied_persons_list_22_November_2016'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Consolidated_United_Nations_Security_Council_Sanctions_List'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'AECA_Debarred_List_statutory'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'AECA_Debarred_List_administrative'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Department of State Designated Foreign Terrorist Organizations'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Department of State Terrorist Exclusion List (TEL)'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Japan Foreign End Users of Concern'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Immigrations and Customs Enforcement Most Wanted Fugitives :: Homeland Security Investigations'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Immigrations and Customs Enforcement Most Wanted Fugitives :: Enforcement and Removal'
				AND status = 'COMPLETE'
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'U.S. Marshals Service :: Major Fugitive Cases'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'U.S. Marshals Service :: 15 Most Wanted'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Naval Criminal Investigative Service  Wanted Fugitives'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Royal Canadian Mounted Police Wanted'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'U.S. Postal Inspection Service Most Wanted'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Nonproliferation Sanctions'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'Entity List'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'U.S. Secret Service Most Wanted'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'OFAC_SDN_XML'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name = 'OFAC_CONSOLIDATED_XML'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	
	
	###################################
	$tmp_sql = "SELECT * 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND results_list_name LIKE '%FBI%'
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	
	$tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	
	
	
	
	// ###################################
	// $tmp_sql = "SELECT * 
	// 			FROM AML_scan_results
	// 			WHERE process_stage LIKE '%OFAC_CONSOLIDATED_XML%'
	// 			
	// 			AND status = 'COMPLETE'
	// 			$add_serach_term
	// 			ORDER BY datetime_created DESC
	// 			LIMIT 1;
	// 			";
	// 
	// $tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	// 
	// if($tmp_results) {
	// 	$tmp_results['results_list_name'] = "OFAC_CONSOLIDATED_XML";
	// 	$results[] = $tmp_results;
	// }
	$tmp_results = "";
	
	
	
	
	
	
	
	### ###################################
	### $tmp_sql = "SELECT * 
	### 			FROM AML_scan_results
	### 			WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
	### 			AND results_list_name = '_XXXXX_'
	### 			AND status = 'COMPLETE'
	### 			ORDER BY datetime_created DESC
	### 			LIMIT 1;
	### 			";
	### 
	### $tmp_results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	
	
	
	if($tmp_results) $results[] = $tmp_results;
	$tmp_results = "";
	

	
	return $results;

}






function consolodate_aml_searches_into_one_array_for_display_v2($whitelabel_business_account_hash,$search_term) {
	
	
	### $ADD_LIST_NAMES = "AND (
	### 	results_list_name = 'European_Union_Financial_Sanctions_List'
	### 	, results_list_name = 'OSFI_Anti_Terrorism_Financing_List_entities'
	### 	, results_list_name = 'OSFI_Anti_Terrorism_Financing_List_persons'
	### 	, results_list_name = 'PEP LIST'
	### 	, results_list_name = 'Unverified List (UVL) [Section 744.15]'
	### 	, results_list_name = 'Unverified List (UVL) [Supplement No. 6]'
	### 	, results_list_name = 'denied_persons_list_22_November_2016'
	### 	, results_list_name = 'Consolidated_United_Nations_Security_Council_Sanctions_List'
	### 	, results_list_name = 'AECA_Debarred_List_statutory'
	### 	, results_list_name = 'AECA_Debarred_List_administrative'
	### 	, results_list_name = 'Department of State Designated Foreign Terrorist Organizations'
	### 	, results_list_name = 'Department of State Terrorist Exclusion List (TEL)'
	### 	, results_list_name = 'Immigrations and Customs Enforcement Most Wanted Fugitives :: Homeland Security Investigations'
	### 	, results_list_name = 'Immigrations and Customs Enforcement Most Wanted Fugitives :: Enforcement and Removal'
	### 	, results_list_name = 'Immigrations and Customs Enforcement Most Wanted Fugitives :: Human Trafficking'
	### 	, results_list_name = 'Japan Foreign End Users of Concern'
	### 	, results_list_name = 'U.S. Marshals Service :: Major Fugitive Cases'
	### 	, results_list_name = 'U.S. Marshals Service :: 15 Most Wanted'
	### 	, results_list_name = 'OFAC_SDN_XML'
	### 	, results_list_name = 'Naval Criminal Investigative Service  Wanted Fugitives'
	### 	, results_list_name = 'Royal Canadian Mounted Police Wanted'
	### 	, results_list_name = 'U.S. Postal Inspection Service Most Wanted'
	### 	, results_list_name = 'Entity List'
	### 	, results_list_name = 'Nonproliferation Sanctions'
	### 	, results_list_name = 'U.S. Secret Service Most Wanted'
	### 	, results_list_name = 'OFAC_CONSOLIDATED_XML'
	### 	, results_list_name LIKE '%FBI%'
	### 	, results_list_name = '_XXXXX_'
	### 	
	### 	)";
	
	
	$ADD_LIST_NAMES = "AND results_list_name != ''";
					
	if($search_term) $add_serach_term = "AND search_term = '". $search_term ."'";
	
	###################################
	$tmp_sql = "SELECT DISTINCT results_list_name 
				FROM AML_scan_results
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				$ADD_LIST_NAMES
				AND status = 'COMPLETE'
				$add_serach_term
				ORDER BY datetime_created DESC
				
				";
	//test("() tmp_sql",$tmp_sql);
	$results = "";
	$tmp_results = "";
	$tmp_results = object_to_array_v2(readarrayTHECASHIER($tmp_sql,"intelitruth"));
	
	//$tmp_results = array_unique($tmp_results);
	//test("tmp_results",$tmp_results);
	
	return $tmp_results;
	
	
	

}




function create_a_new_jane_doe_account($whitelabel_business_account_hash,$member_hash,$personal_account_hash,$business_account_hash) {
	
	
	logger3("create_a_new_jane_doe_account(whitelabel_business_account_hash)",$whitelabel_business_account_hash);
	logger3("create_a_new_jane_doe_account(member_hash)",$member_hash);
	logger3("create_a_new_jane_doe_account(personal_account_hash)",$personal_account_hash);
	logger3("create_a_new_jane_doe_account(business_account_hash)",$business_account_hash);
	
	$tmp_sql = "SELECT memberid 
				FROM members 
				WHERE hash = '". $member_hash ."'
				;";
	logger3("tmp_sql",$tmp_sql);
	$memberid = getTHECASHIER($tmp_sql);
	logger3("memberid",$memberid);
	
	
	$tmp_sql = "SELECT accountid 
				FROM accounts 
				WHERE hash = '". $business_account_hash ."'
				;";
	logger3("tmp_sql",$tmp_sql);
	$business_acountid = getTHECASHIER($tmp_sql);
	logger3("business_acountid",$business_acountid);
	
	
	
	
	$KYC_DATETIME = datetime_v2();
	$results = "";
	$results = array();
	#######################################################################################
	#######################################################################################
	### B!->member
	#######################################################################################
	#######################################################################################
	
	### member #########################################################################
	
	###  FIRST, CREATE A MEMBER:
	
	$new_member_hash = hash_me();
	$_XXXXX_firstname = "Judy Jane";
	$_XXXXX_lastname = "Doe";
	$_XXXXX_emailaddress = "judyjanedoe@example.com";
	$_XXXXX_social_security_number = "111223333";
	$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
	
	$tmp_sql = "INSERT into members (
		
		`memberid`,
		`hash`,
		
		`template_company_hash`,
		
		`sponsor_accountid`,
		
		`salutation`,
		`firstname`,
		`lastname`,
		
		`emailaddress`,
		`password`,
		`birthdate`,
		
		`social_security_number`,
		
		`country_iso3`,
		`timezone`,
		`authorization_voice`,
		
		`type`,
		`coupon_used_to_register`,
		`app_version`,
		
		`whitelabel_business_account_hash`,
		`created`,
		`updated`
		
		) VALUES (
			
		'" . $blank_memberid . "',
		'" . $new_member_hash . "',
		
		'" . $_SESSION['template']['company']['hash'] . "',
		
		
		'" . $_XXXXX_sponsor_accountid . "',

		'" . $_XXXXX_saluation . "',
		'" . $_XXXXX_firstname . "',
		'" . $_XXXXX_lastname . "',
		
		'" . $_XXXXX_emailaddress . "',
		'" . $_XXXXX_password . "',
		'" . $_XXXXX_birth_year . "',
		
		'" . $_XXXXX_social_security_number . "',
		
		'" . $_XXXXX_timezone['country_iso3'] . "',
		'" . $$_XXXXX_timezone['offset'] . "',
		'" . $master_config_authorization_voice . "',
		
		'" . $member_type . "',
		'" . $_XXXXX_coupon . "',
		'" . $incoming_vars['PAYYAP_version'] . "',
		
		'" . $_XXXXX_whitelabel_business_account_hash . "',
		'" . $KYC_DATETIME . "',
		'" . $KYC_DATETIME . "'
		)";
	
	logger3("test_sql",$tmp_sql);
	$new_memberid = $results = insertTHECASHIER($tmp_sql);
	logger3("new_memberid",$new_memberid);

	
	
	
	#######################################################################################
	#######################################################################################
	### B!->accounts
	#######################################################################################
	#######################################################################################
	
	
	
	### personal #########################################################################
	
	$new_account_personal_hash = hash_me();
	
	
	$tmp_sql = "CREATE TEMPORARY TABLE temp_table as SELECT * FROM accounts 
				WHERE hash = 'DEFAULT_JUDY_JANE_DOE'
				AND accounttype = 'PERSONAL'
				;";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	
	
	
	$tmp_sql = "UPDATE temp_table SET accountid = NULL;";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	
	
	$tmp_sql = "UPDATE temp_table SET hash = '". $new_account_personal_hash . "';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	
	
	
	$tmp_sql = "UPDATE temp_table SET whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	
	
	
	$tmp_sql = "UPDATE temp_table SET creator_memberid = '". $new_memberid ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	
	$tmp_sql = "UPDATE temp_table SET created = '". $KYC_DATETIME ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	$tmp_sql = "UPDATE temp_table SET updated = '". $KYC_DATETIME ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	
	$tmp_sql = "UPDATE temp_table SET template_company_hash = '". $_SESSION['template']['company']['hash'] ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	
	$tmp_sql = "UPDATE temp_table SET creator_member_hash = '". $new_member_hash ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	
	
	
	
	
	
	
	$tmp_sql = "INSERT INTO accounts SELECT * FROM temp_table;";
	logger3('tmp_sql', $tmp_sql);
	
	$results = updateTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	$tmp_sql = "DROP TABLE temp_table;";
	logger3('tmp_sql', $tmp_sql);
	
	$results = updateTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	$tmp_sql = "SELECT * FROM accounts WHERE hash = '". $new_account_personal_hash . "';";
	logger3('tmp_sql', $tmp_sql);
	
	$results = $tmp_new_personal_account_results = arrayTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	$new_personal_accountid = $tmp_new_personal_account_results[0]['accountid'];
	logger3('new_personal_accountid', $new_personal_accountid);
	
	
	
	### business #########################################################################
	
	$new_account_business_hash = hash_me();
	$tmp_sql = "CREATE TEMPORARY TABLE temp_table AS SELECT * FROM accounts 
				WHERE hash = 'DEFAULT_JUDY_JANE_DOE' 
				AND accounttype = 'BUSINESS'
				;";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	
	
	$tmp_sql = "UPDATE temp_table SET accountid = NULL;";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	
	
	$tmp_sql = "UPDATE temp_table SET hash = '". $new_account_business_hash . "';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	
	
	
	$tmp_sql = "UPDATE temp_table SET whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	
	
	$tmp_sql = "UPDATE temp_table SET creator_memberid = '". $new_memberid ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	
	
	# $tmp_sql = "UPDATE temp_table SET PAYYAP_application_status = 'SUBMITTED';";
	# logger3('tmp_sql', $tmp_sql);
	# $results = updateTHECASHIER($tmp_sql); 
	# logger3('results', $results);
	


	$tmp_sql = "UPDATE temp_table SET created = '". $KYC_DATETIME ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	
	
	$tmp_sql = "UPDATE temp_table SET updated = '". $KYC_DATETIME ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	
	
	
	$tmp_sql = "UPDATE temp_table SET template_company_hash = '". $_SESSION['template']['company']['hash'] ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	
	$tmp_sql = "UPDATE temp_table SET creator_member_hash = '". $new_member_hash ."';";
	logger3('tmp_sql', $tmp_sql);
	$results = updateTHECASHIER($tmp_sql); 
	logger3('results', $results);
	
	
	






	
	$tmp_sql = "INSERT INTO accounts 
				SELECT * FROM temp_table
				;";
	logger3('tmp_sql', $tmp_sql);
	
	$results = updateTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	$tmp_sql = "DROP TABLE temp_table;";
	logger3('tmp_sql', $tmp_sql);
	
	$results = updateTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	$tmp_sql = "SELECT * 
				FROM accounts 
				WHERE hash = '". $new_account_business_hash . "'
				;";
	logger3('tmp_sql', $tmp_sql);
	
	$results = $tmp_new_business_account_results = arrayTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	$new_business_accountid = $tmp_new_business_account_results[0]['accountid'];
	logger3('new_business_accountid', $new_business_accountid);












	
	
	
	#######################################################################################
	#######################################################################################
	### B!->ids_personal
	#######################################################################################
	#######################################################################################
	
	### selfie (1/1) ###  ###########################################
	
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_photo_id_filename = "";
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = "";
	$_XXXXX_business_accountid = "";
	$_XXXXX_status = "";
	$_XXXXX_document_key = "";
	$_XXXXX_document_description = "";
	$_XXXXX_id_number = "";
	$_XXXXX_firstname = "";
	$_XXXXX_lastname = "";
	$_XXXXX_middlename = "";
	$_XXXXX_birthdate = "";
	$_XXXXX_citizenship_iso3 = "";
	$_XXXXX_proof_of_residence_description = "";
	$_XXXXX_proof_of_residence_filename = "";
	$_XXXXX_residential_address_1 = "";
	$_XXXXX_residential_address_2 = "";
	$_XXXXX_residential_address_3 = "";
	$_XXXXX_residential_postal_code = "";
	$_XXXXX_residential_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_selfie_filename = "JUDY_JANE_DOE_SELFIE.jpg";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
		
		
	$tmp_sql = "INSERT INTO `ids_personal`
		(
		`idid`
		, `hash`
		, `photo_id_filename`
		, `member_hash`
		, `memberid`
		, `accountid`
		, `business_accountid`
		, `status`
		, `document_key`
		, `document_description`
		, `id_number`
		, `firstname`
		, `lastname`
		, `middlename`
		, `birthdate`
		, `citizenship_iso3`
		, `proof_of_residence_description`
		, `proof_of_residence_filename`
		, `residential_address_1`
		, `residential_address_2`
		, `residential_address_3`
		, `residential_postal_code`
		, `residential_country_iso3`
		, `ip`
		, `selfie_filename`
		, `datetime_id_submitted`
		, `datetime_created`
		, `datetime_updated`
		) VALUES (
		'". $_XXXXX_idid ."'
		,'". $_XXXXX_hash ."'
		,'". $_XXXXX_photo_id_filename ."'
		,'". $_XXXXX_member_hash ."'
		,'". $_XXXXX_memberid ."'
		,'". $_XXXXX_accountid ."'
		,'". $_XXXXX_business_accountid ."'
		,'". $_XXXXX_status ."'
		,'". $_XXXXX_document_key ."'
		,'". $_XXXXX_document_description ."'
		,'". $_XXXXX_id_number ."'
		,'". $_XXXXX_firstname ."'
		,'". $_XXXXX_lastname ."'
		,'". $_XXXXX_middlename ."'
		,'". $_XXXXX_birthdate ."'
		,'". $_XXXXX_citizenship_iso3 ."'
		,'". $_XXXXX_proof_of_residence_description ."'
		,'". $_XXXXX_proof_of_residence_filename ."'
		,'". $_XXXXX_residential_address_1 ."'
		,'". $_XXXXX_residential_address_2 ."'
		,'". $_XXXXX_residential_address_3 ."'
		,'". $_XXXXX_residential_postal_code ."'
		,'". $_XXXXX_residential_country_iso3 ."'
		,'". $_XXXXX_ip ."'
		,'". $_XXXXX_selfie_filename ."'
		,'". $_XXXXX_datetime_id_submitted ."'
		,'". $_XXXXX_datetime_created ."'
		,'". $_XXXXX_datetime_updated ."'
	);";
	logger3('tmp_sql', $tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	
	
	### photo id (1/2) ###  ###########################################
	
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_photo_id_filename = "";
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = "";
	$_XXXXX_business_accountid = "";
	$_XXXXX_status = "";
	$_XXXXX_document_key = "";
	$_XXXXX_document_description = "Driver%27s+License+of+Business+Owner";
	$_XXXXX_id_number = "";
	$_XXXXX_firstname = "";
	$_XXXXX_lastname = "";
	$_XXXXX_middlename = "";
	$_XXXXX_birthdate = "";
	$_XXXXX_citizenship_iso3 = "";
	$_XXXXX_proof_of_residence_description = "";
	$_XXXXX_proof_of_residence_filename = "";
	$_XXXXX_residential_address_1 = "";
	$_XXXXX_residential_address_2 = "";
	$_XXXXX_residential_address_3 = "";
	$_XXXXX_residential_postal_code = "";
	$_XXXXX_residential_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_selfie_filename = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
		
		
	$tmp_sql = "INSERT INTO `ids_personal`
		(
		`idid`
		, `hash`
		, `photo_id_filename`
		, `member_hash`
		, `memberid`
		, `accountid`
		, `business_accountid`
		, `status`
		, `document_key`
		, `document_description`
		, `id_number`
		, `firstname`
		, `lastname`
		, `middlename`
		, `birthdate`
		, `citizenship_iso3`
		, `proof_of_residence_description`
		, `proof_of_residence_filename`
		, `residential_address_1`
		, `residential_address_2`
		, `residential_address_3`
		, `residential_postal_code`
		, `residential_country_iso3`
		, `ip`
		, `selfie_filename`
		, `datetime_id_submitted`
		, `datetime_created`
		, `datetime_updated`
		) VALUES (
		'". $_XXXXX_idid ."'
		,'". $_XXXXX_hash ."'
		,'". $_XXXXX_photo_id_filename ."'
		,'". $_XXXXX_member_hash ."'
		,'". $_XXXXX_memberid ."'
		,'". $_XXXXX_accountid ."'
		,'". $_XXXXX_business_accountid ."'
		,'". $_XXXXX_status ."'
		,'". $_XXXXX_document_key ."'
		,'". $_XXXXX_document_description ."'
		,'". $_XXXXX_id_number ."'
		,'". $_XXXXX_firstname ."'
		,'". $_XXXXX_lastname ."'
		,'". $_XXXXX_middlename ."'
		,'". $_XXXXX_birthdate ."'
		,'". $_XXXXX_citizenship_iso3 ."'
		,'". $_XXXXX_proof_of_residence_description ."'
		,'". $_XXXXX_proof_of_residence_filename ."'
		,'". $_XXXXX_residential_address_1 ."'
		,'". $_XXXXX_residential_address_2 ."'
		,'". $_XXXXX_residential_address_3 ."'
		,'". $_XXXXX_residential_postal_code ."'
		,'". $_XXXXX_residential_country_iso3 ."'
		,'". $_XXXXX_ip ."'
		,'". $_XXXXX_selfie_filename ."'
		,'". $_XXXXX_datetime_id_submitted ."'
		,'". $_XXXXX_datetime_created ."'
		,'". $_XXXXX_datetime_updated ."'
	);";
	logger3('tmp_sql', $tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	
	### photo id (2/2) ###  ###########################################
	
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_photo_id_filename = "JUDY_JANE_DOE_DRIVERS_LICENSE.jpg";
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = "";
	$_XXXXX_business_accountid = "";
	$_XXXXX_status = "";
	$_XXXXX_document_key = "";
	$_XXXXX_document_description = "";
	$_XXXXX_id_number = "";
	$_XXXXX_firstname = "";
	$_XXXXX_lastname = "";
	$_XXXXX_middlename = "";
	$_XXXXX_birthdate = "";
	$_XXXXX_citizenship_iso3 = "";
	$_XXXXX_proof_of_residence_description = "";
	$_XXXXX_proof_of_residence_filename = "";
	$_XXXXX_residential_address_1 = "";
	$_XXXXX_residential_address_2 = "";
	$_XXXXX_residential_address_3 = "";
	$_XXXXX_residential_postal_code = "";
	$_XXXXX_residential_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_selfie_filename = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
		
		
	$tmp_sql = "INSERT INTO `ids_personal`
		(
		`idid`
		, `hash`
		, `photo_id_filename`
		, `member_hash`
		, `memberid`
		, `accountid`
		, `business_accountid`
		, `status`
		, `document_key`
		, `document_description`
		, `id_number`
		, `firstname`
		, `lastname`
		, `middlename`
		, `birthdate`
		, `citizenship_iso3`
		, `proof_of_residence_description`
		, `proof_of_residence_filename`
		, `residential_address_1`
		, `residential_address_2`
		, `residential_address_3`
		, `residential_postal_code`
		, `residential_country_iso3`
		, `ip`
		, `selfie_filename`
		, `datetime_id_submitted`
		, `datetime_created`
		, `datetime_updated`
		) VALUES (
		'". $_XXXXX_idid ."'
		,'". $_XXXXX_hash ."'
		,'". $_XXXXX_photo_id_filename ."'
		,'". $_XXXXX_member_hash ."'
		,'". $_XXXXX_memberid ."'
		,'". $_XXXXX_accountid ."'
		,'". $_XXXXX_business_accountid ."'
		,'". $_XXXXX_status ."'
		,'". $_XXXXX_document_key ."'
		,'". $_XXXXX_document_description ."'
		,'". $_XXXXX_id_number ."'
		,'". $_XXXXX_firstname ."'
		,'". $_XXXXX_lastname ."'
		,'". $_XXXXX_middlename ."'
		,'". $_XXXXX_birthdate ."'
		,'". $_XXXXX_citizenship_iso3 ."'
		,'". $_XXXXX_proof_of_residence_description ."'
		,'". $_XXXXX_proof_of_residence_filename ."'
		,'". $_XXXXX_residential_address_1 ."'
		,'". $_XXXXX_residential_address_2 ."'
		,'". $_XXXXX_residential_address_3 ."'
		,'". $_XXXXX_residential_postal_code ."'
		,'". $_XXXXX_residential_country_iso3 ."'
		,'". $_XXXXX_ip ."'
		,'". $_XXXXX_selfie_filename ."'
		,'". $_XXXXX_datetime_id_submitted ."'
		,'". $_XXXXX_datetime_created ."'
		,'". $_XXXXX_datetime_updated ."'
	);";
	logger3('tmp_sql', $tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	
	
	
	
	### proof of residence (1/1) ###  ###########################################
	
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_photo_id_filename = "";
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = "";
	$_XXXXX_business_accountid = "";
	$_XXXXX_status = "";
	$_XXXXX_document_key = "";
	$_XXXXX_document_description = "";
	$_XXXXX_id_number = "";
	$_XXXXX_firstname = "";
	$_XXXXX_lastname = "";
	$_XXXXX_middlename = "";
	$_XXXXX_birthdate = "";
	$_XXXXX_citizenship_iso3 = "";
	$_XXXXX_proof_of_residence_description = "Utility Bill";
	$_XXXXX_proof_of_residence_filename = "JUDY_JANE_DOE_PROOF_OF_RESIDENCE_1.jpg";
	$_XXXXX_residential_address_1 = "";
	$_XXXXX_residential_address_2 = "";
	$_XXXXX_residential_address_3 = "";
	$_XXXXX_residential_postal_code = "";
	$_XXXXX_residential_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_selfie_filename = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
		
		
	$tmp_sql = "INSERT INTO `ids_personal`
		(
		`idid`
		, `hash`
		, `photo_id_filename`
		, `member_hash`
		, `memberid`
		, `accountid`
		, `business_accountid`
		, `status`
		, `document_key`
		, `document_description`
		, `id_number`
		, `firstname`
		, `lastname`
		, `middlename`
		, `birthdate`
		, `citizenship_iso3`
		, `proof_of_residence_description`
		, `proof_of_residence_filename`
		, `residential_address_1`
		, `residential_address_2`
		, `residential_address_3`
		, `residential_postal_code`
		, `residential_country_iso3`
		, `ip`
		, `selfie_filename`
		, `datetime_id_submitted`
		, `datetime_created`
		, `datetime_updated`
		) VALUES (
		'". $_XXXXX_idid ."'
		,'". $_XXXXX_hash ."'
		,'". $_XXXXX_photo_id_filename ."'
		,'". $_XXXXX_member_hash ."'
		,'". $_XXXXX_memberid ."'
		,'". $_XXXXX_accountid ."'
		,'". $_XXXXX_business_accountid ."'
		,'". $_XXXXX_status ."'
		,'". $_XXXXX_document_key ."'
		,'". $_XXXXX_document_description ."'
		,'". $_XXXXX_id_number ."'
		,'". $_XXXXX_firstname ."'
		,'". $_XXXXX_lastname ."'
		,'". $_XXXXX_middlename ."'
		,'". $_XXXXX_birthdate ."'
		,'". $_XXXXX_citizenship_iso3 ."'
		,'". $_XXXXX_proof_of_residence_description ."'
		,'". $_XXXXX_proof_of_residence_filename ."'
		,'". $_XXXXX_residential_address_1 ."'
		,'". $_XXXXX_residential_address_2 ."'
		,'". $_XXXXX_residential_address_3 ."'
		,'". $_XXXXX_residential_postal_code ."'
		,'". $_XXXXX_residential_country_iso3 ."'
		,'". $_XXXXX_ip ."'
		,'". $_XXXXX_selfie_filename ."'
		,'". $_XXXXX_datetime_id_submitted ."'
		,'". $_XXXXX_datetime_created ."'
		,'". $_XXXXX_datetime_updated ."'
	);";
	logger3('tmp_sql', $tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	
	
	#######################################################################################
	#######################################################################################
	### B!->ids_business
	#######################################################################################
	#######################################################################################
		
	### proof of business description  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "Federal%20EIN%20%28TAX%20ID%29%20Registration%20Receipt";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "";
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);	
	
	
	
	### proof of business file  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "JUDY_JANE_DOE_PROOF_OF_BUSINESS_1.jpg";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "";
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	//exit;
	
	
	
	### proof of banking: description  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "Business+Bank+Account+Invoice+%2F+Statement";
	$_XXXXX_proof_of_pricing_filename = "";
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results[]', $results);	
	
	
	
	### proof of banking: filename (1/3)  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "JUDY_JANE_DOE_PROOF_OF_BANKING_1.jpg";
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);	
	
	
	### proof of banking: filename (2/3)  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "JUDY_JANE_DOE_PROOF_OF_BANKING_2.jpg";
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);
	
	
	### proof of banking: filename (3/3)  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "JUDY_JANE_DOE_PROOF_OF_BANKING_3.jpg";
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);	
	
	
	
	
	### proof of taxes: description  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "";
	
	
	
	$_XXXXX_proof_of_tax_returns_description = "1 YEAR of Tax Returns";
	$_XXXXX_proof_of_tax_returns_filename = "";
	$_XXXXX_proof_of_processing_description = "";
	$_XXXXX_proof_of_processing_filename = "";
	
	
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	
	
	, `proof_of_tax_returns_description`
	, `proof_of_tax_returns_filename`
	, `proof_of_processing_description`
	, `proof_of_processing_filename`
	
	
	
	
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	
	
	, '". $_XXXXX_proof_of_tax_returns_description . "'
	, '". $_XXXXX_proof_of_tax_returns_filename . "'
	, '". $_XXXXX_proof_of_processing_description . "'
	, '". $_XXXXX_proof_of_processing_filename . "'
	
	
	
	
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);	
	
	
	
	### proof of taxes: filename (1/2)  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "";
	
	
	
	$_XXXXX_proof_of_tax_returns_description = "";
	$_XXXXX_proof_of_tax_returns_filename = "JUDY_JANE_DOE_TAX_RETURN_1.jpg";
	$_XXXXX_proof_of_processing_description = "";
	$_XXXXX_proof_of_processing_filename = "";
	
	
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	
	
	, `proof_of_tax_returns_description`
	, `proof_of_tax_returns_filename`
	, `proof_of_processing_description`
	, `proof_of_processing_filename`
	
	
	
	
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	
	
	, '". $_XXXXX_proof_of_tax_returns_description . "'
	, '". $_XXXXX_proof_of_tax_returns_filename . "'
	, '". $_XXXXX_proof_of_processing_description . "'
	, '". $_XXXXX_proof_of_processing_filename . "'
	
	
	
	
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);	
	
	
	
	
	### proof of taxes: filename (2/2)  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "";
	
	
	
	$_XXXXX_proof_of_tax_returns_description = "";
	$_XXXXX_proof_of_tax_returns_filename = "JUDY_JANE_DOE_TAX_RETURN_2.jpg";
	$_XXXXX_proof_of_processing_description = "";
	$_XXXXX_proof_of_processing_filename = "";
	
	
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	
	
	, `proof_of_tax_returns_description`
	, `proof_of_tax_returns_filename`
	, `proof_of_processing_description`
	, `proof_of_processing_filename`
	
	
	
	
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	
	
	, '". $_XXXXX_proof_of_tax_returns_description . "'
	, '". $_XXXXX_proof_of_tax_returns_filename . "'
	, '". $_XXXXX_proof_of_processing_description . "'
	, '". $_XXXXX_proof_of_processing_filename . "'
	
	
	
	
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);	
	
	
	
	
	
	
	### proof of processing: description  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "";
	
	
	
	$_XXXXX_proof_of_tax_returns_description = "";
	$_XXXXX_proof_of_tax_returns_filename = "";
	$_XXXXX_proof_of_processing_description = "3 MONTHS of Previous Process Statements";
	$_XXXXX_proof_of_processing_filename = "";
	
	
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	
	
	, `proof_of_tax_returns_description`
	, `proof_of_tax_returns_filename`
	, `proof_of_processing_description`
	, `proof_of_processing_filename`
	
	
	
	
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	
	
	, '". $_XXXXX_proof_of_tax_returns_description . "'
	, '". $_XXXXX_proof_of_tax_returns_filename . "'
	, '". $_XXXXX_proof_of_processing_description . "'
	, '". $_XXXXX_proof_of_processing_filename . "'
	
	
	
	
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);	
	
	
	### proof of processing: filename (1/3)  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "";
	
	
	
	$_XXXXX_proof_of_tax_returns_description = "";
	$_XXXXX_proof_of_tax_returns_filename = "";
	$_XXXXX_proof_of_processing_description = "";
	$_XXXXX_proof_of_processing_filename = "JUDY_JANE_DOE_PROOF_OF_PROCESSING_1.jpg";
	
	
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	
	
	, `proof_of_tax_returns_description`
	, `proof_of_tax_returns_filename`
	, `proof_of_processing_description`
	, `proof_of_processing_filename`
	
	
	
	
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	
	
	, '". $_XXXXX_proof_of_tax_returns_description . "'
	, '". $_XXXXX_proof_of_tax_returns_filename . "'
	, '". $_XXXXX_proof_of_processing_description . "'
	, '". $_XXXXX_proof_of_processing_filename . "'
	
	
	
	
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results[]', $results);	
	
	
	### proof of processing: filename (2/3)  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "";
	
	
	
	$_XXXXX_proof_of_tax_returns_description = "";
	$_XXXXX_proof_of_tax_returns_filename = "";
	$_XXXXX_proof_of_processing_description = "";
	$_XXXXX_proof_of_processing_filename = "JUDY_JANE_DOE_PROOF_OF_PROCESSING_2.jpg";
	
	
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	
	
	, `proof_of_tax_returns_description`
	, `proof_of_tax_returns_filename`
	, `proof_of_processing_description`
	, `proof_of_processing_filename`
	
	
	
	
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	
	
	, '". $_XXXXX_proof_of_tax_returns_description . "'
	, '". $_XXXXX_proof_of_tax_returns_filename . "'
	, '". $_XXXXX_proof_of_processing_description . "'
	, '". $_XXXXX_proof_of_processing_filename . "'
	
	
	
	
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);	
	
	
	### proof of processing: filename (3/3)  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "";
	
	
	
	$_XXXXX_proof_of_tax_returns_description = "";
	$_XXXXX_proof_of_tax_returns_filename = "";
	$_XXXXX_proof_of_processing_description = "";
	$_XXXXX_proof_of_processing_filename = "JUDY_JANE_DOE_PROOF_OF_PROCESSING_3.jpg";
	
	
	
	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	
	
	, `proof_of_tax_returns_description`
	, `proof_of_tax_returns_filename`
	, `proof_of_processing_description`
	, `proof_of_processing_filename`
	
	
	
	
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	
	
	, '". $_XXXXX_proof_of_tax_returns_description . "'
	, '". $_XXXXX_proof_of_tax_returns_filename . "'
	, '". $_XXXXX_proof_of_processing_description . "'
	, '". $_XXXXX_proof_of_processing_filename . "'
	
	
	
	
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	logger3('results', $results);	
	
	
	
	
	
	### proof of processing: signature  ###########################################
	$_XXXXX_idid = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_business_certificate_filename = "";
	$_XXXXX_memberid = $new_memberid;
	$_XXXXX_accountid = $new_business_acountid;
	$_XXXXX_account_hash = $new_account_business_hash;
	$_XXXXX_member_hash = $new_member_hash;
	$_XXXXX_parent_account_hash = "";
	$_XXXXX_status = "SUBMITTED";
	$_XXXXX_document_description = "";

	$_XXXXX_proof_of_pricing_description = "";
	$_XXXXX_proof_of_pricing_filename = "";
	
	
	
	$_XXXXX_proof_of_tax_returns_description = "";
	$_XXXXX_proof_of_tax_returns_filename = "";
	$_XXXXX_proof_of_processing_description = "";
	$_XXXXX_proof_of_processing_filename = "";
	
	$_XXXXX_signature_filename = "JUDY_JANE_DOE_SIGNATURE_1.jpg";

	$_XXXXX_id_number = "";
	$_XXXXX_business_name = "";
	$_XXXXX_business_legal_extension = "";
	$_XXXXX_date_of_incorporation = "";
	$_XXXXX_proof_of_business_location_filename = "";
	$_XXXXX_business_address_1 = "";
	$_XXXXX_business_address_2 = "";
	$_XXXXX_business_address_3 = "";
	$_XXXXX_business_postal_code = "";
	$_XXXXX_business_country_iso3 = "";
	$_XXXXX_ip = "";
	$_XXXXX_datetime_id_submitted = $KYC_DATETIME;
	$_XXXXX_datetime_created = $KYC_DATETIME;
	$_XXXXX_datetime_updated = $KYC_DATETIME;
	
	
	$tmp_sql = "INSERT INTO `ids_business` (
	`idid`
	, `hash`
	, `business_certificate_filename`
	, `memberid`
	, `accountid`
	, `account_hash`
	, `member_hash`
	, `parent_account_hash`
	, `status`
	, `document_description`
	, `proof_of_pricing_description`
	, `proof_of_pricing_filename`
	
	
	, `proof_of_tax_returns_description`
	, `proof_of_tax_returns_filename`
	, `proof_of_processing_description`
	, `proof_of_processing_filename`
	
	
	, `signature_filename`
	
	
	
	
	, `id_number`
	, `business_name`
	, `business_legal_extension`
	, `date_of_incorporation`
	, `proof_of_business_location_filename`
	, `business_address_1`
	, `business_address_2`
	, `business_address_3`
	, `business_postal_code`
	, `business_country_iso3`
	, `ip`
	, `datetime_id_submitted`
	, `datetime_created`
	, `datetime_updated`
	) VALUES (
	'". $_XXXXX_idid . "'
	, '". $_XXXXX_hash . "'
	, '". $_XXXXX_business_certificate_filename . "'
	, '". $_XXXXX_memberid . "'
	, '". $_XXXXX_accountid . "'
	, '". $_XXXXX_account_hash . "'
	, '". $_XXXXX_member_hash . "'
	, '". $_XXXXX_parent_account_hash . "'
	, '". $_XXXXX_status . "'
	, '". $_XXXXX_document_description . "'
	, '". $_XXXXX_proof_of_pricing_description . "'
	, '". $_XXXXX_proof_of_pricing_filename . "'
	
	
	, '". $_XXXXX_proof_of_tax_returns_description . "'
	, '". $_XXXXX_proof_of_tax_returns_filename . "'
	, '". $_XXXXX_proof_of_processing_description . "'
	, '". $_XXXXX_proof_of_processing_filename . "'
	
	, '". $_XXXXX_signature_filename . "'
	
	
	, '". $_XXXXX_id_number . "'
	, '". $_XXXXX_business_name . "'
	, '". $_XXXXX_business_legal_extension . "'
	, '". $_XXXXX_date_of_incorporation . "'
	, '". $_XXXXX_proof_of_business_location_filename . "'
	, '". $_XXXXX_business_address_1 . "'
	, '". $_XXXXX_business_address_2 . "'
	, '". $_XXXXX_business_address_3 . "'
	, '". $_XXXXX_business_postal_code . "'
	, '". $_XXXXX_business_country_iso3 . "'
	, '". $_XXXXX_ip . "'
	, '". $_XXXXX_datetime_id_submitted . "'
	, '". $_XXXXX_datetime_created . "'
	, '". $_XXXXX_datetime_updated . "'
	);
	";

	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	
	logger3('results', $results);	


	

	/// ADD AN IP
	$_XXXX_ipid = "";
	$_XXXX_memberid = $new_memberid;
	$_XXXX_member_hash = $new_member_hash;
	$_XXXX_ip = $_SERVER['REMOTE_ADDR'];
	$_XXXX_city = "";
	$_XXXX_region = "";
	$_XXXX_country_name = "";
	$_XXXX_country_iso3 = "";
	$_XXXX_status = "";
	$_XXXX_sponsor_account_hash = "";
	//if(!$_XXXX_sponsor_account_hash) $_XXXX_sponsor_account_hash = $_COOKIE['tracking__hash'];
	$_XXXX_created = $KYC_DATETIME;
	$_XXXX_updated = $KYC_DATETIME;
	$_XXXXX_template_company_hash = $_SESSION['template']['company']['hash'];
	
	$tmp_sql = "INSERT INTO `ips`
				(
					`ipid`
					, `template_company_hash`
					, `memberid`
					, `member_hash`
					, `ip`
					, `city`
					, `region`
					, `country_name`
					, `country_iso3`
					, `status`
					, `sponsor_account_hash`
					, `created`
					, `updated`
				) VALUES (
					'". $_XXXX_ipid ."'
					,'". $_XXXXX_template_company_hash ."'
					,'". $_XXXX_memberid ."'
					,'". $_XXXX_member_hash ."'
					,'". $_XXXX_ip ."'
					,'". $_XXXX_city ."'
					,'". $_XXXX_region ."'
					,'". $_XXXX_country_name ."'
					,'". $_XXXX_country_iso3 ."'
					,'". $_XXXX_status ."'
					,'". $_XXXX_sponsor_account_hash ."'
					,'". $_XXXX_created ."'
					,'". $_XXXX_updated ."'
				)";
	logger3("tmp_sql",$tmp_sql);
	$nsert_results = insertTHECASHIER($tmp_sql);
	logger3("tmp_sql",$tmp_sql);






	return $results;
	

}



function intelitruth_force_update($device_type="",$app_version="",$whitelabel_business_account_hash="") {
	
	if(!$device_type) return $output['force_update'] = "NO";
	if(!$app_version) return $output['force_update'] = "NO";
	if(!$whitelabel_business_account_hash) return $output['force_update'] = "NO";
	
	
	$tmp_sql = "SELECT *
				FROM accounts
				WHERE hash = '". $whitelabel_business_account_hash ."'
				;";
	$account_details = readTHECASHIER($tmp_sql);
	
	
	
	$device_framework = "iOS";
	if( 
		(stristr($device_type,"mobile")) 
		|| (stristr($device_type,"tablet")) 
	) {
		$device_framework = "Android";
	}
	
	$tmp_output['force_update'] = "NO";
	$tmp_output['itunes_app_store_url'] = "";
	
	if(stristr($device_framework,"iOS")) {
		if($account_details->intelitruth_mobile_itunes_version > $app_version) {
			$tmp_output['force_update'] = "YES";
			$tmp_output['itunes_app_store_url'] = $account_details->itunes_app_store_url;	
		}
	}
	

	if(stristr($device_framework,"Android")) {
		if($account_details->intelitruth_mobile_android_version > $app_version) {
			$tmp_output['force_update'] = "YES";
			$tmp_output['itunes_app_store_url'] = $account_details->google_play_store_url;	
		}
	}	
	
	
	
	return $tmp_output;
	
	
	/*
	
	global $master_config_force_update_android;
	global $master_config_force_update_ios;
	
	$whitelabel_business_account_hash = ""; // will determine the APP LINKS (each whitelabel gets a unique iTUNES/ Android address)
	
	
	
	/// SET THE FRAMEWORK:
	$device_framework = "iOS";
	if( 
		(stristr($device_type,"mobile")) 
		|| (stristr($device_type,"tablet")) 
	) {
		$device_framework = "Android";
	}
	
	if(
		(
			(stristr($device_framework,"ANDROID"))
			&& ($app_version < $master_config_force_update_android)
		) || (
			(stristr($device_framework,"IOS"))
			&& ($app_version < $master_config_force_update_ios)
		)
	) {
	
		$output['force_update'] = "YES"; // default	
		
		if(stristr($device_framework,"iOS")) {
			
			$output['itunes_app_store_url'] = "https://itunes.apple.com/us/app/intelitruth-on-boarding/id1313602980?ls=1&mt=8";
		
		} else {
			
			$output['itunes_app_store_url'] = "https://play.google.com/store/apps/details?id=network.payyap.intelitruth.onboarding";
		}
		
	} else {
		
		$output['force_update'] = "NO"; // default	
	}
	
	*/
	
}









function intelitruth_set_moble_alerts($CRM_SMS_title="",$CRM_SMS_message="",$whitelabel_business_account_hash="",$member_hash="",$business_account_hash="") {
	
	if(!$CRM_SMS_title) return "Nooooooope";
	if(!$CRM_SMS_message) return "Nooooooope";
	
	if(!$whitelabel_business_account_hash) return "Nooooooope";
	if(!$member_hash) return "Nooooooope";
	if(!$business_account_hash) return "Nooooooope";
	
	
	
	$_XXXXX_mobile_alert_id = "";
	$_XXXXX_hash = hash_me();
	
	
	$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
	$_XXXXX_member_hash = $member_hash;
	$_XXXXX_business_account_hash = $business_account_hash;
	
	$_XXXXX_sms_title = addslashes($CRM_SMS_title);
	$_XXXXX_sms_message = addslashes($CRM_SMS_message);
	$_XXXXX_status = "PENDING";
	$_XXXXX_datetime_created = datetime_v2();
	$_XXXXX_datetime_updated = $_XXXXX_datetime_created;
					
	$tmp_sql = "INSERT INTO `CRM_mobile_alerts`
				(
					`mobile_alert_id`
					, `hash`
					
					, `whitelabel_business_account_hash`
					, `member_hash`
					, `business_account_hash`
					
					, `sms_title`
					, `sms_message`
					, `status`
					, `datetime_created`
					, `datetime_updated`
					) VALUES (
					'". $_XXXXX_mobile_alert_id ."'
					,'". $_XXXXX_hash ."'
					
					,'". $_XXXXX_whitelabel_business_account_hash ."'
					,'". $_XXXXX_member_hash ."'
					,'". $_XXXXX_business_account_hash ."'
					
					,'". $_XXXXX_sms_title ."'
					,'". $_XXXXX_sms_message ."'
					,'". $_XXXXX_status ."'
					,'". $_XXXXX_datetime_created ."'
					,'". $_XXXXX_datetime_updated ."'
	)";
	
	//test("tmp_sql",$tmp_sql);
	
	$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
	
	//test("insert_results",$insert_results);
	
	
	
}




function get_client_services($whitelabel_business_account_hash="") {
	
	##########################
	$tmp_sql = "SELECT status 
				FROM client_services 
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND client_service_name LIKE '%AGENT%'
				ORDER BY datetime DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	
	$client_services['agent'] = getTHECASHIER($tmp_sql,"intelitruth");
	if(!$client_services['agent']) $client_services['agent'] = "OFF";
	
	##########################
	$tmp_sql = "SELECT status 
				FROM client_services 
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND client_service_name LIKE '%API%'
				ORDER BY datetime DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	
	$client_services['api'] = getTHECASHIER($tmp_sql,"intelitruth");
	if(!$client_services['api']) $client_services['api'] = "OFF";
	
	
	##########################
	$tmp_sql = "SELECT status 
				FROM client_services 
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND client_service_name LIKE '%APPS%'
				ORDER BY datetime DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	
	$client_services['apps'] = getTHECASHIER($tmp_sql,"intelitruth");
	if(!$client_services['apps']) $client_services['apps'] = "OFF";
	
	
	
	//test("client_services",$client_services);
	
	return $client_services;
	
}


function get_client_service($whitelabel_business_account_hash,$service_name) {
	$tmp_sql = "SELECT status 
				FROM client_services 
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND client_service_name = '". $service_name ."'
				ORDER BY datetime DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	return $client_service = getTHECASHIER($tmp_sql,"intelitruth");
}


function get_ibm_watson_news($query="",$ibm_cloud_service_username="",$ibm_cloud_service_password="",$limit="",$filter_duplicates="",$natural_language_query="") {
	
	
	if(!$query) {
		return "ERROR";
	} else {
		$query = urlencode($query);
	}
	//test("query",$query);
	
	if(!$ibm_cloud_service_username) $ibm_cloud_service_username = "123";
	if(!$ibm_cloud_service_password) $ibm_cloud_service_password = "abc";
	
	//test("ibm_cloud_service_username",$ibm_cloud_service_username);
	//test("ibm_cloud_service_password",$ibm_cloud_service_password);
	
	
	
	
	
	if($_SESSION['sentireport']['ibm_watson_news']['username']) $ibm_cloud_service_username = $_SESSION['sentireport']['ibm_watson_news']['username'];
	if($_SESSION['sentireport']['ibm_watson_news']['password']) $ibm_cloud_service_password = $_SESSION['sentireport']['ibm_watson_news']['password'];
	

	
	
	
	
	if(!$limit) $limit = 40;
	
	if(!$filter_duplicates) $filter_duplicates = "true";
	
	
	$ibm_cloud_service_version = "2018-03-05";
	
	//test("ibm_cloud_service_version",$ibm_cloud_service_version);
	
	
	
	############################################################################################
	############################################################################################
	############################################################################################
	### IBM DISCOVERY NEWS (PREMIUM)
	## require_once("/BANGK!/_other/sentireport.com/gateway/sentireport_preferences.gate");
	
	### LIVE #########################################################
	
	$ibm_premium_service = TRUE;  // SET TO FALSE FOR "LITE" (FREE) SERVICE
	
	if($ibm_premium_service == TRUE) {
		
		### IBM DISOVERY NEWS (GEP : hayden.baillio@sentireport.com)
		$ibm_watson_discovery_news_PAID_PREMIUM_version = "2018-03-05";
		$ibm_watson_discovery_news_PAID_PREMIUM_username = "a0ab5281-c1a1-4078-bdcf-1c97fd6d7f5c";
		$ibm_watson_discovery_news_PAID_PREMIUM_password = "hyzbBpX3n07N";
		
		### IBM NATURAL LANGUAGE UNDERSTANDING (GEP : hayden.baillio@sentireport.com)
		$ibm_watson_natural_language_PAID_PREMIUM_version = "2018-03-16";
		$ibm_watson_natural_language_PAID_PREMIUM_username = "311e30e9-3f2b-434c-8e37-5287a479ed58"; // GEP
		$ibm_watson_natural_language_PAID_PREMIUM_password = "rqOCPEpcFemq";
		
		
		### INTELITRUTH:
		### IBM DISOVERY NEWS (GEP : _XXXX_@intelitruth.com)
		### IBM NATURAL LANGUAGE UNDERSTANDING (GEP : _XXXX_@intelitruth.com)
		
	
	}
	##################################################################

	if($ibm_premium_service == TRUE) {
		$ibm_cloud_service_version = $ibm_watson_discovery_news_PAID_PREMIUM_version;
		$ibm_cloud_service_username = $ibm_watson_discovery_news_PAID_PREMIUM_username;
		$ibm_cloud_service_password = $ibm_watson_discovery_news_PAID_PREMIUM_password;
	}
	############################################################################################
	############################################################################################
	############################################################################################	
	
	
	
	test("ibm_cloud_service_version",$ibm_cloud_service_version);
	test("ibm_cloud_service_username",$ibm_cloud_service_username);
	test("ibm_cloud_service_password",$ibm_cloud_service_password);
	
	
	
	
		
		
	
	//$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&deduplicate=false&highlight=true&passages.count=5&natural_language_query=".$query;
	
	//$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&aggregation=timeslice%28publication_date%2C1day%29&deduplicate=true&highlight=true&passages=true&passages.count=5&query=%28text%3A%22". $query ."%22%2Ctitle%3A%22". $query ."%22%29";
	
	//$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&aggregation=timeslice%28publication_date%2C1day%29&deduplicate=true&highlight=true&passages=true&passages.count=5&natural_language_query=". $query;
	
	//$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=". $discover_version ."&count=". $limit ."&deduplicate=". $filter_duplicates ."&highlight=true&passages=true&passages.count=5&query=text%3A%22". $query ."%22%7Ctitle%3A%22". $query ."%22";

	$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=". $ibm_cloud_service_version ."&count=". $limit ."&deduplicate=". $filter_duplicates ."&highlight=true&passages=true&passages.count=5&query=". $query;
	
	//$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=". $ibm_cloud_service_version ."&count=". $limit ."&deduplicate=". $filter_duplicates ."&highlight=true&query=". $query;
	
	
	
	
	
	
	if(
		(stristr($natural_language_query,"TRUE"))
		|| (stristr($natural_language_query,"natural"))
	) {
		$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=". $ibm_cloud_service_version ."&count=". $limit ."&deduplicate=". $filter_duplicates ."&highlight=true&passages=true&passages.count=5&natural_language_query=". $query;		
	}
	
	test("URL",$URL);
	

	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$URL);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
	curl_setopt($ch, CURLOPT_USERPWD, "$ibm_cloud_service_username:$ibm_cloud_service_password");
	
	$result = curl_exec ($ch);
	
	//test("result",$result);
	
	$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
	
	//test("status_code",$status_code);
	
	

	curl_close ($ch);

	return $result;
	
}









function get_ibm_watson_news_to_twitter($query="") {
	
	
/* 
SEEMS TO BE VALID FOR NATURAL LANGUAGE ONLY:
SAMPLE URL:
https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16
&features=emotion,sentiment
&return_analyzed_text=true
&clean=true
&fallback_to_raw=true
&concepts.limit=8
&emotion.document=true
&entities.limit=50
&entities.mentions=true
&entities.emotion=true
&entities.sentiment=true
&keywords.limit=50
&keywords.emotion=true
&keywords.sentiment=true
&relations.model=en-news
&semantic_roles.limit=50
&semantic_roles.entities=true
&semantic_roles.keywords=true
&sentiment.document=true
*/



$parameters = "";
$parameters .= "&features=emotion,sentiment";
$parameters .= "&return_analyzed_text=true";
$parameters .= "&emotion.document=true";
$parameters .= "&entities.emotion=true";
$parameters .= "&entities.sentiment=true";
$parameters .= "&keywords.emotion=true";
$parameters .= "&keywords.sentiment=true";
$parameters .= "&semantic_roles.entities=true";
$parameters .= "&semantic_roles.keywords=true";
$parameters .= "&sentiment.document=true";
$parameters .= "";
$parameters .= "";
$parameters .= "";
$parameters .= "";
//$parameters = "";


	
	
	logger3("get_ibm_watson_news_to_twitter(query)",$query);



	
	if(!$query) {
		return "ERROR";
	} else {
		$query = urlencode($query);
	}
	//test("query",$query);
	
	if(!$ibm_cloud_service_username) $ibm_cloud_service_username = "123";
	if(!$ibm_cloud_service_password) $ibm_cloud_service_password = "abc";
	
	//test("ibm_cloud_service_username",$ibm_cloud_service_username);
	//test("ibm_cloud_service_password",$ibm_cloud_service_password);
	
	
	
	
	
	if($_SESSION['sentireport']['ibm_watson_news']['username']) $ibm_cloud_service_username = $_SESSION['sentireport']['ibm_watson_news']['username'];
	if($_SESSION['sentireport']['ibm_watson_news']['password']) $ibm_cloud_service_password = $_SESSION['sentireport']['ibm_watson_news']['password'];
	

	
	
	
	
	if(!$limit) $limit = 50; // max is 50 unless you use "offset" for multiple searches of multiple results
	
	if(!$filter_duplicates) $filter_duplicates = "true";
	
	
	$ibm_cloud_service_version = "2018-03-05";
	
	
	
	############################################################################################
	############################################################################################
	### IBM DISCOVERY NEWS (PREMIUM)
	require_once("/BANGK!/_other/sentireport.com/gateway/sentireport_preferences.gate");
	//if($ibm_premium_service) $_SESSION['sentireport']['ibm_watson_news']['ibm_premium_service'] = $ibm_premium_service;
	if($ibm_premium_service == TRUE) {
		$_SESSION['sentireport']['ibm_watson_news']['version'] = $ibm_watson_discovery_news_PAID_PREMIUM_version;
		$_SESSION['sentireport']['ibm_watson_news']['username'] = $ibm_watson_discovery_news_PAID_PREMIUM_username;
		$_SESSION['sentireport']['ibm_watson_news']['password'] = $ibm_watson_discovery_news_PAID_PREMIUM_password;
	
	}
	
	############################################################################################
	############################################################################################	
		
	if($_SESSION['sentireport']['ibm_watson_news']['version']) $ibm_cloud_service_username = $_SESSION['sentireport']['ibm_watson_news']['version'];	
	if($_SESSION['sentireport']['ibm_watson_news']['username']) $ibm_cloud_service_username = $_SESSION['sentireport']['ibm_watson_news']['username'];
	if($_SESSION['sentireport']['ibm_watson_news']['password']) $ibm_cloud_service_password = $_SESSION['sentireport']['ibm_watson_news']['password'];
	

		
		
		
		
	
	//$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&deduplicate=false&highlight=true&passages.count=5&natural_language_query=".$query;
	
	//$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&aggregation=timeslice%28publication_date%2C1day%29&deduplicate=true&highlight=true&passages=true&passages.count=5&query=%28text%3A%22". $query ."%22%2Ctitle%3A%22". $query ."%22%29";
	
	//$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&aggregation=timeslice%28publication_date%2C1day%29&deduplicate=true&highlight=true&passages=true&passages.count=5&natural_language_query=". $query;
	
	//$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=". $discover_version ."&count=". $limit ."&deduplicate=". $filter_duplicates ."&highlight=true&passages=true&passages.count=5&query=text%3A%22". $query ."%22%7Ctitle%3A%22". $query ."%22";

	$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=". $ibm_cloud_service_version . $parameters ."&count=". $limit ."&deduplicate=". $filter_duplicates ."&highlight=true&passages=true&passages.count=5&query=". $query;
	
	
	
	
	
	if(
		(stristr($natural_language_query,"TRUE"))
		|| (stristr($natural_language_query,"natural"))
	) {
		$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=". $ibm_cloud_service_version ."&features=". $FEATURES ."&count=". $limit ."&deduplicate=". $filter_duplicates ."&highlight=true&passages=true&passages.count=5&natural_language_query=". $query;		
	}
	
	
	if(!$_XXXXX_DISPLAY) global $_XXXXX_DISPLAY;
	if(!stristr($_XXXXX_DISPLAY,"DEMO")) {
	if(
		(
			(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
			|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
			|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
		) && (!stristr($_SERVER['REQUEST_URI'],"AIINHR"))
	) {
		logger3("get_ibm_watson_news_to_twitter(0-URL)",$URL);
	}
	}
	
	logger3("get_ibm_watson_news_to_twitter(00-URL)",$URL);
	
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$URL);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
	curl_setopt($ch, CURLOPT_USERPWD, "$ibm_cloud_service_username:$ibm_cloud_service_password");
	$result=curl_exec ($ch);
	$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
	
	if(!$_XXXXX_DISPLAY) global $_XXXXX_DISPLAY;
	if(!stristr($_XXXXX_DISPLAY,"DEMO")) {
	if(
		(
			(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
			|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
			|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
		) && (!stristr($_SERVER['REQUEST_URI'],"AIINHR"))
	) {
		test("status_code",$status_code);
	}
	}
	
	
	curl_close ($ch);

	return $result;
	
}






function get_ibm_watson_natural_language($text_or_url="",$ibm_cloud_service_username="",$ibm_cloud_service_password="",$ibm_cloud_service_version="",$source="url") {
	
	
	
	//test("ibm_cloud_service_version",$ibm_cloud_service_version);
	

	
	
		
	
	if(!$ibm_watson_natural_language_version) global $ibm_watson_natural_language_version;
	if(!$ibm_watson_natural_language_username) global $ibm_watson_natural_language_username;
	if(!$ibm_watson_natural_language_password) global $ibm_watson_natural_language_password;
	
	
	
	if(!$source) $source = "url";
	if(!$ibm_cloud_service_version) $ibm_cloud_service_version = $ibm_watson_natural_language_version;
	if(!$ibm_cloud_service_username) $ibm_cloud_service_username = $ibm_watson_natural_language_username;
	if(!$ibm_cloud_service_password) $ibm_cloud_service_password = $ibm_watson_natural_language_password;
	
	
	if($_SESSION['sentireport']['ibm_natural_language']['service_username']) $ibm_cloud_service_username = $_SESSION['sentireport']['ibm_natural_language']['service_username'];
	if($_SESSION['sentireport']['ibm_natural_language']['service_password']) $ibm_cloud_service_password = $_SESSION['sentireport']['ibm_natural_language']['service_password'];
	
	

	
	if( (!$ibm_cloud_service_username) || (!$ibm_cloud_service_password) ) {
		
		############################################################################################
		############################################################################################
		### IBM NATURAL LANGUAGE UNDERSTANDING (PREMIUM)
		require_once("/BANGK!/_other/sentireport.com/gateway/sentireport_preferences.gate");
		if($ibm_premium_service == TRUE) {
			$ibm_cloud_service_version = $ibm_watson_natural_language_PAID_PREMIUM_version;
			$ibm_cloud_service_username = $ibm_watson_natural_language_PAID_PREMIUM_username;
			$ibm_cloud_service_password = $ibm_watson_natural_language_PAID_PREMIUM_password;
		}
		############################################################################################
		############################################################################################	
	}
	
	
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("ibm_cloud_service_version",$ibm_cloud_service_version);
	}
	
		if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("ibm_cloud_service_username",$ibm_cloud_service_username);
	}
	
		if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("ibm_cloud_service_password",$ibm_cloud_service_password);
	}
	
	
	
	
	if(!$text_or_url) {
		return "ERROR";
	} else {
		//$text_or_url = urlencode($text_or_url);
	}
	//test("query",$query);
	

	$watson_string = "";
	
	if(stristr($source,"url")) {
		$watson_string = "url=" . urlencode($text_or_url);
	} else {
		$watson_string = "text=" . urlencode($text_or_url);
	}
	
	$watson_string .= "&features=entities,sentiment";
	$watson_string .= "&return_analyzed_text=true";
	$watson_string .= "&clean=true";
	$watson_string .= "&fallback_to_raw=true";
	$watson_string .= "&concepts.limit=8";
	$watson_string .= "&emotion.document=false";
	$watson_string .= "&entities.limit=50";
	$watson_string .= "&entities.mentions=false";
	$watson_string .= "&entities.emotion=false";
	$watson_string .= "&entities.sentiment=true";
	$watson_string .= "&keywords.limit=50";
	$watson_string .= "&keywords.emotion=false";
	$watson_string .= "&keywords.sentiment=false";
	$watson_string .= "&relations.model=en-news";
	$watson_string .= "&semantic_roles.limit=50";
	$watson_string .= "&semantic_roles.entities=false";
	$watson_string .= "&semantic_roles.keywords=false";
	$watson_string .= "&sentiment.document=true";
	
	
	//test("watson_string",$watson_string);
	
	
	
	
	# ############################################################################################
	# ############################################################################################
	# ### IBM NATURAL LANGUAGE UNDERSTANDING (PREMIUM)
	# require_once("/BANGK!/_other/sentireport.com/gateway/sentireport_preferences.gate");
	# if($ibm_premium_service == TRUE) {
	# 	$ibm_cloud_service_version = $ibm_watson_natural_language_PAID_PREMIUM_version;
	# 	$ibm_cloud_service_username = $ibm_watson_natural_language_PAID_PREMIUM_username;
	# 	$ibm_cloud_service_password = $ibm_watson_natural_language_PAID_PREMIUM_password;
	# }
	# ############################################################################################
	# ############################################################################################	
		
		
	
	
	
	
	
	# //$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&deduplicate=false&highlight=true&passages.count=5&natural_language_query=".$query;
	# 
	# //$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&aggregation=timeslice%28publication_date%2C1day%29&deduplicate=true&highlight=true&passages=true&passages.count=5&query=%28text%3A%22". $query ."%22%2Ctitle%3A%22". $query ."%22%29";
	# 
	# //$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&aggregation=timeslice%28publication_date%2C1day%29&deduplicate=true&highlight=true&passages=true&passages.count=5&natural_language_query=". $query;
	# 
	# $URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&deduplicate=true&highlight=true&passages=true&passages.count=5&query=text%3A%22". $query ."%22%7Ctitle%3A%22". $query ."%22";
	
	$URL = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=". $ibm_cloud_service_version ."&" . $watson_string;
	
	//test("URL",$URL);
	
	//test("ibm_cloud_service_username",$ibm_cloud_service_username);
	//test("ibm_cloud_service_password",$ibm_cloud_service_password);
	
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$URL);
	curl_setopt($ch, CURLOPT_INTERFACE,'74.81.189.10');
	curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	
	curl_setopt($ch, CURLOPT_USERPWD, "$ibm_cloud_service_username:$ibm_cloud_service_password");
	$result=curl_exec ($ch);
	$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
	curl_close ($ch);
	
	
	
	
	return $result;
	
}






function get_ibm_watson_natural_language_v2($text_or_url="",$ibm_cloud_service_username="",$ibm_cloud_service_password="",$ibm_cloud_service_version="",$source="") {
	
	
	if(!$text_or_url) return FALSE;
	if(!$source) return FALSE;
	
	//test("ibm_cloud_service_version",$ibm_cloud_service_version);
	

	
	
		
	
	if(!$ibm_watson_natural_language_version) global $ibm_watson_natural_language_version;
	if(!$ibm_watson_natural_language_username) global $ibm_watson_natural_language_username;
	if(!$ibm_watson_natural_language_password) global $ibm_watson_natural_language_password;
	
	
	
	if(!$source) $source = "url";
	if(!$ibm_cloud_service_version) $ibm_cloud_service_version = $ibm_watson_natural_language_version;
	if(!$ibm_cloud_service_username) $ibm_cloud_service_username = $ibm_watson_natural_language_username;
	if(!$ibm_cloud_service_password) $ibm_cloud_service_password = $ibm_watson_natural_language_password;
	
	
	if($_SESSION['sentireport']['ibm_natural_language']['service_username']) $ibm_cloud_service_username = $_SESSION['sentireport']['ibm_natural_language']['service_username'];
	if($_SESSION['sentireport']['ibm_natural_language']['service_password']) $ibm_cloud_service_password = $_SESSION['sentireport']['ibm_natural_language']['service_password'];
	
	

	
	if( (!$ibm_cloud_service_username) || (!$ibm_cloud_service_password) ) {
		
		############################################################################################
		############################################################################################
		### IBM NATURAL LANGUAGE UNDERSTANDING (PREMIUM)
		require_once("/BANGK!/_other/sentireport.com/gateway/sentireport_preferences.gate");
		if($ibm_premium_service == TRUE) {
			$ibm_cloud_service_version = $ibm_watson_natural_language_PAID_PREMIUM_version;
			$ibm_cloud_service_username = $ibm_watson_natural_language_PAID_PREMIUM_username;
			$ibm_cloud_service_password = $ibm_watson_natural_language_PAID_PREMIUM_password;
		}
		############################################################################################
		############################################################################################	
	}
	
	
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("ibm_cloud_service_version",$ibm_cloud_service_version);
	}
	
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("ibm_cloud_service_username",$ibm_cloud_service_username);
	}
	
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("ibm_cloud_service_password",$ibm_cloud_service_password);
	}
	
	


	$watson_string = "";
	
	if(stristr($source,"url")) {
		$watson_string = "url=" . urlencode($text_or_url);
	} else {
		$watson_string = "text=" . urlencode($text_or_url);
	}
	
	$watson_string .= "&features=entities,sentiment";
	$watson_string .= "&return_analyzed_text=true";
	$watson_string .= "&clean=true";
	$watson_string .= "&fallback_to_raw=true";
	$watson_string .= "&concepts.limit=8";
	$watson_string .= "&emotion.document=false";
	$watson_string .= "&entities.limit=50";
	$watson_string .= "&entities.mentions=false";
	$watson_string .= "&entities.emotion=false";
	$watson_string .= "&entities.sentiment=true";
	$watson_string .= "&keywords.limit=50";
	$watson_string .= "&keywords.emotion=false";
	$watson_string .= "&keywords.sentiment=false";
	$watson_string .= "&relations.model=en-news";
	$watson_string .= "&semantic_roles.limit=50";
	$watson_string .= "&semantic_roles.entities=false";
	$watson_string .= "&semantic_roles.keywords=false";
	$watson_string .= "&sentiment.document=true";
	
	
	//test("watson_string",$watson_string);
	
	
	
	
	# ############################################################################################
	# ############################################################################################
	# ### IBM NATURAL LANGUAGE UNDERSTANDING (PREMIUM)
	# require_once("/BANGK!/_other/sentireport.com/gateway/sentireport_preferences.gate");
	# if($ibm_premium_service == TRUE) {
	# 	$ibm_cloud_service_version = $ibm_watson_natural_language_PAID_PREMIUM_version;
	# 	$ibm_cloud_service_username = $ibm_watson_natural_language_PAID_PREMIUM_username;
	# 	$ibm_cloud_service_password = $ibm_watson_natural_language_PAID_PREMIUM_password;
	# }
	# ############################################################################################
	# ############################################################################################	
		
		
	
	
	
	
	
	# //$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&deduplicate=false&highlight=true&passages.count=5&natural_language_query=".$query;
	# 
	# //$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&aggregation=timeslice%28publication_date%2C1day%29&deduplicate=true&highlight=true&passages=true&passages.count=5&query=%28text%3A%22". $query ."%22%2Ctitle%3A%22". $query ."%22%29";
	# 
	# //$URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&aggregation=timeslice%28publication_date%2C1day%29&deduplicate=true&highlight=true&passages=true&passages.count=5&natural_language_query=". $query;
	# 
	# $URL = "https://gateway.watsonplatform.net/discovery/api/v1/environments/system/collections/news-en/query?version=2017-11-07&count=50&deduplicate=true&highlight=true&passages=true&passages.count=5&query=text%3A%22". $query ."%22%7Ctitle%3A%22". $query ."%22";
	
	$URL = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=". $ibm_cloud_service_version ."&" . $watson_string;
	
	

	$FEATURES = "sentiment,relations,categories,concepts,emotion,entities,keywords,semantic_roles,metadata";
	$FEATURES = "sentiment,relations,categories,concepts,emotion,entities,keywords,semantic_roles";
	$URL = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=". $ibm_cloud_service_version ."&". $source . "=" . $text_or_url . "&features=" . $FEATURES;
	
	
	
	if(!$_XXXXX_DISPLAY) global $_XXXXX_DISPLAY;
	if(!stristr($_XXXXX_DISPLAY,"DEMO")) {
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		
		test("URL",$URL);
	}
	}
	
	//test("ibm_cloud_service_username",$ibm_cloud_service_username);
	//test("ibm_cloud_service_password",$ibm_cloud_service_password);
	
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$URL);
	curl_setopt($ch, CURLOPT_INTERFACE,'74.81.189.10');
	curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	
	curl_setopt($ch, CURLOPT_USERPWD, "$ibm_cloud_service_username:$ibm_cloud_service_password");
	$result=curl_exec ($ch);
	$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
	curl_close ($ch);
	
	
	
	
	return $result;
	
}











function get_ibm_watson_news_from_database($phrase="") {
	
	$tmp_sql = "SELECT * 
				FROM api_search_engine_results
				WHERE api_service_name = 'ibm_watson_news'
				AND status = 'COMPLETE'
				AND search_term = '".$phrase."'
				ORDER BY datetime_created DESC
				;";
	
	//test("tmp_sql",$tmp_sql);
	
	//$watson_news_results = readTHECASHIER($tmp_sql,"intelitruth");
	
	//test("watson_news_results",$watson_news_results);	
	
	
	
	if($watson_news_results) {
	
		$watson_news_results = unserialize($watson_news_results);
		
		$watson_news_results = json_decode($watson_news_results);
		
		return object_to_array_v2($watson_news_results);
	
	} else {
		
		$watson_news_results = get_ibm_watson_news($query=$phrase,$ibm_cloud_service_username="",$ibm_cloud_service_password="");
		
		/*
		$_XXXXX_search_results_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXXX_whitelabel_business_account_hash = "";
		$_XXXXX_member_hash = "";
		$_XXXXX_api_service_name = "ibm_watson_news";
		$_XXXXX_business_url = "";
		$_XXXXX_search_term = addslashes($phrase);
		$_XXXXX_serialized_search_results = serialize($watson_news_results);
		$_XXXXX_serialized_search_results = addslashes($_XXXXX_serialized_search_results);
		$_XXXXX_risk_score = "";
		$_XXXXX_status = "COMPLETE";
		$_XXXXX_datetime_created = datetime_v2();
						
						
		$tmp_sql = 'INSERT INTO `api_search_engine_results`
					(
						`search_results_id`
						, `hash`
						, `whitelabel_business_account_hash`
						, `member_hash`
						, `api_service_name`
						, `business_url`
						, `search_term`
						, `serialized_search_results`
						, `risk_score`
						, `status`
						, `datetime_created`
					) VALUES (
						"'. $_XXXXX_search_results_id .'"
						,"'. $_XXXXX_hash .'"
						,"'. $_XXXXX_whitelabel_business_account_hash .'"
						,"'. $_XXXXX_member_hash .'"
						,"'. $_XXXXX_api_service_name .'"
						,"'. $_XXXXX_business_url .'"
						,"'. $_XXXXX_search_term .'"
						,"'. $_XXXXX_serialized_search_results .'"
						,"'. $_XXXXX_risk_score .'"
						,"'. $_XXXXX_status .'"
						,"'. $_XXXXX_datetime_created .'"
					)';
		
		test("tmp_sql",$tmp_sql);
		
		$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
		
		test("insert_results",$insert_results);
		
		*/
		
		$watson_news_results = json_decode($watson_news_results);
		
		return object_to_array_v2($watson_news_results);
		
		
	}
	
}


function create_new_intelitruth_preferences_profile($_XXXXX_whitelabel_business_account_hash,$incoming_preferences_profile) {
			
	
	if(!$incoming_preferences_profile) $incoming_preferences_profile = "DEFAULT";
	
	$tmp_sql = "SELECT hash 
				FROM onboarding_preferences
				WHERE form_name = '". addslashes($incoming_preferences_profile) ."'
				AND whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
				ORDER BY datetime_created ASC
				LIMIT 1
				;";
	$existing_profile_hash = $default_profile_exists = getTHECASHIER($tmp_sql,"intelitruth");
	
	if($existing_profile_hash) {  /// GET THE EXISTSING DATA
		
		# //$_XXXXX_whitelabel_business_account_hash = $incoming_vars['whitelabel_business_account_hash'];
		# $tmp_sql = "INSERT INTO `onboarding_preferences`
		# 			(`hash`, `whitelabel_business_account_hash`, `form_type`, `form_name`, `tier`, `onboarding_account_registration_validation_email`, `onboarding_account_registration_validation_sms`, `onboarding_your_region`, `onboarding_business_category`, `onboarding_business_description`, `onboarding_business_key_words`, `onboarding_years_doing_business`, `onboarding_business_accept_credit_card`, `onboarding_average_transaction_value`, `onboarding_first_name`, `onboarding_last_name`, `onboarding_personal_emailaddress`, `onboarding_personal_telephone_number`, `onboarding_personal_street_address`, `onboarding_personal_postal_code`, `onboarding_personal_birthdate`, `onboarding_personal_social_security_number`, `onboarding_business_name`, `onboarding_business_telephone_number`, `onboarding_business_emailaddress`, `onboarding_business_url_homepage`, `onboarding_business_public_directory`, `onboarding_postfix`, `onboarding_business_type`, `onboarding_business_registered_region`, `onboarding_business_EIN`, `onboarding_business_EIN_FAQ`, `onboarding_legal_tickbox_alert_terms_of_service`, `onboarding_legal_tickbox_alert_refund_policy`, `onboarding_legal_tickbox_alert_privacy_policy`, `onboarding_identity_selfie`, `onboarding_identity_photo_id`, `onboarding_identity_photo_id_title`, `onboarding_identity_photo_id_options`, `onboarding_identity_residence`, `onboarding_identity_residence_title`, `onboarding_identity_residence_options`, `onboarding_identity_business`, `onboarding_identity_business_title`, `onboarding_identity_business_options`, `onboarding_identity_banking`, `onboarding_identity_banking_title`, `onboarding_identity_banking_options`, `onboarding_identity_tax_returns`, `onboarding_identity_tax_returns_title`, `onboarding_identity_tax_returns_options`, `onboarding_identity_processing`, `onboarding_identity_processing_title`, `onboarding_identity_processing_options`, `onboarding_owner_signature`, `onboarding_terms_of_service_url`, `onboarding_terms_of_service_text`, `onboarding_whitelabel_business_emailaddress_agents`, `onboarding_whitelabel_business_emailaddress_support`, `onboarding_whitelabel_business_emailaddress_underwriting`, `onboarding_whitelabel_business_account_hostname`, `MATCH_ AcquirerId`, `onboarding_kyc_search_personal_name`, `onboarding_kyc_search_personal_location`, `onboarding_kyc_search_business_name`, `onboarding_kyc_search_business_location`, `onboarding_kyc_search_business_url`, `onboarding_aml_ofac_sdn`, `onboarding_aml_ofac_consolidated`, `onboarding_aml_fbi`, `onboarding_aml_dea`, `onboarding_aml_interpol`, `onboarding_aml_ncmec`, `CRM_followup_STAGE_1_EMAIL_1_subject`, `CRM_followup_STAGE_1_EMAIL_1_body`, `CRM_followup_STAGE_1_EMAIL_2_subject`, `CRM_followup_STAGE_1_EMAIL_2_body`, `CRM_followup_STAGE_1_EMAIL_3_subject`, `CRM_followup_STAGE_1_EMAIL_3_body`, `CRM_followup_STAGE_1_EMAIL_4_subject`, `CRM_followup_STAGE_1_EMAIL_4_body`, `CRM_followup_STAGE_2_EMAIL_1_subject`, `CRM_followup_STAGE_2_EMAIL_1_body`, `CRM_followup_STAGE_2_EMAIL_2_subject`, `CRM_followup_STAGE_2_EMAIL_2_body`, `CRM_followup_STAGE_2_EMAIL_3_subject`, `CRM_followup_STAGE_2_EMAIL_3_body`, `CRM_followup_STAGE_2_EMAIL_4_subject`, `CRM_followup_STAGE_2_EMAIL_4_body`, `CRM_followup_STAGE_3_EMAIL_1_subject`, `CRM_followup_STAGE_3_EMAIL_1_body`, `CRM_followup_STAGE_3_EMAIL_2_subject`, `CRM_followup_STAGE_3_EMAIL_2_body`, `CRM_followup_STAGE_3_EMAIL_3_subject`, `CRM_followup_STAGE_3_EMAIL_3_body`, `CRM_followup_STAGE_3_EMAIL_4_subject`, `CRM_followup_STAGE_3_EMAIL_4_body`, `CRM_followup_STAGE_4_EMAIL_1_subject`, `CRM_followup_STAGE_4_EMAIL_1_body`, `CRM_followup_STAGE_4_EMAIL_2_subject`, `CRM_followup_STAGE_4_EMAIL_2_body`, `CRM_followup_STAGE_4_EMAIL_3_subject`, `CRM_followup_STAGE_4_EMAIL_3_body`, `CRM_followup_STAGE_4_EMAIL_4_subject`, `CRM_followup_STAGE_4_EMAIL_4_body`, `CRM_followup_STAGE_5_EMAIL_1_subject`, `CRM_followup_STAGE_5_EMAIL_1_body`, `CRM_followup_STAGE_5_EMAIL_2_subject`, `CRM_followup_STAGE_5_EMAIL_2_body`, `CRM_followup_STAGE_5_EMAIL_3_subject`, `CRM_followup_STAGE_5_EMAIL_3_body`, `CRM_followup_STAGE_5_EMAIL_4_subject`, `CRM_followup_STAGE_5_EMAIL_4_body`, `CRM_followup_STAGE_6_EMAIL_1_subject`, `CRM_followup_STAGE_6_EMAIL_1_body`, `CRM_followup_STAGE_6_EMAIL_2_subject`, `CRM_followup_STAGE_6_EMAIL_2_body`, `CRM_followup_STAGE_6_EMAIL_3_subject`, `CRM_followup_STAGE_6_EMAIL_3_body`, `CRM_followup_STAGE_6_EMAIL_4_subject`, `CRM_followup_STAGE_6_EMAIL_4_body`, `CRM_followup_STAGE_7_EMAIL_1_subject`, `CRM_followup_STAGE_7_EMAIL_1_body`, `CRM_followup_STAGE_7_EMAIL_2_subject`, `CRM_followup_STAGE_7_EMAIL_2_body`, `CRM_followup_STAGE_7_EMAIL_3_subject`, `CRM_followup_STAGE_7_EMAIL_3_body`, `CRM_followup_STAGE_7_EMAIL_4_subject`, `CRM_followup_STAGE_7_EMAIL_4_body`, `CRM_followup_STAGE_8_EMAIL_1_subject`, `CRM_followup_STAGE_8_EMAIL_1_body`, `CRM_followup_STAGE_8_EMAIL_2_subject`, `CRM_followup_STAGE_8_EMAIL_2_body`, `CRM_followup_STAGE_8_EMAIL_3_subject`, `CRM_followup_STAGE_8_EMAIL_3_body`, `CRM_followup_STAGE_8_EMAIL_4_subject`, `CRM_followup_STAGE_8_EMAIL_4_body`, `login_screen_footer_image_full_url_or_simple_text`, `onboarding_account_registration_process`, `form_type_display_queue`, `more_personal_documents_1`, `more_personal_documents_2`, `more_personal_documents_3`, `more_personal_documents_4`, `more_personal_documents_5`, `more_personal_documents_6`, `more_personal_documents_7`, `more_personal_documents_8`, `more_personal_documents_9`, `more_personal_documents_10`, `more_business_documents_1`, `more_business_documents_2`, `more_business_documents_3`, `more_business_documents_4`, `more_business_documents_5`, `more_business_documents_6`, `more_business_documents_7`, `more_business_documents_8`, `more_business_documents_9`, `more_business_documents_10`, `more_signatures_1`, `more_signatures_2`, `more_signatures_3`, `more_signatures_4`, `more_signatures_5`, `more_signatures_6`, `more_signatures_7`, `more_signatures_8`, `more_signatures_9`, `more_signatures_10`, `datetime_created`, `datetime_updated`)
		# 
		# 			SELECT `hash`, `whitelabel_business_account_hash`, `form_type`, `form_name`, `tier`, `onboarding_account_registration_validation_email`, `onboarding_account_registration_validation_sms`, `onboarding_your_region`, `onboarding_business_category`, `onboarding_business_description`, `onboarding_business_key_words`, `onboarding_years_doing_business`, `onboarding_business_accept_credit_card`, `onboarding_average_transaction_value`, `onboarding_first_name`, `onboarding_last_name`, `onboarding_personal_emailaddress`, `onboarding_personal_telephone_number`, `onboarding_personal_street_address`, `onboarding_personal_postal_code`, `onboarding_personal_birthdate`, `onboarding_personal_social_security_number`, `onboarding_business_name`, `onboarding_business_telephone_number`, `onboarding_business_emailaddress`, `onboarding_business_url_homepage`, `onboarding_business_public_directory`, `onboarding_postfix`, `onboarding_business_type`, `onboarding_business_registered_region`, `onboarding_business_EIN`, `onboarding_business_EIN_FAQ`, `onboarding_legal_tickbox_alert_terms_of_service`, `onboarding_legal_tickbox_alert_refund_policy`, `onboarding_legal_tickbox_alert_privacy_policy`, `onboarding_identity_selfie`, `onboarding_identity_photo_id`, `onboarding_identity_photo_id_title`, `onboarding_identity_photo_id_options`, `onboarding_identity_residence`, `onboarding_identity_residence_title`, `onboarding_identity_residence_options`, `onboarding_identity_business`, `onboarding_identity_business_title`, `onboarding_identity_business_options`, `onboarding_identity_banking`, `onboarding_identity_banking_title`, `onboarding_identity_banking_options`, `onboarding_identity_tax_returns`, `onboarding_identity_tax_returns_title`, `onboarding_identity_tax_returns_options`, `onboarding_identity_processing`, `onboarding_identity_processing_title`, `onboarding_identity_processing_options`, `onboarding_owner_signature`, `onboarding_terms_of_service_url`, `onboarding_terms_of_service_text`, `onboarding_whitelabel_business_emailaddress_agents`, `onboarding_whitelabel_business_emailaddress_support`, `onboarding_whitelabel_business_emailaddress_underwriting`, `onboarding_whitelabel_business_account_hostname`, `MATCH_ AcquirerId`, `onboarding_kyc_search_personal_name`, `onboarding_kyc_search_personal_location`, `onboarding_kyc_search_business_name`, `onboarding_kyc_search_business_location`, `onboarding_kyc_search_business_url`, `onboarding_aml_ofac_sdn`, `onboarding_aml_ofac_consolidated`, `onboarding_aml_fbi`, `onboarding_aml_dea`, `onboarding_aml_interpol`, `onboarding_aml_ncmec`, `CRM_followup_STAGE_1_EMAIL_1_subject`, `CRM_followup_STAGE_1_EMAIL_1_body`, `CRM_followup_STAGE_1_EMAIL_2_subject`, `CRM_followup_STAGE_1_EMAIL_2_body`, `CRM_followup_STAGE_1_EMAIL_3_subject`, `CRM_followup_STAGE_1_EMAIL_3_body`, `CRM_followup_STAGE_1_EMAIL_4_subject`, `CRM_followup_STAGE_1_EMAIL_4_body`, `CRM_followup_STAGE_2_EMAIL_1_subject`, `CRM_followup_STAGE_2_EMAIL_1_body`, `CRM_followup_STAGE_2_EMAIL_2_subject`, `CRM_followup_STAGE_2_EMAIL_2_body`, `CRM_followup_STAGE_2_EMAIL_3_subject`, `CRM_followup_STAGE_2_EMAIL_3_body`, `CRM_followup_STAGE_2_EMAIL_4_subject`, `CRM_followup_STAGE_2_EMAIL_4_body`, `CRM_followup_STAGE_3_EMAIL_1_subject`, `CRM_followup_STAGE_3_EMAIL_1_body`, `CRM_followup_STAGE_3_EMAIL_2_subject`, `CRM_followup_STAGE_3_EMAIL_2_body`, `CRM_followup_STAGE_3_EMAIL_3_subject`, `CRM_followup_STAGE_3_EMAIL_3_body`, `CRM_followup_STAGE_3_EMAIL_4_subject`, `CRM_followup_STAGE_3_EMAIL_4_body`, `CRM_followup_STAGE_4_EMAIL_1_subject`, `CRM_followup_STAGE_4_EMAIL_1_body`, `CRM_followup_STAGE_4_EMAIL_2_subject`, `CRM_followup_STAGE_4_EMAIL_2_body`, `CRM_followup_STAGE_4_EMAIL_3_subject`, `CRM_followup_STAGE_4_EMAIL_3_body`, `CRM_followup_STAGE_4_EMAIL_4_subject`, `CRM_followup_STAGE_4_EMAIL_4_body`, `CRM_followup_STAGE_5_EMAIL_1_subject`, `CRM_followup_STAGE_5_EMAIL_1_body`, `CRM_followup_STAGE_5_EMAIL_2_subject`, `CRM_followup_STAGE_5_EMAIL_2_body`, `CRM_followup_STAGE_5_EMAIL_3_subject`, `CRM_followup_STAGE_5_EMAIL_3_body`, `CRM_followup_STAGE_5_EMAIL_4_subject`, `CRM_followup_STAGE_5_EMAIL_4_body`, `CRM_followup_STAGE_6_EMAIL_1_subject`, `CRM_followup_STAGE_6_EMAIL_1_body`, `CRM_followup_STAGE_6_EMAIL_2_subject`, `CRM_followup_STAGE_6_EMAIL_2_body`, `CRM_followup_STAGE_6_EMAIL_3_subject`, `CRM_followup_STAGE_6_EMAIL_3_body`, `CRM_followup_STAGE_6_EMAIL_4_subject`, `CRM_followup_STAGE_6_EMAIL_4_body`, `CRM_followup_STAGE_7_EMAIL_1_subject`, `CRM_followup_STAGE_7_EMAIL_1_body`, `CRM_followup_STAGE_7_EMAIL_2_subject`, `CRM_followup_STAGE_7_EMAIL_2_body`, `CRM_followup_STAGE_7_EMAIL_3_subject`, `CRM_followup_STAGE_7_EMAIL_3_body`, `CRM_followup_STAGE_7_EMAIL_4_subject`, `CRM_followup_STAGE_7_EMAIL_4_body`, `CRM_followup_STAGE_8_EMAIL_1_subject`, `CRM_followup_STAGE_8_EMAIL_1_body`, `CRM_followup_STAGE_8_EMAIL_2_subject`, `CRM_followup_STAGE_8_EMAIL_2_body`, `CRM_followup_STAGE_8_EMAIL_3_subject`, `CRM_followup_STAGE_8_EMAIL_3_body`, `CRM_followup_STAGE_8_EMAIL_4_subject`, `CRM_followup_STAGE_8_EMAIL_4_body`, `login_screen_footer_image_full_url_or_simple_text`, `onboarding_account_registration_process`, `form_type_display_queue`, `more_personal_documents_1`, `more_personal_documents_2`, `more_personal_documents_3`, `more_personal_documents_4`, `more_personal_documents_5`, `more_personal_documents_6`, `more_personal_documents_7`, `more_personal_documents_8`, `more_personal_documents_9`, `more_personal_documents_10`, `more_business_documents_1`, `more_business_documents_2`, `more_business_documents_3`, `more_business_documents_4`, `more_business_documents_5`, `more_business_documents_6`, `more_business_documents_7`, `more_business_documents_8`, `more_business_documents_9`, `more_business_documents_10`, `more_signatures_1`, `more_signatures_2`, `more_signatures_3`, `more_signatures_4`, `more_signatures_5`, `more_signatures_6`, `more_signatures_7`, `more_signatures_8`, `more_signatures_9`, `more_signatures_10`, `datetime_created`, `datetime_updated`
		# 			
		# 			FROM onboarding_preferences
		# 			
		# 			WHERE hash = '". $existing_profile_hash ."'
		# 			
		# 			;";
		# logger3("tmp_sql",$tmp_sql);
		# $new_onboarding_preferences_id = insertTHECASHIER($tmp_sql,"intelitruth");
		# logger3("new_onboarding_preferences_id",$new_onboarding_preferences_id);
	
	} else { // no default profile exists
		
		
		//$_XXXXX_whitelabel_business_account_hash = $incoming_vars['whitelabel_business_account_hash'];
		$tmp_sql = "INSERT INTO `onboarding_preferences`
					(`hash`, `whitelabel_business_account_hash`, `form_type`, `form_name`, `tier`, `onboarding_account_registration_validation_email`, `onboarding_account_registration_validation_sms`, `onboarding_your_region`, `onboarding_business_category`, `onboarding_business_description`, `onboarding_business_key_words`, `onboarding_years_doing_business`, `onboarding_business_accept_credit_card`, `onboarding_average_transaction_value`, `onboarding_first_name`, `onboarding_last_name`, `onboarding_personal_emailaddress`, `onboarding_personal_telephone_number`, `onboarding_personal_street_address`, `onboarding_personal_postal_code`, `onboarding_personal_birthdate`, `onboarding_personal_social_security_number`, `onboarding_business_name`, `onboarding_business_telephone_number`, `onboarding_business_emailaddress`, `onboarding_business_url_homepage`, `onboarding_business_public_directory`, `onboarding_postfix`, `onboarding_business_type`, `onboarding_business_registered_region`, `onboarding_business_EIN`, `onboarding_business_EIN_FAQ`, `onboarding_legal_tickbox_alert_terms_of_service`, `onboarding_legal_tickbox_alert_refund_policy`, `onboarding_legal_tickbox_alert_privacy_policy`, `onboarding_identity_selfie`, `onboarding_identity_photo_id`, `onboarding_identity_photo_id_title`, `onboarding_identity_photo_id_options`, `onboarding_identity_residence`, `onboarding_identity_residence_title`, `onboarding_identity_residence_options`, `onboarding_identity_business`, `onboarding_identity_business_title`, `onboarding_identity_business_options`, `onboarding_identity_banking`, `onboarding_identity_banking_title`, `onboarding_identity_banking_options`, `onboarding_identity_tax_returns`, `onboarding_identity_tax_returns_title`, `onboarding_identity_tax_returns_options`, `onboarding_identity_processing`, `onboarding_identity_processing_title`, `onboarding_identity_processing_options`, `onboarding_owner_signature`, `onboarding_terms_of_service_url`, `onboarding_terms_of_service_text`, `onboarding_whitelabel_business_emailaddress_agents`, `onboarding_whitelabel_business_emailaddress_support`, `onboarding_whitelabel_business_emailaddress_underwriting`, `onboarding_whitelabel_business_account_hostname`, `MATCH_ AcquirerId`, `onboarding_kyc_search_personal_name`, `onboarding_kyc_search_personal_location`, `onboarding_kyc_search_business_name`, `onboarding_kyc_search_business_location`, `onboarding_kyc_search_business_url`, `onboarding_aml_ofac_sdn`, `onboarding_aml_ofac_consolidated`, `onboarding_aml_fbi`, `onboarding_aml_dea`, `onboarding_aml_interpol`, `onboarding_aml_ncmec`, `CRM_followup_STAGE_1_EMAIL_1_subject`, `CRM_followup_STAGE_1_EMAIL_1_body`, `CRM_followup_STAGE_1_EMAIL_2_subject`, `CRM_followup_STAGE_1_EMAIL_2_body`, `CRM_followup_STAGE_1_EMAIL_3_subject`, `CRM_followup_STAGE_1_EMAIL_3_body`, `CRM_followup_STAGE_1_EMAIL_4_subject`, `CRM_followup_STAGE_1_EMAIL_4_body`, `CRM_followup_STAGE_2_EMAIL_1_subject`, `CRM_followup_STAGE_2_EMAIL_1_body`, `CRM_followup_STAGE_2_EMAIL_2_subject`, `CRM_followup_STAGE_2_EMAIL_2_body`, `CRM_followup_STAGE_2_EMAIL_3_subject`, `CRM_followup_STAGE_2_EMAIL_3_body`, `CRM_followup_STAGE_2_EMAIL_4_subject`, `CRM_followup_STAGE_2_EMAIL_4_body`, `CRM_followup_STAGE_3_EMAIL_1_subject`, `CRM_followup_STAGE_3_EMAIL_1_body`, `CRM_followup_STAGE_3_EMAIL_2_subject`, `CRM_followup_STAGE_3_EMAIL_2_body`, `CRM_followup_STAGE_3_EMAIL_3_subject`, `CRM_followup_STAGE_3_EMAIL_3_body`, `CRM_followup_STAGE_3_EMAIL_4_subject`, `CRM_followup_STAGE_3_EMAIL_4_body`, `CRM_followup_STAGE_4_EMAIL_1_subject`, `CRM_followup_STAGE_4_EMAIL_1_body`, `CRM_followup_STAGE_4_EMAIL_2_subject`, `CRM_followup_STAGE_4_EMAIL_2_body`, `CRM_followup_STAGE_4_EMAIL_3_subject`, `CRM_followup_STAGE_4_EMAIL_3_body`, `CRM_followup_STAGE_4_EMAIL_4_subject`, `CRM_followup_STAGE_4_EMAIL_4_body`, `CRM_followup_STAGE_5_EMAIL_1_subject`, `CRM_followup_STAGE_5_EMAIL_1_body`, `CRM_followup_STAGE_5_EMAIL_2_subject`, `CRM_followup_STAGE_5_EMAIL_2_body`, `CRM_followup_STAGE_5_EMAIL_3_subject`, `CRM_followup_STAGE_5_EMAIL_3_body`, `CRM_followup_STAGE_5_EMAIL_4_subject`, `CRM_followup_STAGE_5_EMAIL_4_body`, `CRM_followup_STAGE_6_EMAIL_1_subject`, `CRM_followup_STAGE_6_EMAIL_1_body`, `CRM_followup_STAGE_6_EMAIL_2_subject`, `CRM_followup_STAGE_6_EMAIL_2_body`, `CRM_followup_STAGE_6_EMAIL_3_subject`, `CRM_followup_STAGE_6_EMAIL_3_body`, `CRM_followup_STAGE_6_EMAIL_4_subject`, `CRM_followup_STAGE_6_EMAIL_4_body`, `CRM_followup_STAGE_7_EMAIL_1_subject`, `CRM_followup_STAGE_7_EMAIL_1_body`, `CRM_followup_STAGE_7_EMAIL_2_subject`, `CRM_followup_STAGE_7_EMAIL_2_body`, `CRM_followup_STAGE_7_EMAIL_3_subject`, `CRM_followup_STAGE_7_EMAIL_3_body`, `CRM_followup_STAGE_7_EMAIL_4_subject`, `CRM_followup_STAGE_7_EMAIL_4_body`, `CRM_followup_STAGE_8_EMAIL_1_subject`, `CRM_followup_STAGE_8_EMAIL_1_body`, `CRM_followup_STAGE_8_EMAIL_2_subject`, `CRM_followup_STAGE_8_EMAIL_2_body`, `CRM_followup_STAGE_8_EMAIL_3_subject`, `CRM_followup_STAGE_8_EMAIL_3_body`, `CRM_followup_STAGE_8_EMAIL_4_subject`, `CRM_followup_STAGE_8_EMAIL_4_body`, `login_screen_footer_image_full_url_or_simple_text`, `onboarding_account_registration_process`, `form_type_display_queue`, `more_personal_documents_1`, `more_personal_documents_2`, `more_personal_documents_3`, `more_personal_documents_4`, `more_personal_documents_5`, `more_personal_documents_6`, `more_personal_documents_7`, `more_personal_documents_8`, `more_personal_documents_9`, `more_personal_documents_10`, `more_business_documents_1`, `more_business_documents_2`, `more_business_documents_3`, `more_business_documents_4`, `more_business_documents_5`, `more_business_documents_6`, `more_business_documents_7`, `more_business_documents_8`, `more_business_documents_9`, `more_business_documents_10`, `more_signatures_1`, `more_signatures_2`, `more_signatures_3`, `more_signatures_4`, `more_signatures_5`, `more_signatures_6`, `more_signatures_7`, `more_signatures_8`, `more_signatures_9`, `more_signatures_10`, `datetime_created`, `datetime_updated`)
		
					SELECT `hash`, `whitelabel_business_account_hash`, `form_type`, `form_name`, `tier`, `onboarding_account_registration_validation_email`, `onboarding_account_registration_validation_sms`, `onboarding_your_region`, `onboarding_business_category`, `onboarding_business_description`, `onboarding_business_key_words`, `onboarding_years_doing_business`, `onboarding_business_accept_credit_card`, `onboarding_average_transaction_value`, `onboarding_first_name`, `onboarding_last_name`, `onboarding_personal_emailaddress`, `onboarding_personal_telephone_number`, `onboarding_personal_street_address`, `onboarding_personal_postal_code`, `onboarding_personal_birthdate`, `onboarding_personal_social_security_number`, `onboarding_business_name`, `onboarding_business_telephone_number`, `onboarding_business_emailaddress`, `onboarding_business_url_homepage`, `onboarding_business_public_directory`, `onboarding_postfix`, `onboarding_business_type`, `onboarding_business_registered_region`, `onboarding_business_EIN`, `onboarding_business_EIN_FAQ`, `onboarding_legal_tickbox_alert_terms_of_service`, `onboarding_legal_tickbox_alert_refund_policy`, `onboarding_legal_tickbox_alert_privacy_policy`, `onboarding_identity_selfie`, `onboarding_identity_photo_id`, `onboarding_identity_photo_id_title`, `onboarding_identity_photo_id_options`, `onboarding_identity_residence`, `onboarding_identity_residence_title`, `onboarding_identity_residence_options`, `onboarding_identity_business`, `onboarding_identity_business_title`, `onboarding_identity_business_options`, `onboarding_identity_banking`, `onboarding_identity_banking_title`, `onboarding_identity_banking_options`, `onboarding_identity_tax_returns`, `onboarding_identity_tax_returns_title`, `onboarding_identity_tax_returns_options`, `onboarding_identity_processing`, `onboarding_identity_processing_title`, `onboarding_identity_processing_options`, `onboarding_owner_signature`, `onboarding_terms_of_service_url`, `onboarding_terms_of_service_text`, `onboarding_whitelabel_business_emailaddress_agents`, `onboarding_whitelabel_business_emailaddress_support`, `onboarding_whitelabel_business_emailaddress_underwriting`, `onboarding_whitelabel_business_account_hostname`, `MATCH_ AcquirerId`, `onboarding_kyc_search_personal_name`, `onboarding_kyc_search_personal_location`, `onboarding_kyc_search_business_name`, `onboarding_kyc_search_business_location`, `onboarding_kyc_search_business_url`, `onboarding_aml_ofac_sdn`, `onboarding_aml_ofac_consolidated`, `onboarding_aml_fbi`, `onboarding_aml_dea`, `onboarding_aml_interpol`, `onboarding_aml_ncmec`, `CRM_followup_STAGE_1_EMAIL_1_subject`, `CRM_followup_STAGE_1_EMAIL_1_body`, `CRM_followup_STAGE_1_EMAIL_2_subject`, `CRM_followup_STAGE_1_EMAIL_2_body`, `CRM_followup_STAGE_1_EMAIL_3_subject`, `CRM_followup_STAGE_1_EMAIL_3_body`, `CRM_followup_STAGE_1_EMAIL_4_subject`, `CRM_followup_STAGE_1_EMAIL_4_body`, `CRM_followup_STAGE_2_EMAIL_1_subject`, `CRM_followup_STAGE_2_EMAIL_1_body`, `CRM_followup_STAGE_2_EMAIL_2_subject`, `CRM_followup_STAGE_2_EMAIL_2_body`, `CRM_followup_STAGE_2_EMAIL_3_subject`, `CRM_followup_STAGE_2_EMAIL_3_body`, `CRM_followup_STAGE_2_EMAIL_4_subject`, `CRM_followup_STAGE_2_EMAIL_4_body`, `CRM_followup_STAGE_3_EMAIL_1_subject`, `CRM_followup_STAGE_3_EMAIL_1_body`, `CRM_followup_STAGE_3_EMAIL_2_subject`, `CRM_followup_STAGE_3_EMAIL_2_body`, `CRM_followup_STAGE_3_EMAIL_3_subject`, `CRM_followup_STAGE_3_EMAIL_3_body`, `CRM_followup_STAGE_3_EMAIL_4_subject`, `CRM_followup_STAGE_3_EMAIL_4_body`, `CRM_followup_STAGE_4_EMAIL_1_subject`, `CRM_followup_STAGE_4_EMAIL_1_body`, `CRM_followup_STAGE_4_EMAIL_2_subject`, `CRM_followup_STAGE_4_EMAIL_2_body`, `CRM_followup_STAGE_4_EMAIL_3_subject`, `CRM_followup_STAGE_4_EMAIL_3_body`, `CRM_followup_STAGE_4_EMAIL_4_subject`, `CRM_followup_STAGE_4_EMAIL_4_body`, `CRM_followup_STAGE_5_EMAIL_1_subject`, `CRM_followup_STAGE_5_EMAIL_1_body`, `CRM_followup_STAGE_5_EMAIL_2_subject`, `CRM_followup_STAGE_5_EMAIL_2_body`, `CRM_followup_STAGE_5_EMAIL_3_subject`, `CRM_followup_STAGE_5_EMAIL_3_body`, `CRM_followup_STAGE_5_EMAIL_4_subject`, `CRM_followup_STAGE_5_EMAIL_4_body`, `CRM_followup_STAGE_6_EMAIL_1_subject`, `CRM_followup_STAGE_6_EMAIL_1_body`, `CRM_followup_STAGE_6_EMAIL_2_subject`, `CRM_followup_STAGE_6_EMAIL_2_body`, `CRM_followup_STAGE_6_EMAIL_3_subject`, `CRM_followup_STAGE_6_EMAIL_3_body`, `CRM_followup_STAGE_6_EMAIL_4_subject`, `CRM_followup_STAGE_6_EMAIL_4_body`, `CRM_followup_STAGE_7_EMAIL_1_subject`, `CRM_followup_STAGE_7_EMAIL_1_body`, `CRM_followup_STAGE_7_EMAIL_2_subject`, `CRM_followup_STAGE_7_EMAIL_2_body`, `CRM_followup_STAGE_7_EMAIL_3_subject`, `CRM_followup_STAGE_7_EMAIL_3_body`, `CRM_followup_STAGE_7_EMAIL_4_subject`, `CRM_followup_STAGE_7_EMAIL_4_body`, `CRM_followup_STAGE_8_EMAIL_1_subject`, `CRM_followup_STAGE_8_EMAIL_1_body`, `CRM_followup_STAGE_8_EMAIL_2_subject`, `CRM_followup_STAGE_8_EMAIL_2_body`, `CRM_followup_STAGE_8_EMAIL_3_subject`, `CRM_followup_STAGE_8_EMAIL_3_body`, `CRM_followup_STAGE_8_EMAIL_4_subject`, `CRM_followup_STAGE_8_EMAIL_4_body`, `login_screen_footer_image_full_url_or_simple_text`, `onboarding_account_registration_process`, `form_type_display_queue`, `more_personal_documents_1`, `more_personal_documents_2`, `more_personal_documents_3`, `more_personal_documents_4`, `more_personal_documents_5`, `more_personal_documents_6`, `more_personal_documents_7`, `more_personal_documents_8`, `more_personal_documents_9`, `more_personal_documents_10`, `more_business_documents_1`, `more_business_documents_2`, `more_business_documents_3`, `more_business_documents_4`, `more_business_documents_5`, `more_business_documents_6`, `more_business_documents_7`, `more_business_documents_8`, `more_business_documents_9`, `more_business_documents_10`, `more_signatures_1`, `more_signatures_2`, `more_signatures_3`, `more_signatures_4`, `more_signatures_5`, `more_signatures_6`, `more_signatures_7`, `more_signatures_8`, `more_signatures_9`, `more_signatures_10`, `datetime_created`, `datetime_updated`
					
					FROM onboarding_preferences
					
					WHERE whitelabel_business_account_hash = 'DEFAULT'
					
					;";
		logger3("tmp_sql",$tmp_sql);
		$new_onboarding_preferences_id = insertTHECASHIER($tmp_sql,"intelitruth");
		logger3("new_onboarding_preferences_id",$new_onboarding_preferences_id);
		
		
		
		
		
		$_XXXXX_whitelabel_business_account_hash = $_XXXXX_whitelabel_business_account_hash;
		$_XXXXX_datetime_updated = datetime();
		$tmp_sql = "UPDATE onboarding_preferences 
					SET whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
					, form_name = '". addslashes($incoming_preferences_profile) ."'
					, datetime_created = '". $_XXXXX_datetime_created ."'
					, datetime_updated = '". $_XXXXX_datetime_updated ."'
					WHERE onboarding_preferences_id = '". $new_onboarding_preferences_id ."'
					;";
		logger3("WHITELABEL_tmp_sql",$tmp_sql);
		$update_results = updateTHECASHIER($tmp_sql,"intelitruth");
		logger3("WHITELABEL_tmp_sqlupdate_results",$update_results);
		
		
		
		
	
		
		
		
		
		
	}
	
	# $_XXXXX_hash = hash_me();
	# $_XXXXX_datetime = datetime_v2();
	# $_XXXXX_form_name = addslashes($incoming_preferences_profile);
	# $tmp_sql = "INSERT INTO `onboarding_preferences`
	# 			(
	# 				`onboarding_preferences_id`
	# 				, `hash`,
	# 				, `whitelabel_business_account_hash`
	# 				, `form_name`
	# 				, `datetime_created`
	# 				, `datetime_updated`
	# 			) VALUES (
	# 				,''
	# 				,'". $_XXXXX_hash."'
	# 				,'". $_XXXXX_whitelabel_business_account_hash ."'
	# 				,'". $_XXXXX_form_name ."'
	# 				,'". $_XXXXX_datetime ."'
	# 				,'". $_XXXXX_datetime ."'
	# 				
	# 			);
	# 			
	# 			";
	# logger3("tmp_sql",$tmp_sql);
	# $insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
	# logger3("insert_results",$insert_results);



}
	


function IEW_create_new_intelitruth_preferences_profile($_XXXXX_whitelabel_business_account_hash,$incoming_preferences_profile="") {
	
	
	
	logger3("IEW_create_new_intelitruth_preferences_profile() _XXXXX_whitelabel_business_account_hash",$_XXXXX_whitelabel_business_account_hash);
	logger3("IEW_create_new_intelitruth_preferences_profile() incoming_preferences_profile",$incoming_preferences_profile);
	
	
	
	##############################################################
	##############################################################
	### V1
	
/*
	
		if(!$incoming_preferences_profile) $incoming_preferences_profile = "DEFAULT";
		
		$tmp_sql = "SELECT hash 
					FROM onboarding_preferences
					WHERE form_name = '". addslashes($incoming_preferences_profile) ."'
					AND whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
					ORDER BY datetime_created ASC
					LIMIT 1
					;";
		$existing_profile_hash = $default_profile_exists = getTHECASHIER($tmp_sql,"intelitruth");
		
		if($existing_profile_hash) {  /// GET THE EXISTSING DATA
			
			# //$_XXXXX_whitelabel_business_account_hash = $incoming_vars['whitelabel_business_account_hash'];
			# $tmp_sql = "INSERT INTO `onboarding_preferences`
			# 			(`hash`, `whitelabel_business_account_hash`, `form_type`, `form_name`, `tier`, `onboarding_account_registration_validation_email`, `onboarding_account_registration_validation_sms`, `onboarding_your_region`, `onboarding_business_category`, `onboarding_business_description`, `onboarding_business_key_words`, `onboarding_years_doing_business`, `onboarding_business_accept_credit_card`, `onboarding_average_transaction_value`, `onboarding_first_name`, `onboarding_last_name`, `onboarding_personal_emailaddress`, `onboarding_personal_telephone_number`, `onboarding_personal_street_address`, `onboarding_personal_postal_code`, `onboarding_personal_birthdate`, `onboarding_personal_social_security_number`, `onboarding_business_name`, `onboarding_business_telephone_number`, `onboarding_business_emailaddress`, `onboarding_business_url_homepage`, `onboarding_business_public_directory`, `onboarding_postfix`, `onboarding_business_type`, `onboarding_business_registered_region`, `onboarding_business_EIN`, `onboarding_business_EIN_FAQ`, `onboarding_legal_tickbox_alert_terms_of_service`, `onboarding_legal_tickbox_alert_refund_policy`, `onboarding_legal_tickbox_alert_privacy_policy`, `onboarding_identity_selfie`, `onboarding_identity_photo_id`, `onboarding_identity_photo_id_title`, `onboarding_identity_photo_id_options`, `onboarding_identity_residence`, `onboarding_identity_residence_title`, `onboarding_identity_residence_options`, `onboarding_identity_business`, `onboarding_identity_business_title`, `onboarding_identity_business_options`, `onboarding_identity_banking`, `onboarding_identity_banking_title`, `onboarding_identity_banking_options`, `onboarding_identity_tax_returns`, `onboarding_identity_tax_returns_title`, `onboarding_identity_tax_returns_options`, `onboarding_identity_processing`, `onboarding_identity_processing_title`, `onboarding_identity_processing_options`, `onboarding_owner_signature`, `onboarding_terms_of_service_url`, `onboarding_terms_of_service_text`, `onboarding_whitelabel_business_emailaddress_agents`, `onboarding_whitelabel_business_emailaddress_support`, `onboarding_whitelabel_business_emailaddress_underwriting`, `onboarding_whitelabel_business_account_hostname`, `MATCH_ AcquirerId`, `onboarding_kyc_search_personal_name`, `onboarding_kyc_search_personal_location`, `onboarding_kyc_search_business_name`, `onboarding_kyc_search_business_location`, `onboarding_kyc_search_business_url`, `onboarding_aml_ofac_sdn`, `onboarding_aml_ofac_consolidated`, `onboarding_aml_fbi`, `onboarding_aml_dea`, `onboarding_aml_interpol`, `onboarding_aml_ncmec`, `CRM_followup_STAGE_1_EMAIL_1_subject`, `CRM_followup_STAGE_1_EMAIL_1_body`, `CRM_followup_STAGE_1_EMAIL_2_subject`, `CRM_followup_STAGE_1_EMAIL_2_body`, `CRM_followup_STAGE_1_EMAIL_3_subject`, `CRM_followup_STAGE_1_EMAIL_3_body`, `CRM_followup_STAGE_1_EMAIL_4_subject`, `CRM_followup_STAGE_1_EMAIL_4_body`, `CRM_followup_STAGE_2_EMAIL_1_subject`, `CRM_followup_STAGE_2_EMAIL_1_body`, `CRM_followup_STAGE_2_EMAIL_2_subject`, `CRM_followup_STAGE_2_EMAIL_2_body`, `CRM_followup_STAGE_2_EMAIL_3_subject`, `CRM_followup_STAGE_2_EMAIL_3_body`, `CRM_followup_STAGE_2_EMAIL_4_subject`, `CRM_followup_STAGE_2_EMAIL_4_body`, `CRM_followup_STAGE_3_EMAIL_1_subject`, `CRM_followup_STAGE_3_EMAIL_1_body`, `CRM_followup_STAGE_3_EMAIL_2_subject`, `CRM_followup_STAGE_3_EMAIL_2_body`, `CRM_followup_STAGE_3_EMAIL_3_subject`, `CRM_followup_STAGE_3_EMAIL_3_body`, `CRM_followup_STAGE_3_EMAIL_4_subject`, `CRM_followup_STAGE_3_EMAIL_4_body`, `CRM_followup_STAGE_4_EMAIL_1_subject`, `CRM_followup_STAGE_4_EMAIL_1_body`, `CRM_followup_STAGE_4_EMAIL_2_subject`, `CRM_followup_STAGE_4_EMAIL_2_body`, `CRM_followup_STAGE_4_EMAIL_3_subject`, `CRM_followup_STAGE_4_EMAIL_3_body`, `CRM_followup_STAGE_4_EMAIL_4_subject`, `CRM_followup_STAGE_4_EMAIL_4_body`, `CRM_followup_STAGE_5_EMAIL_1_subject`, `CRM_followup_STAGE_5_EMAIL_1_body`, `CRM_followup_STAGE_5_EMAIL_2_subject`, `CRM_followup_STAGE_5_EMAIL_2_body`, `CRM_followup_STAGE_5_EMAIL_3_subject`, `CRM_followup_STAGE_5_EMAIL_3_body`, `CRM_followup_STAGE_5_EMAIL_4_subject`, `CRM_followup_STAGE_5_EMAIL_4_body`, `CRM_followup_STAGE_6_EMAIL_1_subject`, `CRM_followup_STAGE_6_EMAIL_1_body`, `CRM_followup_STAGE_6_EMAIL_2_subject`, `CRM_followup_STAGE_6_EMAIL_2_body`, `CRM_followup_STAGE_6_EMAIL_3_subject`, `CRM_followup_STAGE_6_EMAIL_3_body`, `CRM_followup_STAGE_6_EMAIL_4_subject`, `CRM_followup_STAGE_6_EMAIL_4_body`, `CRM_followup_STAGE_7_EMAIL_1_subject`, `CRM_followup_STAGE_7_EMAIL_1_body`, `CRM_followup_STAGE_7_EMAIL_2_subject`, `CRM_followup_STAGE_7_EMAIL_2_body`, `CRM_followup_STAGE_7_EMAIL_3_subject`, `CRM_followup_STAGE_7_EMAIL_3_body`, `CRM_followup_STAGE_7_EMAIL_4_subject`, `CRM_followup_STAGE_7_EMAIL_4_body`, `CRM_followup_STAGE_8_EMAIL_1_subject`, `CRM_followup_STAGE_8_EMAIL_1_body`, `CRM_followup_STAGE_8_EMAIL_2_subject`, `CRM_followup_STAGE_8_EMAIL_2_body`, `CRM_followup_STAGE_8_EMAIL_3_subject`, `CRM_followup_STAGE_8_EMAIL_3_body`, `CRM_followup_STAGE_8_EMAIL_4_subject`, `CRM_followup_STAGE_8_EMAIL_4_body`, `login_screen_footer_image_full_url_or_simple_text`, `onboarding_account_registration_process`, `form_type_display_queue`, `more_personal_documents_1`, `more_personal_documents_2`, `more_personal_documents_3`, `more_personal_documents_4`, `more_personal_documents_5`, `more_personal_documents_6`, `more_personal_documents_7`, `more_personal_documents_8`, `more_personal_documents_9`, `more_personal_documents_10`, `more_business_documents_1`, `more_business_documents_2`, `more_business_documents_3`, `more_business_documents_4`, `more_business_documents_5`, `more_business_documents_6`, `more_business_documents_7`, `more_business_documents_8`, `more_business_documents_9`, `more_business_documents_10`, `more_signatures_1`, `more_signatures_2`, `more_signatures_3`, `more_signatures_4`, `more_signatures_5`, `more_signatures_6`, `more_signatures_7`, `more_signatures_8`, `more_signatures_9`, `more_signatures_10`, `datetime_created`, `datetime_updated`)
			# 
			# 			SELECT `hash`, `whitelabel_business_account_hash`, `form_type`, `form_name`, `tier`, `onboarding_account_registration_validation_email`, `onboarding_account_registration_validation_sms`, `onboarding_your_region`, `onboarding_business_category`, `onboarding_business_description`, `onboarding_business_key_words`, `onboarding_years_doing_business`, `onboarding_business_accept_credit_card`, `onboarding_average_transaction_value`, `onboarding_first_name`, `onboarding_last_name`, `onboarding_personal_emailaddress`, `onboarding_personal_telephone_number`, `onboarding_personal_street_address`, `onboarding_personal_postal_code`, `onboarding_personal_birthdate`, `onboarding_personal_social_security_number`, `onboarding_business_name`, `onboarding_business_telephone_number`, `onboarding_business_emailaddress`, `onboarding_business_url_homepage`, `onboarding_business_public_directory`, `onboarding_postfix`, `onboarding_business_type`, `onboarding_business_registered_region`, `onboarding_business_EIN`, `onboarding_business_EIN_FAQ`, `onboarding_legal_tickbox_alert_terms_of_service`, `onboarding_legal_tickbox_alert_refund_policy`, `onboarding_legal_tickbox_alert_privacy_policy`, `onboarding_identity_selfie`, `onboarding_identity_photo_id`, `onboarding_identity_photo_id_title`, `onboarding_identity_photo_id_options`, `onboarding_identity_residence`, `onboarding_identity_residence_title`, `onboarding_identity_residence_options`, `onboarding_identity_business`, `onboarding_identity_business_title`, `onboarding_identity_business_options`, `onboarding_identity_banking`, `onboarding_identity_banking_title`, `onboarding_identity_banking_options`, `onboarding_identity_tax_returns`, `onboarding_identity_tax_returns_title`, `onboarding_identity_tax_returns_options`, `onboarding_identity_processing`, `onboarding_identity_processing_title`, `onboarding_identity_processing_options`, `onboarding_owner_signature`, `onboarding_terms_of_service_url`, `onboarding_terms_of_service_text`, `onboarding_whitelabel_business_emailaddress_agents`, `onboarding_whitelabel_business_emailaddress_support`, `onboarding_whitelabel_business_emailaddress_underwriting`, `onboarding_whitelabel_business_account_hostname`, `MATCH_ AcquirerId`, `onboarding_kyc_search_personal_name`, `onboarding_kyc_search_personal_location`, `onboarding_kyc_search_business_name`, `onboarding_kyc_search_business_location`, `onboarding_kyc_search_business_url`, `onboarding_aml_ofac_sdn`, `onboarding_aml_ofac_consolidated`, `onboarding_aml_fbi`, `onboarding_aml_dea`, `onboarding_aml_interpol`, `onboarding_aml_ncmec`, `CRM_followup_STAGE_1_EMAIL_1_subject`, `CRM_followup_STAGE_1_EMAIL_1_body`, `CRM_followup_STAGE_1_EMAIL_2_subject`, `CRM_followup_STAGE_1_EMAIL_2_body`, `CRM_followup_STAGE_1_EMAIL_3_subject`, `CRM_followup_STAGE_1_EMAIL_3_body`, `CRM_followup_STAGE_1_EMAIL_4_subject`, `CRM_followup_STAGE_1_EMAIL_4_body`, `CRM_followup_STAGE_2_EMAIL_1_subject`, `CRM_followup_STAGE_2_EMAIL_1_body`, `CRM_followup_STAGE_2_EMAIL_2_subject`, `CRM_followup_STAGE_2_EMAIL_2_body`, `CRM_followup_STAGE_2_EMAIL_3_subject`, `CRM_followup_STAGE_2_EMAIL_3_body`, `CRM_followup_STAGE_2_EMAIL_4_subject`, `CRM_followup_STAGE_2_EMAIL_4_body`, `CRM_followup_STAGE_3_EMAIL_1_subject`, `CRM_followup_STAGE_3_EMAIL_1_body`, `CRM_followup_STAGE_3_EMAIL_2_subject`, `CRM_followup_STAGE_3_EMAIL_2_body`, `CRM_followup_STAGE_3_EMAIL_3_subject`, `CRM_followup_STAGE_3_EMAIL_3_body`, `CRM_followup_STAGE_3_EMAIL_4_subject`, `CRM_followup_STAGE_3_EMAIL_4_body`, `CRM_followup_STAGE_4_EMAIL_1_subject`, `CRM_followup_STAGE_4_EMAIL_1_body`, `CRM_followup_STAGE_4_EMAIL_2_subject`, `CRM_followup_STAGE_4_EMAIL_2_body`, `CRM_followup_STAGE_4_EMAIL_3_subject`, `CRM_followup_STAGE_4_EMAIL_3_body`, `CRM_followup_STAGE_4_EMAIL_4_subject`, `CRM_followup_STAGE_4_EMAIL_4_body`, `CRM_followup_STAGE_5_EMAIL_1_subject`, `CRM_followup_STAGE_5_EMAIL_1_body`, `CRM_followup_STAGE_5_EMAIL_2_subject`, `CRM_followup_STAGE_5_EMAIL_2_body`, `CRM_followup_STAGE_5_EMAIL_3_subject`, `CRM_followup_STAGE_5_EMAIL_3_body`, `CRM_followup_STAGE_5_EMAIL_4_subject`, `CRM_followup_STAGE_5_EMAIL_4_body`, `CRM_followup_STAGE_6_EMAIL_1_subject`, `CRM_followup_STAGE_6_EMAIL_1_body`, `CRM_followup_STAGE_6_EMAIL_2_subject`, `CRM_followup_STAGE_6_EMAIL_2_body`, `CRM_followup_STAGE_6_EMAIL_3_subject`, `CRM_followup_STAGE_6_EMAIL_3_body`, `CRM_followup_STAGE_6_EMAIL_4_subject`, `CRM_followup_STAGE_6_EMAIL_4_body`, `CRM_followup_STAGE_7_EMAIL_1_subject`, `CRM_followup_STAGE_7_EMAIL_1_body`, `CRM_followup_STAGE_7_EMAIL_2_subject`, `CRM_followup_STAGE_7_EMAIL_2_body`, `CRM_followup_STAGE_7_EMAIL_3_subject`, `CRM_followup_STAGE_7_EMAIL_3_body`, `CRM_followup_STAGE_7_EMAIL_4_subject`, `CRM_followup_STAGE_7_EMAIL_4_body`, `CRM_followup_STAGE_8_EMAIL_1_subject`, `CRM_followup_STAGE_8_EMAIL_1_body`, `CRM_followup_STAGE_8_EMAIL_2_subject`, `CRM_followup_STAGE_8_EMAIL_2_body`, `CRM_followup_STAGE_8_EMAIL_3_subject`, `CRM_followup_STAGE_8_EMAIL_3_body`, `CRM_followup_STAGE_8_EMAIL_4_subject`, `CRM_followup_STAGE_8_EMAIL_4_body`, `login_screen_footer_image_full_url_or_simple_text`, `onboarding_account_registration_process`, `form_type_display_queue`, `more_personal_documents_1`, `more_personal_documents_2`, `more_personal_documents_3`, `more_personal_documents_4`, `more_personal_documents_5`, `more_personal_documents_6`, `more_personal_documents_7`, `more_personal_documents_8`, `more_personal_documents_9`, `more_personal_documents_10`, `more_business_documents_1`, `more_business_documents_2`, `more_business_documents_3`, `more_business_documents_4`, `more_business_documents_5`, `more_business_documents_6`, `more_business_documents_7`, `more_business_documents_8`, `more_business_documents_9`, `more_business_documents_10`, `more_signatures_1`, `more_signatures_2`, `more_signatures_3`, `more_signatures_4`, `more_signatures_5`, `more_signatures_6`, `more_signatures_7`, `more_signatures_8`, `more_signatures_9`, `more_signatures_10`, `datetime_created`, `datetime_updated`
			# 			
			# 			FROM onboarding_preferences
			# 			
			# 			WHERE hash = '". $existing_profile_hash ."'
			# 			
			# 			;";
			# logger3("tmp_sql",$tmp_sql);
			# $new_onboarding_preferences_id = insertTHECASHIER($tmp_sql,"intelitruth");
			# logger3("new_onboarding_preferences_id",$new_onboarding_preferences_id);
		
		} else { // no default profile exists
			
			
			//$_XXXXX_whitelabel_business_account_hash = $incoming_vars['whitelabel_business_account_hash'];
			$tmp_sql = "INSERT INTO `onboarding_preferences`
						(`hash`, `whitelabel_business_account_hash`, `form_type`, `form_name`, `tier`, `onboarding_account_registration_validation_email`, `onboarding_account_registration_validation_sms`, `onboarding_your_region`, `onboarding_business_category`, `onboarding_business_description`, `onboarding_business_key_words`, `onboarding_years_doing_business`, `onboarding_business_accept_credit_card`, `onboarding_average_transaction_value`, `onboarding_first_name`, `onboarding_last_name`, `onboarding_personal_emailaddress`, `onboarding_personal_telephone_number`, `onboarding_personal_street_address`, `onboarding_personal_postal_code`, `onboarding_personal_birthdate`, `onboarding_personal_social_security_number`, `onboarding_business_name`, `onboarding_business_telephone_number`, `onboarding_business_emailaddress`, `onboarding_business_url_homepage`, `onboarding_business_public_directory`, `onboarding_postfix`, `onboarding_business_type`, `onboarding_business_registered_region`, `onboarding_business_EIN`, `onboarding_business_EIN_FAQ`, `onboarding_legal_tickbox_alert_terms_of_service`, `onboarding_legal_tickbox_alert_refund_policy`, `onboarding_legal_tickbox_alert_privacy_policy`, `onboarding_identity_selfie`, `onboarding_identity_photo_id`, `onboarding_identity_photo_id_title`, `onboarding_identity_photo_id_options`, `onboarding_identity_residence`, `onboarding_identity_residence_title`, `onboarding_identity_residence_options`, `onboarding_identity_business`, `onboarding_identity_business_title`, `onboarding_identity_business_options`, `onboarding_identity_banking`, `onboarding_identity_banking_title`, `onboarding_identity_banking_options`, `onboarding_identity_tax_returns`, `onboarding_identity_tax_returns_title`, `onboarding_identity_tax_returns_options`, `onboarding_identity_processing`, `onboarding_identity_processing_title`, `onboarding_identity_processing_options`, `onboarding_owner_signature`, `onboarding_terms_of_service_url`, `onboarding_terms_of_service_text`, `onboarding_whitelabel_business_emailaddress_agents`, `onboarding_whitelabel_business_emailaddress_support`, `onboarding_whitelabel_business_emailaddress_underwriting`, `onboarding_whitelabel_business_account_hostname`, `MATCH_ AcquirerId`, `onboarding_kyc_search_personal_name`, `onboarding_kyc_search_personal_location`, `onboarding_kyc_search_business_name`, `onboarding_kyc_search_business_location`, `onboarding_kyc_search_business_url`, `onboarding_aml_ofac_sdn`, `onboarding_aml_ofac_consolidated`, `onboarding_aml_fbi`, `onboarding_aml_dea`, `onboarding_aml_interpol`, `onboarding_aml_ncmec`, `CRM_followup_STAGE_1_EMAIL_1_subject`, `CRM_followup_STAGE_1_EMAIL_1_body`, `CRM_followup_STAGE_1_EMAIL_2_subject`, `CRM_followup_STAGE_1_EMAIL_2_body`, `CRM_followup_STAGE_1_EMAIL_3_subject`, `CRM_followup_STAGE_1_EMAIL_3_body`, `CRM_followup_STAGE_1_EMAIL_4_subject`, `CRM_followup_STAGE_1_EMAIL_4_body`, `CRM_followup_STAGE_2_EMAIL_1_subject`, `CRM_followup_STAGE_2_EMAIL_1_body`, `CRM_followup_STAGE_2_EMAIL_2_subject`, `CRM_followup_STAGE_2_EMAIL_2_body`, `CRM_followup_STAGE_2_EMAIL_3_subject`, `CRM_followup_STAGE_2_EMAIL_3_body`, `CRM_followup_STAGE_2_EMAIL_4_subject`, `CRM_followup_STAGE_2_EMAIL_4_body`, `CRM_followup_STAGE_3_EMAIL_1_subject`, `CRM_followup_STAGE_3_EMAIL_1_body`, `CRM_followup_STAGE_3_EMAIL_2_subject`, `CRM_followup_STAGE_3_EMAIL_2_body`, `CRM_followup_STAGE_3_EMAIL_3_subject`, `CRM_followup_STAGE_3_EMAIL_3_body`, `CRM_followup_STAGE_3_EMAIL_4_subject`, `CRM_followup_STAGE_3_EMAIL_4_body`, `CRM_followup_STAGE_4_EMAIL_1_subject`, `CRM_followup_STAGE_4_EMAIL_1_body`, `CRM_followup_STAGE_4_EMAIL_2_subject`, `CRM_followup_STAGE_4_EMAIL_2_body`, `CRM_followup_STAGE_4_EMAIL_3_subject`, `CRM_followup_STAGE_4_EMAIL_3_body`, `CRM_followup_STAGE_4_EMAIL_4_subject`, `CRM_followup_STAGE_4_EMAIL_4_body`, `CRM_followup_STAGE_5_EMAIL_1_subject`, `CRM_followup_STAGE_5_EMAIL_1_body`, `CRM_followup_STAGE_5_EMAIL_2_subject`, `CRM_followup_STAGE_5_EMAIL_2_body`, `CRM_followup_STAGE_5_EMAIL_3_subject`, `CRM_followup_STAGE_5_EMAIL_3_body`, `CRM_followup_STAGE_5_EMAIL_4_subject`, `CRM_followup_STAGE_5_EMAIL_4_body`, `CRM_followup_STAGE_6_EMAIL_1_subject`, `CRM_followup_STAGE_6_EMAIL_1_body`, `CRM_followup_STAGE_6_EMAIL_2_subject`, `CRM_followup_STAGE_6_EMAIL_2_body`, `CRM_followup_STAGE_6_EMAIL_3_subject`, `CRM_followup_STAGE_6_EMAIL_3_body`, `CRM_followup_STAGE_6_EMAIL_4_subject`, `CRM_followup_STAGE_6_EMAIL_4_body`, `CRM_followup_STAGE_7_EMAIL_1_subject`, `CRM_followup_STAGE_7_EMAIL_1_body`, `CRM_followup_STAGE_7_EMAIL_2_subject`, `CRM_followup_STAGE_7_EMAIL_2_body`, `CRM_followup_STAGE_7_EMAIL_3_subject`, `CRM_followup_STAGE_7_EMAIL_3_body`, `CRM_followup_STAGE_7_EMAIL_4_subject`, `CRM_followup_STAGE_7_EMAIL_4_body`, `CRM_followup_STAGE_8_EMAIL_1_subject`, `CRM_followup_STAGE_8_EMAIL_1_body`, `CRM_followup_STAGE_8_EMAIL_2_subject`, `CRM_followup_STAGE_8_EMAIL_2_body`, `CRM_followup_STAGE_8_EMAIL_3_subject`, `CRM_followup_STAGE_8_EMAIL_3_body`, `CRM_followup_STAGE_8_EMAIL_4_subject`, `CRM_followup_STAGE_8_EMAIL_4_body`, `login_screen_footer_image_full_url_or_simple_text`, `onboarding_account_registration_process`, `form_type_display_queue`, `more_personal_documents_1`, `more_personal_documents_2`, `more_personal_documents_3`, `more_personal_documents_4`, `more_personal_documents_5`, `more_personal_documents_6`, `more_personal_documents_7`, `more_personal_documents_8`, `more_personal_documents_9`, `more_personal_documents_10`, `more_business_documents_1`, `more_business_documents_2`, `more_business_documents_3`, `more_business_documents_4`, `more_business_documents_5`, `more_business_documents_6`, `more_business_documents_7`, `more_business_documents_8`, `more_business_documents_9`, `more_business_documents_10`, `more_signatures_1`, `more_signatures_2`, `more_signatures_3`, `more_signatures_4`, `more_signatures_5`, `more_signatures_6`, `more_signatures_7`, `more_signatures_8`, `more_signatures_9`, `more_signatures_10`, `datetime_created`, `datetime_updated`)
			
						SELECT `hash`, `whitelabel_business_account_hash`, `form_type`, `form_name`, `tier`, `onboarding_account_registration_validation_email`, `onboarding_account_registration_validation_sms`, `onboarding_your_region`, `onboarding_business_category`, `onboarding_business_description`, `onboarding_business_key_words`, `onboarding_years_doing_business`, `onboarding_business_accept_credit_card`, `onboarding_average_transaction_value`, `onboarding_first_name`, `onboarding_last_name`, `onboarding_personal_emailaddress`, `onboarding_personal_telephone_number`, `onboarding_personal_street_address`, `onboarding_personal_postal_code`, `onboarding_personal_birthdate`, `onboarding_personal_social_security_number`, `onboarding_business_name`, `onboarding_business_telephone_number`, `onboarding_business_emailaddress`, `onboarding_business_url_homepage`, `onboarding_business_public_directory`, `onboarding_postfix`, `onboarding_business_type`, `onboarding_business_registered_region`, `onboarding_business_EIN`, `onboarding_business_EIN_FAQ`, `onboarding_legal_tickbox_alert_terms_of_service`, `onboarding_legal_tickbox_alert_refund_policy`, `onboarding_legal_tickbox_alert_privacy_policy`, `onboarding_identity_selfie`, `onboarding_identity_photo_id`, `onboarding_identity_photo_id_title`, `onboarding_identity_photo_id_options`, `onboarding_identity_residence`, `onboarding_identity_residence_title`, `onboarding_identity_residence_options`, `onboarding_identity_business`, `onboarding_identity_business_title`, `onboarding_identity_business_options`, `onboarding_identity_banking`, `onboarding_identity_banking_title`, `onboarding_identity_banking_options`, `onboarding_identity_tax_returns`, `onboarding_identity_tax_returns_title`, `onboarding_identity_tax_returns_options`, `onboarding_identity_processing`, `onboarding_identity_processing_title`, `onboarding_identity_processing_options`, `onboarding_owner_signature`, `onboarding_terms_of_service_url`, `onboarding_terms_of_service_text`, `onboarding_whitelabel_business_emailaddress_agents`, `onboarding_whitelabel_business_emailaddress_support`, `onboarding_whitelabel_business_emailaddress_underwriting`, `onboarding_whitelabel_business_account_hostname`, `MATCH_ AcquirerId`, `onboarding_kyc_search_personal_name`, `onboarding_kyc_search_personal_location`, `onboarding_kyc_search_business_name`, `onboarding_kyc_search_business_location`, `onboarding_kyc_search_business_url`, `onboarding_aml_ofac_sdn`, `onboarding_aml_ofac_consolidated`, `onboarding_aml_fbi`, `onboarding_aml_dea`, `onboarding_aml_interpol`, `onboarding_aml_ncmec`, `CRM_followup_STAGE_1_EMAIL_1_subject`, `CRM_followup_STAGE_1_EMAIL_1_body`, `CRM_followup_STAGE_1_EMAIL_2_subject`, `CRM_followup_STAGE_1_EMAIL_2_body`, `CRM_followup_STAGE_1_EMAIL_3_subject`, `CRM_followup_STAGE_1_EMAIL_3_body`, `CRM_followup_STAGE_1_EMAIL_4_subject`, `CRM_followup_STAGE_1_EMAIL_4_body`, `CRM_followup_STAGE_2_EMAIL_1_subject`, `CRM_followup_STAGE_2_EMAIL_1_body`, `CRM_followup_STAGE_2_EMAIL_2_subject`, `CRM_followup_STAGE_2_EMAIL_2_body`, `CRM_followup_STAGE_2_EMAIL_3_subject`, `CRM_followup_STAGE_2_EMAIL_3_body`, `CRM_followup_STAGE_2_EMAIL_4_subject`, `CRM_followup_STAGE_2_EMAIL_4_body`, `CRM_followup_STAGE_3_EMAIL_1_subject`, `CRM_followup_STAGE_3_EMAIL_1_body`, `CRM_followup_STAGE_3_EMAIL_2_subject`, `CRM_followup_STAGE_3_EMAIL_2_body`, `CRM_followup_STAGE_3_EMAIL_3_subject`, `CRM_followup_STAGE_3_EMAIL_3_body`, `CRM_followup_STAGE_3_EMAIL_4_subject`, `CRM_followup_STAGE_3_EMAIL_4_body`, `CRM_followup_STAGE_4_EMAIL_1_subject`, `CRM_followup_STAGE_4_EMAIL_1_body`, `CRM_followup_STAGE_4_EMAIL_2_subject`, `CRM_followup_STAGE_4_EMAIL_2_body`, `CRM_followup_STAGE_4_EMAIL_3_subject`, `CRM_followup_STAGE_4_EMAIL_3_body`, `CRM_followup_STAGE_4_EMAIL_4_subject`, `CRM_followup_STAGE_4_EMAIL_4_body`, `CRM_followup_STAGE_5_EMAIL_1_subject`, `CRM_followup_STAGE_5_EMAIL_1_body`, `CRM_followup_STAGE_5_EMAIL_2_subject`, `CRM_followup_STAGE_5_EMAIL_2_body`, `CRM_followup_STAGE_5_EMAIL_3_subject`, `CRM_followup_STAGE_5_EMAIL_3_body`, `CRM_followup_STAGE_5_EMAIL_4_subject`, `CRM_followup_STAGE_5_EMAIL_4_body`, `CRM_followup_STAGE_6_EMAIL_1_subject`, `CRM_followup_STAGE_6_EMAIL_1_body`, `CRM_followup_STAGE_6_EMAIL_2_subject`, `CRM_followup_STAGE_6_EMAIL_2_body`, `CRM_followup_STAGE_6_EMAIL_3_subject`, `CRM_followup_STAGE_6_EMAIL_3_body`, `CRM_followup_STAGE_6_EMAIL_4_subject`, `CRM_followup_STAGE_6_EMAIL_4_body`, `CRM_followup_STAGE_7_EMAIL_1_subject`, `CRM_followup_STAGE_7_EMAIL_1_body`, `CRM_followup_STAGE_7_EMAIL_2_subject`, `CRM_followup_STAGE_7_EMAIL_2_body`, `CRM_followup_STAGE_7_EMAIL_3_subject`, `CRM_followup_STAGE_7_EMAIL_3_body`, `CRM_followup_STAGE_7_EMAIL_4_subject`, `CRM_followup_STAGE_7_EMAIL_4_body`, `CRM_followup_STAGE_8_EMAIL_1_subject`, `CRM_followup_STAGE_8_EMAIL_1_body`, `CRM_followup_STAGE_8_EMAIL_2_subject`, `CRM_followup_STAGE_8_EMAIL_2_body`, `CRM_followup_STAGE_8_EMAIL_3_subject`, `CRM_followup_STAGE_8_EMAIL_3_body`, `CRM_followup_STAGE_8_EMAIL_4_subject`, `CRM_followup_STAGE_8_EMAIL_4_body`, `login_screen_footer_image_full_url_or_simple_text`, `onboarding_account_registration_process`, `form_type_display_queue`, `more_personal_documents_1`, `more_personal_documents_2`, `more_personal_documents_3`, `more_personal_documents_4`, `more_personal_documents_5`, `more_personal_documents_6`, `more_personal_documents_7`, `more_personal_documents_8`, `more_personal_documents_9`, `more_personal_documents_10`, `more_business_documents_1`, `more_business_documents_2`, `more_business_documents_3`, `more_business_documents_4`, `more_business_documents_5`, `more_business_documents_6`, `more_business_documents_7`, `more_business_documents_8`, `more_business_documents_9`, `more_business_documents_10`, `more_signatures_1`, `more_signatures_2`, `more_signatures_3`, `more_signatures_4`, `more_signatures_5`, `more_signatures_6`, `more_signatures_7`, `more_signatures_8`, `more_signatures_9`, `more_signatures_10`, `datetime_created`, `datetime_updated`
						
						FROM onboarding_preferences
						
						WHERE whitelabel_business_account_hash = 'DEFAULT'
						
						;";
			logger3("tmp_sql",$tmp_sql);
	
			
			$new_onboarding_preferences_id = insertTHECASHIER($tmp_sql,"intelitruth");
			logger3("new_onboarding_preferences_id",$new_onboarding_preferences_id);
			
			
			
			
			
			
			$_XXXXX_whitelabel_business_account_hash = $_XXXXX_whitelabel_business_account_hash;
			$_XXXXX_datetime_updated = datetime();
			$tmp_sql = "UPDATE onboarding_preferences 
						SET whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
						, form_name = '". addslashes($incoming_preferences_profile) ."'
						WHERE onboarding_preferences_id = '". $new_onboarding_preferences_id ."'
						;";
			logger3("WHITELABEL_tmp_sql",$tmp_sql);
			$update_results = updateTHECASHIER($tmp_sql,"intelitruth");
			logger3("WHITELABEL_tmp_sqlupdate_results",$update_results);
			
			
			
			
		}
		
		# $_XXXXX_hash = hash_me();
		# $_XXXXX_datetime = datetime_v2();
		# $_XXXXX_form_name = addslashes($incoming_preferences_profile);
		# $tmp_sql = "INSERT INTO `onboarding_preferences`
		# 			(
		# 				`onboarding_preferences_id`
		# 				, `hash`,
		# 				, `whitelabel_business_account_hash`
		# 				, `form_name`
		# 				, `datetime_created`
		# 				, `datetime_updated`
		# 			) VALUES (
		# 				,''
		# 				,'". $_XXXXX_hash."'
		# 				,'". $_XXXXX_whitelabel_business_account_hash ."'
		# 				,'". $_XXXXX_form_name ."'
		# 				,'". $_XXXXX_datetime ."'
		# 				,'". $_XXXXX_datetime ."'
		# 				
		# 			);
		# 			
		# 			";
		# logger3("tmp_sql",$tmp_sql);
		# $insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
		# logger3("insert_results",$insert_results);
	
*/
	
	
	
	
/*
	
	##############################################################
	##############################################################
	### V2
	
	if($incoming_preferences_profile) {
		$ADD_incoming_preferences_profile = "AND form_name = '". addslashes($incoming_preferences_profile) ."'"; 
	}
	
	$tmp_sql = "SELECT * 
				FROM onboarding_preferences
				WHERE whitelabel_business_account_hash = 'DEFAULT'
				$ADD_incoming_preferences_profile
				;";
	$default_onboarding_preferences_array = object_to_array_v2(readarrayTHECASHIER($tmp_sql,"intelitruth"));
	
	
	
	
	foreach($default_onboarding_preferences_array AS $default_onboarding_preferences_array_key => $default_onboarding_preferences_details) {
		
		
		
		logger3("FOREACH(default_onboarding_preferences_details[$default_onboarding_preferences_array_key])",$default_onboarding_preferences_details);
		
		$default_onboarding_preferences_details = object_to_array_v2($default_onboarding_preferences_details);
		
		
		$tmp_sql = "INSERT INTO `onboarding_preferences`
					(
						`hash`
						, `whitelabel_business_account_hash`
						, `form_type`
						, `form_name`
						, `tier`
						, `onboarding_account_registration_validation_email`
						, `onboarding_account_registration_validation_sms`
						, `onboarding_your_region`
						, `onboarding_business_category`
						, `onboarding_business_description`
						, `onboarding_business_key_words`
						, `onboarding_years_doing_business`
						, `onboarding_business_accept_credit_card`
						, `onboarding_average_transaction_value`
						, `onboarding_first_name`
						, `onboarding_last_name`
						, `onboarding_personal_emailaddress`
						, `onboarding_personal_telephone_number`
						, `onboarding_personal_street_address`
						, `onboarding_personal_postal_code`
						, `onboarding_personal_birthdate`
						, `onboarding_personal_social_security_number`
						, `onboarding_business_name`
						, `onboarding_business_telephone_number`
						, `onboarding_business_emailaddress`
						, `onboarding_business_url_homepage`
						, `onboarding_business_public_directory`
						, `onboarding_postfix`
						, `onboarding_business_type`
						, `onboarding_business_registered_region`
						, `onboarding_business_EIN`
						, `onboarding_business_EIN_FAQ`
						, `onboarding_legal_tickbox_alert_terms_of_service`
						, `onboarding_legal_tickbox_alert_refund_policy`
						, `onboarding_legal_tickbox_alert_privacy_policy`
						, `onboarding_identity_selfie`
						, `onboarding_identity_photo_id`
						, `onboarding_identity_photo_id_title`
						, `onboarding_identity_photo_id_options`
						, `onboarding_identity_residence`
						, `onboarding_identity_residence_title`
						, `onboarding_identity_residence_options`
						, `onboarding_identity_business`
						, `onboarding_identity_business_title`
						, `onboarding_identity_business_options`
						, `onboarding_identity_banking`
						, `onboarding_identity_banking_title`
						, `onboarding_identity_banking_options`
						, `onboarding_identity_tax_returns`
						, `onboarding_identity_tax_returns_title`
						, `onboarding_identity_tax_returns_options`
						, `onboarding_identity_processing`
						, `onboarding_identity_processing_title`
						, `onboarding_identity_processing_options`
						, `onboarding_owner_signature`
						, `onboarding_terms_of_service_url`
						, `onboarding_terms_of_service_text`
						, `onboarding_whitelabel_business_emailaddress_agents`
						, `onboarding_whitelabel_business_emailaddress_support`
						, `onboarding_whitelabel_business_emailaddress_underwriting`
						, `onboarding_whitelabel_business_account_hostname`
						, `MATCH_ AcquirerId`
						, `onboarding_kyc_search_personal_name`
						, `onboarding_kyc_search_personal_location`
						, `onboarding_kyc_search_business_name`
						, `onboarding_kyc_search_business_location`
						, `onboarding_kyc_search_business_url`
						, `onboarding_aml_ofac_sdn`
						, `onboarding_aml_ofac_consolidated`
						, `onboarding_aml_fbi`
						, `onboarding_aml_dea`
						, `onboarding_aml_interpol`
						, `onboarding_aml_ncmec`
						, `CRM_followup_STAGE_1_EMAIL_1_subject`
						, `CRM_followup_STAGE_1_EMAIL_1_body`
						, `CRM_followup_STAGE_1_EMAIL_2_subject`
						, `CRM_followup_STAGE_1_EMAIL_2_body`
						, `CRM_followup_STAGE_1_EMAIL_3_subject`
						, `CRM_followup_STAGE_1_EMAIL_3_body`
						, `CRM_followup_STAGE_1_EMAIL_4_subject`
						, `CRM_followup_STAGE_1_EMAIL_4_body`
						, `CRM_followup_STAGE_2_EMAIL_1_subject`
						, `CRM_followup_STAGE_2_EMAIL_1_body`
						, `CRM_followup_STAGE_2_EMAIL_2_subject`
						, `CRM_followup_STAGE_2_EMAIL_2_body`
						, `CRM_followup_STAGE_2_EMAIL_3_subject`
						, `CRM_followup_STAGE_2_EMAIL_3_body`
						, `CRM_followup_STAGE_2_EMAIL_4_subject`
						, `CRM_followup_STAGE_2_EMAIL_4_body`
						, `CRM_followup_STAGE_3_EMAIL_1_subject`
						, `CRM_followup_STAGE_3_EMAIL_1_body`
						, `CRM_followup_STAGE_3_EMAIL_2_subject`
						, `CRM_followup_STAGE_3_EMAIL_2_body`
						, `CRM_followup_STAGE_3_EMAIL_3_subject`
						, `CRM_followup_STAGE_3_EMAIL_3_body`
						, `CRM_followup_STAGE_3_EMAIL_4_subject`
						, `CRM_followup_STAGE_3_EMAIL_4_body`
						, `CRM_followup_STAGE_4_EMAIL_1_subject`
						, `CRM_followup_STAGE_4_EMAIL_1_body`
						, `CRM_followup_STAGE_4_EMAIL_2_subject`
						, `CRM_followup_STAGE_4_EMAIL_2_body`
						, `CRM_followup_STAGE_4_EMAIL_3_subject`
						, `CRM_followup_STAGE_4_EMAIL_3_body`
						, `CRM_followup_STAGE_4_EMAIL_4_subject`
						, `CRM_followup_STAGE_4_EMAIL_4_body`
						, `CRM_followup_STAGE_5_EMAIL_1_subject`
						, `CRM_followup_STAGE_5_EMAIL_1_body`
						, `CRM_followup_STAGE_5_EMAIL_2_subject`
						, `CRM_followup_STAGE_5_EMAIL_2_body`
						, `CRM_followup_STAGE_5_EMAIL_3_subject`
						, `CRM_followup_STAGE_5_EMAIL_3_body`
						, `CRM_followup_STAGE_5_EMAIL_4_subject`
						, `CRM_followup_STAGE_5_EMAIL_4_body`
						, `CRM_followup_STAGE_6_EMAIL_1_subject`
						, `CRM_followup_STAGE_6_EMAIL_1_body`
						, `CRM_followup_STAGE_6_EMAIL_2_subject`
						, `CRM_followup_STAGE_6_EMAIL_2_body`
						, `CRM_followup_STAGE_6_EMAIL_3_subject`
						, `CRM_followup_STAGE_6_EMAIL_3_body`
						, `CRM_followup_STAGE_6_EMAIL_4_subject`
						, `CRM_followup_STAGE_6_EMAIL_4_body`
						, `CRM_followup_STAGE_7_EMAIL_1_subject`
						, `CRM_followup_STAGE_7_EMAIL_1_body`
						, `CRM_followup_STAGE_7_EMAIL_2_subject`
						, `CRM_followup_STAGE_7_EMAIL_2_body`
						, `CRM_followup_STAGE_7_EMAIL_3_subject`
						, `CRM_followup_STAGE_7_EMAIL_3_body`
						, `CRM_followup_STAGE_7_EMAIL_4_subject`
						, `CRM_followup_STAGE_7_EMAIL_4_body`
						, `CRM_followup_STAGE_8_EMAIL_1_subject`
						, `CRM_followup_STAGE_8_EMAIL_1_body`
						, `CRM_followup_STAGE_8_EMAIL_2_subject`
						, `CRM_followup_STAGE_8_EMAIL_2_body`
						, `CRM_followup_STAGE_8_EMAIL_3_subject`
						, `CRM_followup_STAGE_8_EMAIL_3_body`
						, `CRM_followup_STAGE_8_EMAIL_4_subject`
						, `CRM_followup_STAGE_8_EMAIL_4_body`
						, `login_screen_footer_image_full_url_or_simple_text`
						, `onboarding_account_registration_process`
						, `form_type_display_queue`
						, `more_personal_documents_1`
						, `more_personal_documents_2`
						, `more_personal_documents_3`
						, `more_personal_documents_4`
						, `more_personal_documents_5`
						, `more_personal_documents_6`
						, `more_personal_documents_7`
						, `more_personal_documents_8`
						, `more_personal_documents_9`
						, `more_personal_documents_10`
						, `more_business_documents_1`
						, `more_business_documents_2`
						, `more_business_documents_3`
						, `more_business_documents_4`
						, `more_business_documents_5`
						, `more_business_documents_6`
						, `more_business_documents_7`
						, `more_business_documents_8`
						, `more_business_documents_9`
						, `more_business_documents_10`
						, `more_signatures_1`
						, `more_signatures_2`
						, `more_signatures_3`
						, `more_signatures_4`
						, `more_signatures_5`
						, `more_signatures_6`
						, `more_signatures_7`
						, `more_signatures_8`
						, `more_signatures_9`
						, `more_signatures_10`
						, `datetime_created`
						, `datetime_updated`
					)
		
					SELECT 
						`hash`
						, `whitelabel_business_account_hash`
						, `form_type`
						, `form_name`
						, `tier`
						, `onboarding_account_registration_validation_email`
						, `onboarding_account_registration_validation_sms`
						, `onboarding_your_region`
						, `onboarding_business_category`
						, `onboarding_business_description`
						, `onboarding_business_key_words`
						, `onboarding_years_doing_business`
						, `onboarding_business_accept_credit_card`
						, `onboarding_average_transaction_value`
						, `onboarding_first_name`
						, `onboarding_last_name`
						, `onboarding_personal_emailaddress`
						, `onboarding_personal_telephone_number`
						, `onboarding_personal_street_address`
						, `onboarding_personal_postal_code`
						, `onboarding_personal_birthdate`
						, `onboarding_personal_social_security_number`
						, `onboarding_business_name`
						, `onboarding_business_telephone_number`
						, `onboarding_business_emailaddress`
						, `onboarding_business_url_homepage`
						, `onboarding_business_public_directory`
						, `onboarding_postfix`
						, `onboarding_business_type`
						, `onboarding_business_registered_region`
						, `onboarding_business_EIN`
						, `onboarding_business_EIN_FAQ`
						, `onboarding_legal_tickbox_alert_terms_of_service`
						, `onboarding_legal_tickbox_alert_refund_policy`
						, `onboarding_legal_tickbox_alert_privacy_policy`
						, `onboarding_identity_selfie`
						, `onboarding_identity_photo_id`
						, `onboarding_identity_photo_id_title`
						, `onboarding_identity_photo_id_options`
						, `onboarding_identity_residence`
						, `onboarding_identity_residence_title`
						, `onboarding_identity_residence_options`
						, `onboarding_identity_business`
						, `onboarding_identity_business_title`
						, `onboarding_identity_business_options`
						, `onboarding_identity_banking`
						, `onboarding_identity_banking_title`
						, `onboarding_identity_banking_options`
						, `onboarding_identity_tax_returns`
						, `onboarding_identity_tax_returns_title`
						, `onboarding_identity_tax_returns_options`
						, `onboarding_identity_processing`
						, `onboarding_identity_processing_title`
						, `onboarding_identity_processing_options`
						, `onboarding_owner_signature`
						, `onboarding_terms_of_service_url`
						, `onboarding_terms_of_service_text`
						, `onboarding_whitelabel_business_emailaddress_agents`
						, `onboarding_whitelabel_business_emailaddress_support`
						, `onboarding_whitelabel_business_emailaddress_underwriting`
						, `onboarding_whitelabel_business_account_hostname`
						, `MATCH_ AcquirerId`
						, `onboarding_kyc_search_personal_name`
						, `onboarding_kyc_search_personal_location`
						, `onboarding_kyc_search_business_name`
						, `onboarding_kyc_search_business_location`
						, `onboarding_kyc_search_business_url`
						, `onboarding_aml_ofac_sdn`
						, `onboarding_aml_ofac_consolidated`
						, `onboarding_aml_fbi`
						, `onboarding_aml_dea`
						, `onboarding_aml_interpol`
						, `onboarding_aml_ncmec`
						, `CRM_followup_STAGE_1_EMAIL_1_subject`
						, `CRM_followup_STAGE_1_EMAIL_1_body`
						, `CRM_followup_STAGE_1_EMAIL_2_subject`
						, `CRM_followup_STAGE_1_EMAIL_2_body`
						, `CRM_followup_STAGE_1_EMAIL_3_subject`
						, `CRM_followup_STAGE_1_EMAIL_3_body`
						, `CRM_followup_STAGE_1_EMAIL_4_subject`
						, `CRM_followup_STAGE_1_EMAIL_4_body`
						, `CRM_followup_STAGE_2_EMAIL_1_subject`
						, `CRM_followup_STAGE_2_EMAIL_1_body`
						, `CRM_followup_STAGE_2_EMAIL_2_subject`
						, `CRM_followup_STAGE_2_EMAIL_2_body`
						, `CRM_followup_STAGE_2_EMAIL_3_subject`
						, `CRM_followup_STAGE_2_EMAIL_3_body`
						, `CRM_followup_STAGE_2_EMAIL_4_subject`
						, `CRM_followup_STAGE_2_EMAIL_4_body`
						, `CRM_followup_STAGE_3_EMAIL_1_subject`
						, `CRM_followup_STAGE_3_EMAIL_1_body`
						, `CRM_followup_STAGE_3_EMAIL_2_subject`
						, `CRM_followup_STAGE_3_EMAIL_2_body`
						, `CRM_followup_STAGE_3_EMAIL_3_subject`
						, `CRM_followup_STAGE_3_EMAIL_3_body`
						, `CRM_followup_STAGE_3_EMAIL_4_subject`
						, `CRM_followup_STAGE_3_EMAIL_4_body`
						, `CRM_followup_STAGE_4_EMAIL_1_subject`
						, `CRM_followup_STAGE_4_EMAIL_1_body`
						, `CRM_followup_STAGE_4_EMAIL_2_subject`
						, `CRM_followup_STAGE_4_EMAIL_2_body`
						, `CRM_followup_STAGE_4_EMAIL_3_subject`
						, `CRM_followup_STAGE_4_EMAIL_3_body`
						, `CRM_followup_STAGE_4_EMAIL_4_subject`
						, `CRM_followup_STAGE_4_EMAIL_4_body`
						, `CRM_followup_STAGE_5_EMAIL_1_subject`
						, `CRM_followup_STAGE_5_EMAIL_1_body`
						, `CRM_followup_STAGE_5_EMAIL_2_subject`
						, `CRM_followup_STAGE_5_EMAIL_2_body`
						, `CRM_followup_STAGE_5_EMAIL_3_subject`
						, `CRM_followup_STAGE_5_EMAIL_3_body`
						, `CRM_followup_STAGE_5_EMAIL_4_subject`
						, `CRM_followup_STAGE_5_EMAIL_4_body`
						, `CRM_followup_STAGE_6_EMAIL_1_subject`
						, `CRM_followup_STAGE_6_EMAIL_1_body`
						, `CRM_followup_STAGE_6_EMAIL_2_subject`
						, `CRM_followup_STAGE_6_EMAIL_2_body`
						, `CRM_followup_STAGE_6_EMAIL_3_subject`
						, `CRM_followup_STAGE_6_EMAIL_3_body`
						, `CRM_followup_STAGE_6_EMAIL_4_subject`
						, `CRM_followup_STAGE_6_EMAIL_4_body`
						, `CRM_followup_STAGE_7_EMAIL_1_subject`
						, `CRM_followup_STAGE_7_EMAIL_1_body`
						, `CRM_followup_STAGE_7_EMAIL_2_subject`
						, `CRM_followup_STAGE_7_EMAIL_2_body`
						, `CRM_followup_STAGE_7_EMAIL_3_subject`
						, `CRM_followup_STAGE_7_EMAIL_3_body`
						, `CRM_followup_STAGE_7_EMAIL_4_subject`
						, `CRM_followup_STAGE_7_EMAIL_4_body`
						, `CRM_followup_STAGE_8_EMAIL_1_subject`
						, `CRM_followup_STAGE_8_EMAIL_1_body`
						, `CRM_followup_STAGE_8_EMAIL_2_subject`
						, `CRM_followup_STAGE_8_EMAIL_2_body`
						, `CRM_followup_STAGE_8_EMAIL_3_subject`
						, `CRM_followup_STAGE_8_EMAIL_3_body`
						, `CRM_followup_STAGE_8_EMAIL_4_subject`
						, `CRM_followup_STAGE_8_EMAIL_4_body`
						, `login_screen_footer_image_full_url_or_simple_text`
						, `onboarding_account_registration_process`
						, `form_type_display_queue`
						, `more_personal_documents_1`
						, `more_personal_documents_2`
						, `more_personal_documents_3`
						, `more_personal_documents_4`
						, `more_personal_documents_5`
						, `more_personal_documents_6`
						, `more_personal_documents_7`
						, `more_personal_documents_8`
						, `more_personal_documents_9`
						, `more_personal_documents_10`
						, `more_business_documents_1`
						, `more_business_documents_2`
						, `more_business_documents_3`
						, `more_business_documents_4`
						, `more_business_documents_5`
						, `more_business_documents_6`
						, `more_business_documents_7`
						, `more_business_documents_8`
						, `more_business_documents_9`
						, `more_business_documents_10`
						, `more_signatures_1`
						, `more_signatures_2`
						, `more_signatures_3`
						, `more_signatures_4`
						, `more_signatures_5`
						, `more_signatures_6`
						, `more_signatures_7`
						, `more_signatures_8`
						, `more_signatures_9`
						, `more_signatures_10`
						, `datetime_created`
						, `datetime_updated`
					
					FROM onboarding_preferences
					
					WHERE whitelabel_business_account_hash = 'DEFAULT'
					
					AND form_name = '". addslashes($default_onboarding_preferences_details['form_name']) ."'
					
					;";
		logger3("tmp_sql",$tmp_sql);

		
		$new_onboarding_preferences_id = insertTHECASHIER($tmp_sql,"intelitruth");
		logger3("new_onboarding_preferences_id",$new_onboarding_preferences_id);
		
		
		
		$_XXXXX_whitelabel_business_account_hash = $_XXXXX_whitelabel_business_account_hash;
		$_XXXXX_datetime = datetime();
		$_XXXXX_hash = hash_me();
		$tmp_sql = "UPDATE onboarding_preferences 
				SET hash = '". $_XXXXX_hash ."'
				, whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
				, datetime_created = '". $_XXXXX_datetime ."'
				, datetime_updated = '". $_XXXXX_datetime ."'
				WHERE onboarding_preferences_id = '". $new_onboarding_preferences_id ."'
				;";
		logger3("WHITELABEL_tmp_sql",$tmp_sql);
		$update_results = updateTHECASHIER($tmp_sql,"intelitruth");
		logger3("WHITELABEL_tmp_sqlupdate_results",$update_results);
	}
	
*/	
	
	
	
	##############################################################
	##############################################################
	### V3
	
	if(!$incoming_preferences_profile) $incoming_preferences_profile = "DEFAULT";
	global $master_config_DEFAULT_ONBOARDING_TIERS;

	
	$tmp_sql = "SELECT * 
				FROM onboarding_preferences
				WHERE whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
				AND form_name = '". addslashes($incoming_preferences_profile) ."'
				ORDER BY datetime_created DESC
				LIMIT 1;";
	logger3("999-IEW_create_new_intelitruth_preferences_profile(1-tmp_sql)",$tmp_sql);
	
	$onboarding_preferences_array = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	logger3("999-IEW_create_new_intelitruth_preferences_profile(onboarding_preferences_array)",$onboarding_preferences_array);
	
	
	
	if(!$onboarding_preferences_array['hash']) {
		
		$DEFAULT_incoming_preferences_profile = $incoming_preferences_profile;
		
		if(
			($DEFAULT_incoming_preferences_profile != "PERSONAL")
			AND ($DEFAULT_incoming_preferences_profile != "BUSINESS")
			AND ($DEFAULT_incoming_preferences_profile != "New Account (Personal)")
			AND ($DEFAULT_incoming_preferences_profile != "New Account (Business)")
			AND ($DEFAULT_incoming_preferences_profile != "PERSONAL:60")
			AND ($DEFAULT_incoming_preferences_profile != "PERSONAL:80")
			AND ($DEFAULT_incoming_preferences_profile != "PERSONAL:100")
			AND ($DEFAULT_incoming_preferences_profile != "BUSINESS:60")
			AND ($DEFAULT_incoming_preferences_profile != "BUSINESS:80")
			AND ($DEFAULT_incoming_preferences_profile != "BUSINESS:100")
			AND ($DEFAULT_incoming_preferences_profile != "Individual Account")
			AND ($DEFAULT_incoming_preferences_profile != "Corporate Account")
			AND ($DEFAULT_incoming_preferences_profile != "Corporate Partner")
			AND ($DEFAULT_incoming_preferences_profile != "HR/Employee")
			
		) {
			$DEFAULT_incoming_preferences_profile = "DEFAULT";
		}
		
		$tmp_sql = "INSERT INTO `onboarding_preferences`
					(
						`hash`
						, `whitelabel_business_account_hash`
						, `form_type`
						, `form_name`
						, `tier`
						, `onboarding_face_biometrics_validate_selfie`
						, `onboarding_face_biometrics_validate_photo_id`
						, `onboarding_face_biometrics_match_selfie_vs_photo_id`
						, `onboarding_account_registration_validation_email`
						, `onboarding_account_registration_validation_sms`
						, `onboarding_your_region`
						, `onboarding_business_category`
						, `onboarding_business_description`
						, `onboarding_business_key_words`
						, `onboarding_years_doing_business`
						, `onboarding_business_accept_credit_card`
						, `onboarding_average_transaction_value`
						, `onboarding_first_name`
						, `onboarding_middle_name`
						, `onboarding_last_name`
						, `onboarding_personal_emailaddress`
						, `onboarding_personal_telephone_number`
						, `onboarding_personal_street_address`
						, `onboarding_personal_street_address_2`
						, `onboarding_personal_city`
						, `onboarding_personal_state`
						, `onboarding_personal_postal_code`
						, `onboarding_personal_country_iso3`
						, `onboarding_personal_birthdate`
						, `onboarding_personal_gender`
						, `onboarding_personal_minimum_age`
						, `onboarding_personal_social_security_number`
						, `onboarding_business_name`
						, `onboarding_business_telephone_number`
						, `onboarding_business_emailaddress`
						, `onboarding_business_url_homepage`
						, `onboarding_business_public_directory`
						, `onboarding_postfix`
						, `onboarding_business_type`
						, `onboarding_business_registered_region`
						, `onboarding_business_registered_country_iso3`
						, `onboarding_business_mailing_street_1`
						, `onboarding_business_mailing_street_2`
						, `onboarding_business_mailing_city`
						, `onboarding_business_mailing_state`
						, `onboarding_business_mailing_postal_code`
						, `onboarding_business_mailing_country_iso3`
						, `onboarding_business_EIN`
						, `onboarding_business_EIN_FAQ`
						, `onboarding_legal_tickbox_alert_terms_of_service`
						, `onboarding_legal_tickbox_alert_refund_policy`
						, `onboarding_legal_tickbox_alert_privacy_policy`
						, `onboarding_identity_selfie`
						, `onboarding_identity_photo_id`
						, `onboarding_identity_photo_id_title`
						, `onboarding_identity_photo_id_options`
						, `onboarding_identity_residence`
						, `onboarding_identity_residence_title`
						, `onboarding_identity_residence_options`
						, `onboarding_identity_business`
						, `onboarding_identity_business_title`
						, `onboarding_identity_business_options`
						, `onboarding_identity_banking`
						, `onboarding_identity_banking_title`
						, `onboarding_identity_banking_options`
						, `onboarding_identity_tax_returns`
						, `onboarding_identity_tax_returns_title`
						, `onboarding_identity_tax_returns_options`
						, `onboarding_identity_processing`
						, `onboarding_identity_processing_title`
						, `onboarding_identity_processing_options`
						, `onboarding_owner_signature`
						, `onboarding_terms_of_service_url`
						, `onboarding_terms_of_service_text`
						, `onboarding_whitelabel_business_emailaddress_agents`
						, `onboarding_whitelabel_business_emailaddress_support`
						, `onboarding_whitelabel_business_emailaddress_underwriting`
						, `onboarding_whitelabel_business_account_hostname`
						, `MATCH_ AcquirerId`
						, `onboarding_kyc_search_personal_name`
						, `onboarding_kyc_search_personal_location`
						, `onboarding_kyc_search_business_name`
						, `onboarding_kyc_search_business_location`
						, `onboarding_kyc_search_business_url`
						, `onboarding_aml_ofac_sdn`
						, `onboarding_aml_ofac_consolidated`
						, `onboarding_aml_fbi`
						, `onboarding_aml_dea`
						, `onboarding_aml_interpol`
						, `onboarding_aml_ncmec`
						, `CRM_followup_STAGE_1_EMAIL_1_subject`
						, `CRM_followup_STAGE_1_EMAIL_1_body`
						, `CRM_followup_STAGE_1_EMAIL_2_subject`
						, `CRM_followup_STAGE_1_EMAIL_2_body`
						, `CRM_followup_STAGE_1_EMAIL_3_subject`
						, `CRM_followup_STAGE_1_EMAIL_3_body`
						, `CRM_followup_STAGE_1_EMAIL_4_subject`
						, `CRM_followup_STAGE_1_EMAIL_4_body`
						, `CRM_followup_STAGE_2_EMAIL_1_subject`
						, `CRM_followup_STAGE_2_EMAIL_1_body`
						, `CRM_followup_STAGE_2_EMAIL_2_subject`
						, `CRM_followup_STAGE_2_EMAIL_2_body`
						, `CRM_followup_STAGE_2_EMAIL_3_subject`
						, `CRM_followup_STAGE_2_EMAIL_3_body`
						, `CRM_followup_STAGE_2_EMAIL_4_subject`
						, `CRM_followup_STAGE_2_EMAIL_4_body`
						, `CRM_followup_STAGE_3_EMAIL_1_subject`
						, `CRM_followup_STAGE_3_EMAIL_1_body`
						, `CRM_followup_STAGE_3_EMAIL_2_subject`
						, `CRM_followup_STAGE_3_EMAIL_2_body`
						, `CRM_followup_STAGE_3_EMAIL_3_subject`
						, `CRM_followup_STAGE_3_EMAIL_3_body`
						, `CRM_followup_STAGE_3_EMAIL_4_subject`
						, `CRM_followup_STAGE_3_EMAIL_4_body`
						, `CRM_followup_STAGE_4_EMAIL_1_subject`
						, `CRM_followup_STAGE_4_EMAIL_1_body`
						, `CRM_followup_STAGE_4_EMAIL_2_subject`
						, `CRM_followup_STAGE_4_EMAIL_2_body`
						, `CRM_followup_STAGE_4_EMAIL_3_subject`
						, `CRM_followup_STAGE_4_EMAIL_3_body`
						, `CRM_followup_STAGE_4_EMAIL_4_subject`
						, `CRM_followup_STAGE_4_EMAIL_4_body`
						, `CRM_followup_STAGE_5_EMAIL_1_subject`
						, `CRM_followup_STAGE_5_EMAIL_1_body`
						, `CRM_followup_STAGE_5_EMAIL_2_subject`
						, `CRM_followup_STAGE_5_EMAIL_2_body`
						, `CRM_followup_STAGE_5_EMAIL_3_subject`
						, `CRM_followup_STAGE_5_EMAIL_3_body`
						, `CRM_followup_STAGE_5_EMAIL_4_subject`
						, `CRM_followup_STAGE_5_EMAIL_4_body`
						, `CRM_followup_STAGE_6_EMAIL_1_subject`
						, `CRM_followup_STAGE_6_EMAIL_1_body`
						, `CRM_followup_STAGE_6_EMAIL_2_subject`
						, `CRM_followup_STAGE_6_EMAIL_2_body`
						, `CRM_followup_STAGE_6_EMAIL_3_subject`
						, `CRM_followup_STAGE_6_EMAIL_3_body`
						, `CRM_followup_STAGE_6_EMAIL_4_subject`
						, `CRM_followup_STAGE_6_EMAIL_4_body`
						, `CRM_followup_STAGE_7_EMAIL_1_subject`
						, `CRM_followup_STAGE_7_EMAIL_1_body`
						, `CRM_followup_STAGE_7_EMAIL_2_subject`
						, `CRM_followup_STAGE_7_EMAIL_2_body`
						, `CRM_followup_STAGE_7_EMAIL_3_subject`
						, `CRM_followup_STAGE_7_EMAIL_3_body`
						, `CRM_followup_STAGE_7_EMAIL_4_subject`
						, `CRM_followup_STAGE_7_EMAIL_4_body`
						, `CRM_followup_STAGE_8_EMAIL_1_subject`
						, `CRM_followup_STAGE_8_EMAIL_1_body`
						, `CRM_followup_STAGE_8_EMAIL_2_subject`
						, `CRM_followup_STAGE_8_EMAIL_2_body`
						, `CRM_followup_STAGE_8_EMAIL_3_subject`
						, `CRM_followup_STAGE_8_EMAIL_3_body`
						, `CRM_followup_STAGE_8_EMAIL_4_subject`
						, `CRM_followup_STAGE_8_EMAIL_4_body`
						, `login_screen_footer_image_full_url_or_simple_text`
						, `onboarding_account_registration_process`
						, `form_type_display_queue`
						, `form_logo_header`
						, `form_logo_icon`
						, `login_registration_instructional_text`
						, `more_personal_documents_1`
						, `more_personal_documents_2`
						, `more_personal_documents_3`
						, `more_personal_documents_4`
						, `more_personal_documents_5`
						, `more_personal_documents_6`
						, `more_personal_documents_7`
						, `more_personal_documents_8`
						, `more_personal_documents_9`
						, `more_personal_documents_10`
						, `more_business_documents_1`
						, `more_business_documents_2`
						, `more_business_documents_3`
						, `more_business_documents_4`
						, `more_business_documents_5`
						, `more_business_documents_6`
						, `more_business_documents_7`
						, `more_business_documents_8`
						, `more_business_documents_9`
						, `more_business_documents_10`
						, `more_signatures_1`
						, `more_signatures_2`
						, `more_signatures_3`
						, `more_signatures_4`
						, `more_signatures_5`
						, `more_signatures_6`
						, `more_signatures_7`
						, `more_signatures_8`
						, `more_signatures_9`
						, `more_signatures_10`
						, `post_onboarding_submission_status`
						, `post_onboarding_editable_profile`
						, `onboarding_cancel_exit_url`
						, `onboarding_cancel_exit_url_add_member_id`
						, `onboarding_post_submission_url`
						, `onboarding_post_submission_url_add_member_id`
						, `preference_name`
						, `datetime_created`
						, `datetime_updated`
					)
		
					SELECT 
						`hash`
						, `whitelabel_business_account_hash`
						, `form_type`
						, `form_name`
						, `tier`
						, `onboarding_face_biometrics_validate_selfie`
						, `onboarding_face_biometrics_validate_photo_id`
						, `onboarding_face_biometrics_match_selfie_vs_photo_id`
						, `onboarding_account_registration_validation_email`
						, `onboarding_account_registration_validation_sms`
						, `onboarding_your_region`
						, `onboarding_business_category`
						, `onboarding_business_description`
						, `onboarding_business_key_words`
						, `onboarding_years_doing_business`
						, `onboarding_business_accept_credit_card`
						, `onboarding_average_transaction_value`
						, `onboarding_first_name`
						, `onboarding_middle_name`
						, `onboarding_last_name`
						, `onboarding_personal_emailaddress`
						, `onboarding_personal_telephone_number`
						, `onboarding_personal_street_address`
						, `onboarding_personal_street_address_2`
						, `onboarding_personal_city`
						, `onboarding_personal_state`
						, `onboarding_personal_postal_code`
						, `onboarding_personal_country_iso3`
						, `onboarding_personal_birthdate`
						, `onboarding_personal_gender`
						, `onboarding_personal_minimum_age`
						, `onboarding_personal_social_security_number`
						, `onboarding_business_name`
						, `onboarding_business_telephone_number`
						, `onboarding_business_emailaddress`
						, `onboarding_business_url_homepage`
						, `onboarding_business_public_directory`
						, `onboarding_postfix`
						, `onboarding_business_type`
						, `onboarding_business_registered_region`
						, `onboarding_business_registered_country_iso3`
						, `onboarding_business_mailing_street_1`
						, `onboarding_business_mailing_street_2`
						, `onboarding_business_mailing_city`
						, `onboarding_business_mailing_state`
						, `onboarding_business_mailing_postal_code`
						, `onboarding_business_mailing_country_iso3`
						, `onboarding_business_EIN`
						, `onboarding_business_EIN_FAQ`
						, `onboarding_legal_tickbox_alert_terms_of_service`
						, `onboarding_legal_tickbox_alert_refund_policy`
						, `onboarding_legal_tickbox_alert_privacy_policy`
						, `onboarding_identity_selfie`
						, `onboarding_identity_photo_id`
						, `onboarding_identity_photo_id_title`
						, `onboarding_identity_photo_id_options`
						, `onboarding_identity_residence`
						, `onboarding_identity_residence_title`
						, `onboarding_identity_residence_options`
						, `onboarding_identity_business`
						, `onboarding_identity_business_title`
						, `onboarding_identity_business_options`
						, `onboarding_identity_banking`
						, `onboarding_identity_banking_title`
						, `onboarding_identity_banking_options`
						, `onboarding_identity_tax_returns`
						, `onboarding_identity_tax_returns_title`
						, `onboarding_identity_tax_returns_options`
						, `onboarding_identity_processing`
						, `onboarding_identity_processing_title`
						, `onboarding_identity_processing_options`
						, `onboarding_owner_signature`
						, `onboarding_terms_of_service_url`
						, `onboarding_terms_of_service_text`
						, `onboarding_whitelabel_business_emailaddress_agents`
						, `onboarding_whitelabel_business_emailaddress_support`
						, `onboarding_whitelabel_business_emailaddress_underwriting`
						, `onboarding_whitelabel_business_account_hostname`
						, `MATCH_ AcquirerId`
						, `onboarding_kyc_search_personal_name`
						, `onboarding_kyc_search_personal_location`
						, `onboarding_kyc_search_business_name`
						, `onboarding_kyc_search_business_location`
						, `onboarding_kyc_search_business_url`
						, `onboarding_aml_ofac_sdn`
						, `onboarding_aml_ofac_consolidated`
						, `onboarding_aml_fbi`
						, `onboarding_aml_dea`
						, `onboarding_aml_interpol`
						, `onboarding_aml_ncmec`
						, `CRM_followup_STAGE_1_EMAIL_1_subject`
						, `CRM_followup_STAGE_1_EMAIL_1_body`
						, `CRM_followup_STAGE_1_EMAIL_2_subject`
						, `CRM_followup_STAGE_1_EMAIL_2_body`
						, `CRM_followup_STAGE_1_EMAIL_3_subject`
						, `CRM_followup_STAGE_1_EMAIL_3_body`
						, `CRM_followup_STAGE_1_EMAIL_4_subject`
						, `CRM_followup_STAGE_1_EMAIL_4_body`
						, `CRM_followup_STAGE_2_EMAIL_1_subject`
						, `CRM_followup_STAGE_2_EMAIL_1_body`
						, `CRM_followup_STAGE_2_EMAIL_2_subject`
						, `CRM_followup_STAGE_2_EMAIL_2_body`
						, `CRM_followup_STAGE_2_EMAIL_3_subject`
						, `CRM_followup_STAGE_2_EMAIL_3_body`
						, `CRM_followup_STAGE_2_EMAIL_4_subject`
						, `CRM_followup_STAGE_2_EMAIL_4_body`
						, `CRM_followup_STAGE_3_EMAIL_1_subject`
						, `CRM_followup_STAGE_3_EMAIL_1_body`
						, `CRM_followup_STAGE_3_EMAIL_2_subject`
						, `CRM_followup_STAGE_3_EMAIL_2_body`
						, `CRM_followup_STAGE_3_EMAIL_3_subject`
						, `CRM_followup_STAGE_3_EMAIL_3_body`
						, `CRM_followup_STAGE_3_EMAIL_4_subject`
						, `CRM_followup_STAGE_3_EMAIL_4_body`
						, `CRM_followup_STAGE_4_EMAIL_1_subject`
						, `CRM_followup_STAGE_4_EMAIL_1_body`
						, `CRM_followup_STAGE_4_EMAIL_2_subject`
						, `CRM_followup_STAGE_4_EMAIL_2_body`
						, `CRM_followup_STAGE_4_EMAIL_3_subject`
						, `CRM_followup_STAGE_4_EMAIL_3_body`
						, `CRM_followup_STAGE_4_EMAIL_4_subject`
						, `CRM_followup_STAGE_4_EMAIL_4_body`
						, `CRM_followup_STAGE_5_EMAIL_1_subject`
						, `CRM_followup_STAGE_5_EMAIL_1_body`
						, `CRM_followup_STAGE_5_EMAIL_2_subject`
						, `CRM_followup_STAGE_5_EMAIL_2_body`
						, `CRM_followup_STAGE_5_EMAIL_3_subject`
						, `CRM_followup_STAGE_5_EMAIL_3_body`
						, `CRM_followup_STAGE_5_EMAIL_4_subject`
						, `CRM_followup_STAGE_5_EMAIL_4_body`
						, `CRM_followup_STAGE_6_EMAIL_1_subject`
						, `CRM_followup_STAGE_6_EMAIL_1_body`
						, `CRM_followup_STAGE_6_EMAIL_2_subject`
						, `CRM_followup_STAGE_6_EMAIL_2_body`
						, `CRM_followup_STAGE_6_EMAIL_3_subject`
						, `CRM_followup_STAGE_6_EMAIL_3_body`
						, `CRM_followup_STAGE_6_EMAIL_4_subject`
						, `CRM_followup_STAGE_6_EMAIL_4_body`
						, `CRM_followup_STAGE_7_EMAIL_1_subject`
						, `CRM_followup_STAGE_7_EMAIL_1_body`
						, `CRM_followup_STAGE_7_EMAIL_2_subject`
						, `CRM_followup_STAGE_7_EMAIL_2_body`
						, `CRM_followup_STAGE_7_EMAIL_3_subject`
						, `CRM_followup_STAGE_7_EMAIL_3_body`
						, `CRM_followup_STAGE_7_EMAIL_4_subject`
						, `CRM_followup_STAGE_7_EMAIL_4_body`
						, `CRM_followup_STAGE_8_EMAIL_1_subject`
						, `CRM_followup_STAGE_8_EMAIL_1_body`
						, `CRM_followup_STAGE_8_EMAIL_2_subject`
						, `CRM_followup_STAGE_8_EMAIL_2_body`
						, `CRM_followup_STAGE_8_EMAIL_3_subject`
						, `CRM_followup_STAGE_8_EMAIL_3_body`
						, `CRM_followup_STAGE_8_EMAIL_4_subject`
						, `CRM_followup_STAGE_8_EMAIL_4_body`
						, `login_screen_footer_image_full_url_or_simple_text`
						, `onboarding_account_registration_process`
						, `form_type_display_queue`
						, `form_logo_header`
						, `form_logo_icon`
						, `login_registration_instructional_text`
						, `more_personal_documents_1`
						, `more_personal_documents_2`
						, `more_personal_documents_3`
						, `more_personal_documents_4`
						, `more_personal_documents_5`
						, `more_personal_documents_6`
						, `more_personal_documents_7`
						, `more_personal_documents_8`
						, `more_personal_documents_9`
						, `more_personal_documents_10`
						, `more_business_documents_1`
						, `more_business_documents_2`
						, `more_business_documents_3`
						, `more_business_documents_4`
						, `more_business_documents_5`
						, `more_business_documents_6`
						, `more_business_documents_7`
						, `more_business_documents_8`
						, `more_business_documents_9`
						, `more_business_documents_10`
						, `more_signatures_1`
						, `more_signatures_2`
						, `more_signatures_3`
						, `more_signatures_4`
						, `more_signatures_5`
						, `more_signatures_6`
						, `more_signatures_7`
						, `more_signatures_8`
						, `more_signatures_9`
						, `more_signatures_10`
						, `post_onboarding_submission_status`
						, `post_onboarding_editable_profile`
						, `onboarding_cancel_exit_url`
						, `onboarding_cancel_exit_url_add_member_id`
						, `onboarding_post_submission_url`
						, `onboarding_post_submission_url_add_member_id`
						, `preference_name`
						, `datetime_created`
						, `datetime_updated`
					
					FROM onboarding_preferences
					
					WHERE whitelabel_business_account_hash = '". $master_config_DEFAULT_ONBOARDING_TIERS ."'
					
					AND form_name = '". $DEFAULT_incoming_preferences_profile ."'
					
					;";
					
		logger3("999-IEW_create_new_intelitruth_preferences_profile(2-tmp_sql)",$tmp_sql);

		
		$new_onboarding_preferences_id = insertTHECASHIER($tmp_sql,"intelitruth");
		logger3("999-new_onboarding_preferences_id",$new_onboarding_preferences_id);
		
		
		
		$_XXXXX_datetime_updated = datetime();
		$_XXXXX_hash = hash_me();
		$tmp_sql = "UPDATE onboarding_preferences 
				SET hash = '". $_XXXXX_hash ."'
				, whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
				, form_name = '". addslashes($incoming_preferences_profile) ."'
				, datetime_updated = '". $_XXXXX_datetime_updated ."'
				WHERE onboarding_preferences_id = '". $new_onboarding_preferences_id ."'
				;";
		logger3("IEW_create_new_intelitruth_preferences_profile(3-tmp_sql)",$tmp_sql);
		$update_results = updateTHECASHIER($tmp_sql,"intelitruth");
		logger3("999-IEW_create_new_intelitruth_preferences_profile() ",$update_results);
	
	}

}
	


function convert_complex_unicode_urlencoded_string_to_html($coded_string) {




		return utf8_encode($coded_string);





	# $business_description_str_ireplace = str_ireplace("%u", "&#x", $coded_string); 
	# test("1. business_description_str_ireplace",$business_description_str_ireplace);
	# 
	# //$business_description_str_ireplace = str_ireplace("&#x", "%u", $business_description_str_ireplace); 
	# //test("1.1 business_description_str_ireplace",$business_description_str_ireplace);
	# 
	# 
	# 
	# 
	# $business_description_str_ireplace = str_ireplace("+", "&plus;", $business_description_str_ireplace); 
	# test("2. business_description_str_ireplace",$business_description_str_ireplace);
	# 
	# $business_description_urldecode = urldecode($business_description_str_ireplace); 
	# test("business_description_urldecode",$business_description_urldecode);
	# 
	# $business_description_str_ireplace = str_ireplace("&plus;", "+", $business_description_urldecode); 
	# test("3. business_description_str_ireplace",$business_description_str_ireplace);
	# 
	# 
	# 
	# //$business_description_str_ireplace = str_ireplace("  ", " ", $business_description_str_ireplace); 
	# //test("4. business_description_str_ireplace",$business_description_str_ireplace);
	# 
	# 
	# return $business_description_str_ireplace;
	
	
	
	# $coded_string = str_ireplace("%20", " ", $coded_string); 
	# logger3("coded_string",$coded_string);
	# 
	# $coded_string = str_ireplace("%3A", ":", $coded_string); 
	# logger3("coded_string",$coded_string);
	# 
	# $coded_string = str_ireplace("%u2605", "☆", $coded_string); 
	# logger3("coded_string",$coded_string);
	# 
	# $coded_string = str_ireplace("%u2606", "★", $coded_string); 
	# logger3("coded_string",$coded_string);
	# 
	# 
	# return $coded_string;
	
	
	
	
	
}



function microsoft_azure_face_detect($path_to_image="",$microsoft_azure_face_key="") {
	
	logger3("1- microsoft_azure_face_detect(path_to_image)",$path_to_image);
	logger3("1- microsoft_azure_face_detect(microsoft_azure_face_key)",$microsoft_azure_face_key);
	
	if(!$path_to_image) return false;
	//if(!$microsoft_azure_face_key) $microsoft_azure_face_key = "da3e4f788f454fa083050c414fb8dac5";
	//if(!$microsoft_azure_face_key) $microsoft_azure_face_key = "3f336564a27845b5ae6ba16357559c4a";
	
	
	//test("-2- path_to_image",$path_to_image);
	//test("-2- microsoft_azure_face_key",$microsoft_azure_face_key);
	

	//define( 'API_BASE_URL','https://southcentralus.api.cognitive.microsoft.com/face/v1.0/detect?');
	//define( 'API_BASE_URL','https://eastus.api.cognitive.microsoft.com/face/v1.0/detect?');
	//define( 'API_BASE_URL','https://eastus.api.cognitive.microsoft.com/face/v1.0/detect?');
	
	//azure.001@corp.intelitruth.com
	if(!$microsoft_azure_face_key) $microsoft_azure_face_key = "d103dd93cfb84a3193ccef07ae3b2ed6"; // KEY #1
	define( 'API_BASE_URL','https://intelitruth.cognitiveservices.azure.com/face/v1.0/detect');
	
	
	logger3("2- microsoft_azure_face_detect(path_to_image)",$path_to_image);
	logger3("2- microsoft_azure_face_detect(microsoft_azure_face_key)",$microsoft_azure_face_key);
	
	
	$img = $path_to_image;
	
	$post_string = '{"url":"' . $img . '"}';
	
	$query_params = array(
	    'returnFaceId'				=>	'true'
	    ,'returnFaceLandmarks'		=>	'true'
	    ,'useCache'					=>	'false'
	
	);
	
	$params = '';
	foreach( $query_params as $key => $value ) {
	    $params .= $key . '=' . $value . '&';
	}
	//$params .= 'subscription-key=' . API_PRIMARY_KEY;
	
	$post_url = API_BASE_URL ."?". $params;
	
	logger3("-3- post_url",$post_url);
	
	
	
	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HTTPHEADER, array(                                                                          
	    'Content-Type: application/json',
	    'Ocp-Apim-Subscription-Key: '. $microsoft_azure_face_key,                                                                            
	    'Content-Length: ' . strlen($post_string))
	);    
	
	curl_setopt( $ch, CURLOPT_URL, $post_url );
	curl_setopt( $ch, CURLOPT_POST, true );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_string );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	$response_json = curl_exec( $ch );
	
	
	curl_close( $ch );
	
	logger3("-100- microsoft_azure_face_detect(response_json)",$response_json);
	
	$final_response = object_to_array_v10(json_decode($response_json));
	
	logger3("-102- microsoft_azure_face_detect(final_response)",$final_response);
	
	return $final_response;
	

}



function microsoft_azure_face_verify($microsoft_azure_face_id_1="",$microsoft_azure_face_id_2="",$microsoft_azure_face_key="") {
	
	logger3("microsoft_azure_face_verify(1) microsoft_azure_face_id_1",$microsoft_azure_face_id_1);
	logger3("microsoft_azure_face_verify(2) microsoft_azure_face_id_2",$microsoft_azure_face_id_2);
	logger3("microsoft_azure_face_verify(3) microsoft_azure_face_key",$microsoft_azure_face_key);
	
	if(!$microsoft_azure_face_id_1) return false;
	if(!$microsoft_azure_face_id_2) return false;
	
	## if(!$microsoft_azure_face_key) $microsoft_azure_face_key = "da3e4f788f454fa083050c414fb8dac5";
	## if(!$microsoft_azure_face_key) $microsoft_azure_face_key = "3f336564a27845b5ae6ba16357559c4a";
	## $url = "https://southcentralus.api.cognitive.microsoft.com/face/v1.0/verify";
	##  $url = "https://eastus.api.cognitive.microsoft.com/face/v1.0/verify";
	
	logger3("microsoft_azure_face_verify(3) url",$url);
	
	
	//azure.001@corp.intelitruth.com
	if(!$microsoft_azure_face_key) $microsoft_azure_face_key = "d103dd93cfb84a3193ccef07ae3b2ed6"; // KEY #1
	$url = "https://intelitruth.cognitiveservices.azure.com/face/v1.0/verify";
	
	
	
	
	$params_array = array(
							"faceId1"	=>	$microsoft_azure_face_id_1
							,"faceId2"	=>	$microsoft_azure_face_id_2
						);
	$params = json_encode($params_array);
	
	logger3("microsoft_azure_face_verify(4) params",$params);
	
	
	
	$ch = curl_init();
	//curl_setopt( $ch, CURLOPT_HTTPHEADER, 'Content-Type: application/json'); 
	
	curl_setopt( $ch, CURLOPT_HTTPHEADER, array(                                                                          
	    'Content-Type: application/json',
	     'Ocp-Apim-Subscription-Key: '. $microsoft_azure_face_key,
	     'Transfer-Encoding: chunked'    
	     )
	); 
	
	
	curl_setopt( $ch, CURLOPT_URL, $url);
	curl_setopt( $ch, CURLOPT_POSTFIELDS, $params );
	curl_setopt( $ch, CURLOPT_POST, true );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	
	$response_json = curl_exec( $ch );
	logger3("microsoft_azure_face_verify(5) response_json",$response_json);
	
	curl_close( $ch );
	
	$response = json_decode($response_json);
	logger3("microsoft_azure_face_verify(6) response",$response);
	
	return object_to_array_v2($response);
	
}








function microsoft_azure_ocr($path_to_image="",$microsoft_azure_ocr_key="") {
	
	
	logger3("microsoft_azure_ocr(1) path_to_image",$path_to_image);
	logger3("microsoft_azure_ocr(2) microsoft_azure_ocr_key",$microsoft_azure_ocr_key);
	
	if(!$path_to_image) return false;
	//if(!$microsoft_azure_ocr_key) $microsoft_azure_ocr_key = "0097a77785be4e9d924c7f7a951ec677";
	if(!$microsoft_azure_ocr_key) $microsoft_azure_ocr_key = "3ad5f01014b7402bb46c78dd94ea6600";
	
	$path_to_image = str_ireplace("https", "http", $path_to_image);

	define( 'API_BASE_URL','https://eastus.api.cognitive.microsoft.com/vision/v1.0/ocr?');
	
	
	
	$img = $path_to_image;
	
	logger3("img",$img);
	
	$post_string = '{"url":"' . $img . '"}';
	
	$query_params = array(
	    'language'				=> 'unk',
	    'detectOrientation'		=> 'true'
	
	);
	
	$params = '';
	foreach( $query_params as $key => $value ) {
	    $params .= $key . '=' . $value . '&';
	}
	
	$post_url = API_BASE_URL . $params;
	logger3("microsoft_azure_ocr(3) post_url",$post_url);
	
	
	logger3("microsoft_azure_ocr(4) path_to_image",$path_to_image);
	logger3("microsoft_azure_ocr(5) microsoft_azure_ocr_key",$microsoft_azure_ocr_key);
	
	
	$ch = curl_init();
	curl_setopt( 
		$ch, CURLOPT_HTTPHEADER, array(                                                                          
	    'Content-Type: application/json',
	    'Ocp-Apim-Subscription-Key: '. $microsoft_azure_ocr_key,                                                                            
	    'Content-Length: ' . strlen($post_string)
	    )
	);    
	
	curl_setopt( $ch, CURLOPT_URL, $post_url );
	curl_setopt( $ch, CURLOPT_POST, true );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_string );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	$response_json = curl_exec( $ch );
	
	logger3("microsoft_azure_ocr(10) response_json",$response_json);
	
	curl_close( $ch );
	
	return $response = object_to_array_v2(json_decode($response_json));
	//test("1. response",$response);

}




function microsoft_azure_ocr_v2($path_to_image="",$microsoft_azure_ocr_key="") {
	
	logger3("microsoft_azure_ocr(1) path_to_image",$path_to_image);
	logger3("microsoft_azure_ocr(2) microsoft_azure_ocr_key",$microsoft_azure_ocr_key);
	
	if(!$path_to_image) return false;
	//if(!$microsoft_azure_ocr_key) $microsoft_azure_ocr_key = "0097a77785be4e9d924c7f7a951ec677";
	if(!$microsoft_azure_ocr_key) $microsoft_azure_ocr_key = "3ad5f01014b7402bb46c78dd94ea6600";
	
	$path_to_image = str_ireplace("https", "http", $path_to_image);
	
	$microsoft_azure_ocr_body = array(
		 'url' => $path_to_image,
	);
	$microsoft_azure_ocr_body = json_encode($microsoft_azure_ocr_body);
	
	logger3("microsoft_azure_ocr_body",$microsoft_azure_ocr_body);
	
	require_once 'HTTP/Request2.php';
	
	
	$request = new Http_Request2('http://eastus.api.cognitive.microsoft.com/vision/v1.0/ocr');
	$url = $request->getUrl();
	
	$headers = array(
	    // Request headers
	    'Content-Type' => 'application/json',
	    'Ocp-Apim-Subscription-Key' => $microsoft_azure_ocr_key,
	);
	
	$request->setHeader($headers);
	
	$parameters = array(
	    // Request parameters
	    'language' => 'unk',
	    'detectOrientation ' => 'true',
	);
	
	$url->setQueryVariables($parameters);
	
	$request->setMethod(HTTP_Request2::METHOD_POST);
	
	// Request body
	$request->setBody($microsoft_azure_ocr_body);
	
	try
	{
	    $response = $request->send();
	    $final_response = $response->getBody();
	    //test("final_response",$final_response);
	    
	}
	catch (HttpException $ex)
	{
	    logger3("ex",$ex);
	}
	
	$final_response = json_decode($final_response);
	
	logger3("final_response",$final_response);
	
	return $final_response;
	

}




function convert_image_to_jpeg($path_to_original_image,$path_to_new_jpg,$CompressionQuality="") {

	

	if(stristr($path_to_original_image,".PDF"))
	{
	
		logger3("convert_image_to_jpeg(): path_to_original_image",$path_to_original_image);
		logger3("convert_image_to_jpeg(): path_to_new_jpg",$path_to_new_jpg);
		$im = new imagick();
		$im->setResolution(300,300);
		$im->readimage($path_to_original_image ."[0]"); 
		$im->setImageFormat('jpeg');    
		$im->writeImage(path_to_new_jpg); 
		$im->clear(); 
		$im->destroy();
		return true;
	}


	
	logger3("convert_image_to_jpeg(path_to_original_image)",$path_to_original_image);
	
	logger3("convert_image_to_jpeg(path_to_new_jpg)",$path_to_new_jpg);
	
	if(!$CompressionQuality) $CompressionQuality = "100";
	
	logger3("convert_image_to_jpeg(CompressionQuality)",$CompressionQuality);
	
	$im = new imagick( $path_to_original_image ); 
	
	logger3("convert_image_to_jpeg(im)",$im);

	
	
	logger3("convert_image_to_jpeg(5)");
	
	//possibly resize 
	//$image_size = $im->getImageSize();
	$image_size = $im->getImageLength();
	
	logger3("convert_image_to_jpeg(image_size)",$image_size);
	
	
	while($image_size > 3800000) {
		
		$current_width = $im->getImageWidth();
		logger3("convert_image_to_jpeg(current_width)",$current_width);
		
		$current_height = $im->getImageHeight();
		logger3("convert_image_to_jpeg(current_height)",$current_height);
		
		$new_width = $current_width * .6;
		logger3("convert_image_to_jpeg(new_width)",$new_width);
		
		$new_height = $current_height * .6;
		logger3("convert_image_to_jpeg(new_height)",$new_height);
		
		$im->resizeImage($new_width, $new_height, imagick::FILTER_LANCZOS, 1);
		$im->writeImage($path_to_new_jpg); 
		$im->clear();
		$im->destroy(); 
		
		$im = new imagick( $path_to_new_jpg );
		
		
		$image_size = $im->getImageSize();
		
		logger3("convert_image_to_jpeg(image_size)",$image_size);
		
	}
	
	// convert to jpg 
	//$im->setImageColorspace(255); 
	
	$im->setCompression(Imagick::COMPRESSION_JPEG); 
	$im->setCompressionQuality($CompressionQuality); 
	$im->setImageFormat('jpeg'); 
	
	
	//$im -> scaleImage(1024, 0, true);
	//$cropWidth = $im->getImageWidth();
    //$cropHeight = $im->getImageHeight();
    
    //$newWidth = $cropWidth / 2;
    //$newHeight = $cropHeight / 2;
    
    //$im->resizeImage($newWidth, $newHeight, imagick::FILTER_LANCZOS, 1);  
    
    
    
    # $im->cropimage(
    #         $newWidth,
    #         $newHeight,
    #         ($cropWidth - $newWidth) / 2,
    #         ($cropHeight - $newHeight) / 2
    #     );
    
	
	logger3("convert_image_to_jpeg(6)");
	
	//write image on server 
	$im->writeImage($path_to_new_jpg); 
	
	logger3("convert_image_to_jpeg(7)");
	
	$im->clear(); 
	$im->destroy(); 
	
	logger3("convert_image_to_jpeg(8)");

}


function convert_image_to_jpeg_v2($path_to_original_image,$path_to_new_jpg,$CompressionQuality="",$image_size_kb="") {
	
	logger3("convert_image_to_jpeg(path_to_original_image)",$path_to_original_image);
	
	logger3("convert_image_to_jpeg(path_to_new_jpg)",$path_to_new_jpg);
	
	if(!$CompressionQuality) $CompressionQuality = "100";
	
	logger3("convert_image_to_jpeg(CompressionQuality)",$CompressionQuality);
	
	$im = new imagick( $path_to_original_image ); 
	
	logger3("convert_image_to_jpeg(im)",$im);

	
	
	logger3("convert_image_to_jpeg(5)");
	
	//possibly resize 
	$image_size = $im->getImageSize();
	
	logger3("convert_image_to_jpeg(image_size)",$image_size);
	
	if(!$image_size_kb) $image_size_kb = 1950000;
	
	while($image_size > $image_size_kb) {
		
		$current_width = $im->getImageWidth();
		logger3("convert_image_to_jpeg(current_width)",$current_width);
		
		$current_height = $im->getImageHeight();
		logger3("convert_image_to_jpeg(current_height)",$current_height);
		
		$new_width = $current_width * .6;
		logger3("convert_image_to_jpeg(new_width)",$new_width);
		
		$new_height = $current_height * .6;
		logger3("convert_image_to_jpeg(new_height)",$new_height);
		
		$im->resizeImage($new_width, $new_height, imagick::FILTER_LANCZOS, 1);
		$im->writeImage($path_to_new_jpg); 
		$im->clear();
		$im->destroy(); 
		
		$im = new imagick( $path_to_new_jpg );
		
		
		$image_size = $im->getImageSize();
		
		logger3("convert_image_to_jpeg(image_size)",$image_size);
		
	}
	
	// convert to jpg 
	//$im->setImageColorspace(255); 
	
	$im->setCompression(Imagick::COMPRESSION_JPEG); 
	$im->setCompressionQuality($CompressionQuality); 
	$im->setImageFormat('jpeg'); 
	
	
	//$im -> scaleImage(1024, 0, true);
	//$cropWidth = $im->getImageWidth();
    //$cropHeight = $im->getImageHeight();
    
    //$newWidth = $cropWidth / 2;
    //$newHeight = $cropHeight / 2;
    
    //$im->resizeImage($newWidth, $newHeight, imagick::FILTER_LANCZOS, 1);  
    
    
    
    # $im->cropimage(
    #         $newWidth,
    #         $newHeight,
    #         ($cropWidth - $newWidth) / 2,
    #         ($cropHeight - $newHeight) / 2
    #     );
    
	
	logger3("convert_image_to_jpeg(6)");
	
	//write image on server 
	$im->writeImage($path_to_new_jpg); 
	
	logger3("convert_image_to_jpeg(7)");
	
	$im->clear(); 
	$im->destroy(); 
	
	logger3("convert_image_to_jpeg(8)");

}






function get_image_size($path_to_image) {
	
	if(!$path_to_image) return false;
	
	$img = new imagick( $path_to_image );
	$size = $img->getImageSize();
	$img->clear(); 
	$img->destroy(); 
	return $size;
}


function rotate_image($imagePath,$angle="",$background_color="") {
	
	//if(!$imagePath) return false;
	
	if(!$angle) $angle = 90;
	//$background_color = "";
	
	//test("imagePath",$imagePath);
	
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->rotateimage($background_color,$angle);
    
    //write image on server 
	$imagick->writeImage($imagePath); 
	$imagick->clear(); 
	$imagick->destroy(); 
}


function sharpen_image($imagePath,$contrast="") {
	
	if(!$imagePath) return false;
	
	if(!$contrast) $contrast = 1;
	
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->contrastImage($contrast);
    
    //write image on server 
	$imagick->writeImage($imagePath); 
	$imagick->clear(); 
	$imagick->destroy(); 
}




function get_remote_file_and_save_to_local_directory($path_to_remote_filename,$new_local_filename="",$path_to_local_directory="") {
	

	if(!$path_to_local_filename) $path_to_local_directory = "/BANGK!/authorizations/ids/";
	$path_to_local_filename = $path_to_local_directory . $new_local_filename;
	
	
	//test("path_to_remote_filename",$path_to_remote_filename);
	//test("new_local_filename",$new_local_filename);
	//test("path_to_local_directory",$path_to_local_directory);
	//test("path_to_local_filename",$path_to_local_filename);
	

	$image = file_get_contents($path_to_remote_filename);
	file_put_contents($path_to_local_filename, $image); //Where to save the image on your server

}




function decode_business_subcategory($db_encoded_string) {
	
	$tmp_business_description = $db_encoded_string;
	$tmp_business_description = str_ireplace("%u2606", "☆", $tmp_business_description);
	$tmp_business_description = str_ireplace("%u2605", "★", $tmp_business_description);
	$tmp_business_description = str_ireplace("%3A", ":", $tmp_business_description);
	$tmp_business_description = str_ireplace("%20", " ", $tmp_business_description);
	$tmp_business_description = str_ireplace("%27", "'", $tmp_business_description);
	$tmp_business_description = str_ireplace("%C9", "É", $tmp_business_description);
	
	$tmp_business_description = str_ireplace("%28", "(", $tmp_business_description);
	$tmp_business_description = str_ireplace("%29", ")", $tmp_business_description);
	$tmp_business_description = str_ireplace("%2F", "/", $tmp_business_description);	
	$tmp_business_description = str_ireplace("%2D", "-", $tmp_business_description);
	$tmp_business_description = str_ireplace("%2B", "+", $tmp_business_description);
	$tmp_business_description = str_ireplace("%26", "&", $tmp_business_description);
	$tmp_business_description = str_ireplace("%24", "$", $tmp_business_description);
	$tmp_business_description = str_ireplace("%2C", ",", $tmp_business_description);
	$tmp_business_description = str_ireplace("%23", "#", $tmp_business_description);
	$tmp_business_description = str_ireplace("%2E", ".", $tmp_business_description);
	$tmp_business_description = str_ireplace("%3B", ";", $tmp_business_description);
	
	$tmp_business_description = str_ireplace("%3C", "<", $tmp_business_description);
	$tmp_business_description = str_ireplace("%3D", "=", $tmp_business_description);
	$tmp_business_description = str_ireplace("%3E", ">", $tmp_business_description);
	$tmp_business_description = str_ireplace("%3F", "?", $tmp_business_description);
	$tmp_business_description = str_ireplace("%40", "@", $tmp_business_description);
	$tmp_business_description = str_ireplace("%5B", "[", $tmp_business_description);
	$tmp_business_description = str_ireplace("%5D", "]", $tmp_business_description);
	$tmp_business_description = str_ireplace("%5F", "_", $tmp_business_description);
	$tmp_business_description = str_ireplace("%7C", "|", $tmp_business_description);
	$tmp_business_description = str_ireplace("%21", "!", $tmp_business_description);


	return $tmp_business_description;
}




function time_ago($date) {
   $timestamp = strtotime($date);	
   
   $strTime = array("second", "minute", "hour", "day", "month", "year");
   $length = array("60","60","24","30","12","10");

   $currentTime = time();
   if($currentTime >= $timestamp) {
		$diff     = time()- $timestamp;
		for($i = 0; $diff >= $length[$i] && $i < count($length)-1; $i++) {
		$diff = $diff / $length[$i];
		}

		$diff = round($diff);
		return $diff . " " . $strTime[$i] . "(s) ago ";
   }
}
	
	
	
Function fullCURL($url,$parameters) {


	$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_POSTFIELDS, $parameters); 

	curl_setopt ($ch, CURLOPT_HEADER, 0);

	curl_setopt ($ch, CURLOPT_ENCODING, 0);

	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

	curl_setopt ($ch, CURLOPT_AUTOREFERER, 1);

	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.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.");

	curl_close ($ch);
	
	return $result;

}


Function kurl_2018($url,$parameters) {


	$result = FALSE;
	$attempt = 1;
	
	while(
		($result === FALSE) 
		&& ($attempt <= 3) 
	) {
	
		$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_POSTFIELDS, $parameters); 
		
		curl_setopt ($ch, CURLOPT_HEADER, 0);
		
		curl_setopt ($ch, CURLOPT_ENCODING, 0);
		
		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
		
		curl_setopt ($ch, CURLOPT_AUTOREFERER, 1);
		
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		
		$CURLOPT_USERAGENT = getUserAgent();
		curl_setopt($ch, CURLOPT_USERAGENT, $CURLOPT_USERAGENT);
		
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
		
		curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); 
		
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		
		$result = curl_exec ($ch);
		
		if($result === FALSE) {
			test('curl_exec Error: ' . curl_error($ch));
			$attempt++;
		}
		
		curl_close ($ch);
	}
	
	return $result;

}



Function fullCURL_sentireport_cron($url,$parameters) {


	$result = FALSE;
	$attempt = 1;
	
	while(
		($result === FALSE) 
		&& ($attempt <= 3) 
	) {
	
		$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_POSTFIELDS, $parameters); 
		
		curl_setopt ($ch, CURLOPT_HEADER, 0);
		
		curl_setopt ($ch, CURLOPT_ENCODING, 0);
		
		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
		
		curl_setopt ($ch, CURLOPT_AUTOREFERER, 1);
		
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		
		$CURLOPT_USERAGENT = getUserAgent();
		curl_setopt($ch, CURLOPT_USERAGENT, $CURLOPT_USERAGENT);
		
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
		
		curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); 
		
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		
		$result = curl_exec ($ch);
		
		if($result === FALSE) {
			test('curl_exec Error: ' . curl_error($ch));
			$attempt++;
		}
		
		curl_close ($ch);
	}
	
	return $result;

}



function getUserAgent()
{
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5";
	$userAgentArray[] = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36 OPR/49.0.2725.47";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5";
	$userAgentArray[] = "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36 OPR/49.0.2725.64";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/62.0.3202.94 Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0";
	$userAgentArray[] = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;  Trident/5.0)";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; rv:52.0) Gecko/20100101 Firefox/52.0";
	$userAgentArray[] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/63.0.3239.84 Chrome/63.0.3239.84 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0";
	$userAgentArray[] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0;  Trident/5.0)";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:58.0) Gecko/20100101 Firefox/58.0";
	$userAgentArray[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Safari/604.1.38";
	$userAgentArray[] = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36";
	$userAgentArray[] = "Mozilla/5.0 (X11; CrOS x86_64 9901.77.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.97 Safari/537.36";
	
	$getArrayKey = array_rand($userAgentArray);
	return $userAgentArray[$getArrayKey];
 
}




function whitepages_pro($country_code_iso3,$local_telephone_number,$key="") {
	
	if(!$key) $key = "5a248e5b280f4669bc36a5dc6319fa74";
	
	
	$calling_code = geo_data($country_code_iso3,"iso3","calling_code");
	
	$final_telephone_number = "+".$calling_code.$local_telephone_number;
	
	$file_get_contents = file_get_contents("https://proapi.whitepages.com/3.0/phone?api_key=". $key ."&phone=".$final_telephone_number);
	
	return object_to_array_v2(json_decode($file_get_contents));
	
}	



function hashme_v2($desired_random_string_length) {
	
	if(!$desired_random_string_length) $desired_random_string_length = 32;
	//test("desired_random_string_length",$desired_random_string_length);
	
	$part_one_length = number_format($desired_random_string_length/2,0)-2;
	//test("part_one_length",$part_one_length);
	
	$part_two_length = number_format($desired_random_string_length/2,0);
	//test("part_two_length",$part_two_length);
	
	
	return substr(str_shuffle(str_repeat("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz0123456789!@$%*()", 63)), 0, $desired_random_string_length);
	
	
}



function object_to_array_v3($object) {
    if(!is_object($object) && !is_array($object))
        return $object;

    return array_map('object_to_array_v3', (array) $object);
}

function get_protected_value($whole_object,$key_name) {
  $array = (array)$whole_object;
  $prefix = chr(0).'*'.chr(0);
  return $array[$prefix.$key_name];
}
		
		



function get_current_sentiment_score($target_primary,$target_near="",$target_type="") {
	
	
	
	
	global $ibm_watson_disovery_news_username;
	global $ibm_watson_disovery_news_password;
	
	
	//test("target_primary",$target_primary);
	//test("target_near",$target_near);
	
	//if(!$type) $type = "Organization";
	if(!$target_near) $target_near = " ";
	if(!$target_type) $target_type = "Person";
	
	$accumulative_sentiment_score = "";
	
	
	$associate_deep_dive_results_json = get_ibm_watson_news($target_primary,$ibm_watson_disovery_news_username,$ibm_watson_disovery_news_password);

	$json_decode_array = json_decode($associate_deep_dive_results_json);
	
	$json_decode_array = object_to_array_v2($json_decode_array);
	
	//test("json_decode_array",$json_decode_array);

	//exit;
	
	
	$frequency_total = 0;
	$frequency_scored = 0;
	
	foreach($json_decode_array['results'] AS $key => $results_details) {
		
		
		//test("results_details",$results_details);
		
		//exit;
		
		
		$json_encoded_details = json_encode($results_details);
		
		//test("search",$search);
		
		
		
		//test("target_near",$target_near);
		
		if(
			(stristr($json_encoded_details,$target_primary))
			&& (stristr($json_encoded_details,$target_near))
		
		) {
			
			$frequency_total++;
			//test("frequency_total",$frequency_total);
			
			foreach($results_details[enriched_text][entities] AS $entities_key => $entites_details) {
				
				//test("entites_details",$entites_details);
				
				
				/// get scores
				
				if(
					(stristr($entites_details[text],$target_primary))
					&& (stristr($entites_details[type],$target_type))
				
					 
				) {

				
					
					if($entites_details[sentiment][score] != 0) {
						
						$frequency_scored++;
						
						// test("entites_details[sentiment][score]",$entites_details[sentiment][score]);
						// test("entites_details[text]",$entites_details[text]);
						// test("entites_details[type]",$entites_details[type]);
						
						$accumulative_sentiment_score = $accumulative_sentiment_score + $entites_details[sentiment][score];
						
						//test("accumulative_sentiment_score",$accumulative_sentiment_score);
						
						//test("-------","-------");
					}

				}	
			}
		}
	}
	
	$output['frequency_total'] = $frequency_total;
	$output['frequency_scored'] = $frequency_scored;
	$output['accumulative_score'] = number_format($accumulative_sentiment_score,9);
	$output['sentiscore'] = number_format($accumulative_sentiment_score / $frequency_scored,9);
	
	return $output;
}	




function ibm_watson_news_get_associates_from_article($article_details_json_decoded,$target_primary,$target_type="") {
	
	
	
	
	if(!$target_type) $target_type = "Person";
	//test("article_details_json_decoded",$article_details_json_decoded);
	
	//test("target_primary",$target_primary);
	//test("target_type",$target_type);
	
	$article_details_json_decoded = object_to_array_v2($article_details_json_decoded);
	
	$associates_array = array();
	
	$number_of_associates = 0;
	
	foreach($article_details_json_decoded[enriched_text][entities] AS $entities_key => $entites_details) {
		
		//test("entites_details",$entites_details);
		
		
		/// test person
		if(
			(stristr($entites_details[type],$target_type)) 
			&& (!stristr($entites_details[text],$target_primary)) 
		) {
			
			
			
			/// test full name
			$full_name = explode(" ", $entites_details[text]);
			if(
				($full_name[1])
				&& (strlen($full_name[1])>1)
			) {
				
				
		
				//test("entites_details[sentiment][score]",$entites_details[sentiment][score]);
				//test("entites_details[text]",$entites_details[text]);
				//test("entites_details[type]",$entites_details[type]);
				//test("-------","-------");
				
				
				$associates_array[$number_of_associates]['associate_type'] = $entites_details[type];
				$associates_array[$number_of_associates]['associate_name'] = $entites_details[text];
				$associates_array[$number_of_associates]['associate_sentiment_score'] = $entites_details[sentiment][score];
				
				$number_of_associates++;
				
				
				
			}
		}
	}
	
	return $associates_array;
}




function search_twitter($search,$longitude="",$latitude="",$radius="",$oauth_access_token="",$oauth_access_token_secret="",$consumer_key="",$consumer_secret="") {
	



	if(!$oauth_access_token) $oauth_access_token = "938813268042440704-CT62Ej00nz1ukzVfDQzhrHwIlCK6Rgj";
	if(!$oauth_access_token_secret) $oauth_access_token_secret = "yC9kaTo35XLmw8RLRrrHltRj2eGpUR4qwp6C0NKhkgGQy";
	if(!$consumer_key) $consumer_key = "7zWfA5Ccsnc5U0QTDUCVFxPd6";
	if(!$consumer_secret) $consumer_secret = "6GIQ6D767sooEjQIRT1ZlQqFz1Z6Ez3SSgj21He2yNLqeFBnY7";
	
	
	
	
	
	if($_SESSION['sentireport']['oauth_access_token']) $oauth_access_token = $_SESSION['sentireport']['oauth_access_token'];
	if($_SESSION['sentireport']['oauth_access_token_secret']) $oauth_access_token_secret = $_SESSION['sentireport']['oauth_access_token_secret'];
	if($_SESSION['sentireport']['consumer_key']) $consumer_key = $_SESSION['sentireport']['consumer_key'];
	if($_SESSION['sentireport']['consumer_secret']) $consumer_secret = $_SESSION['sentireport']['consumer_secret'];
	
	if(!$_XXXXX_DISPLAY) global $_XXXXX_DISPLAY;
	if(!stristr($_XXXXX_DISPLAY,"DEMO")) {
		
	if(stristr($_SERVER['SCRIPT_NAME'],"cron")) {
		test("oauth_access_token",$oauth_access_token);
		test("oauth_access_token_secret",$oauth_access_token_secret);
		test("consumer_key",$consumer_key);
		test("consumer_secret",$consumer_secret);
	}
	}
	
	
	
	
	
	
	

	//test("000 search",$search);
	//test("000 longitude",$longitude);
	//test("000 latitude",$latitude);
	//test("000 radius",$radius);


	require_once("/BANGK!/_other/sentireport.com/gateway/vendor/j7mbo/twitter-api-php/TwitterAPIExchange.php");
	
	
	
	
	
	
	
	# $longitude = $incoming_vars['longitude'];
	# $latitude = $incoming_vars['latitude'];
	# $radius = $incoming_vars['radius'];
	# $search = $incoming_vars['search'];

	
	
	
	
	
	/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
	$settings = array(
	    'oauth_access_token' => $oauth_access_token,
	    'oauth_access_token_secret' => $oauth_access_token_secret,
	    'consumer_key' => $consumer_key,
	    'consumer_secret' => $consumer_secret
	);
	
	/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
	//$url = 'https://api.twitter.com/1.1/blocks/create.json';
	//$requestMethod = 'POST';
	//** POST fields required by the URL above. See relevant docs as above **/
	
	$postfields = array(
	    'screen_name' => 'Sentireport LLC', 
	    'skip_status' => '1'
	);
	
	
	
	$url = 'https://api.twitter.com/1.1/search/tweets.json';
	$requestMethod = 'GET';
	
	# $longitude = "-97.771258"; // austin
	# $latitude = "30.326374"; // austin
	# $radius = "100m";
	# $getfield = '?q=test&geocode=37.781157,-122.398720,100mi&count=100';
	
	if(!$longitude) $longitude = "-97.771258"; // austin
	if(!$latitude) $latitude = "30.326374"; // austin
	if(!$radius) $radius = "20km";
	if(!$search) $search = "";
	
	//test("search",$search);
	//test("longitude",$longitude);
	//test("latitude",$latitude);
	//test("radius",$radius);
	
	
	$disable_retweets = " -filter:retweets";
	$date_since = date("Y-m-d",strtotime("-7 days"));
	$date_until = date("Y-m-d",time());
	$search_datetime = "since=". $date_since . "&until=". $date_until;
	
	
	//test("disable_retweets",$disable_retweets);
	//test("date_since",$date_since);
	//test("date_until",$date_until);
	//test("search_datetime",$search_datetime);
	
	//$search_location = " -bio_contains:texas";
	//$search_city = "brushy creek";
	//$accuracy = "500ft";
	
	$return_count = "100";
	
	//$radius = "1000km";
	
	

	
	
	///$getfield = "?q=". $search . $disable_retweets . $search_location . "&geocode=". $latitude .",". $longitude .",". $radius ."&granularity=". $search_city ."&accuracy=". $accuracy ."&count=". $return_count ."&tweet_mode=extended&".$search_datetime;
	
	/// shorter version (minus "granularity", minus "accuracy")
	$getfield = "?q=". $search . $disable_retweets . $search_location . "&geocode=". $latitude .",". $longitude .",". $radius ."&count=". $return_count ."&tweet_mode=extended&".$search_datetime;
	//$getfield = "?q=". $search;
	
	//$getfield = "?q=". $search;
		
	if(stristr($_SERVER['SCRIPT_NAME'],"cron")) {
		test("getfield",$getfield);
	}
	
	//$getfield = '?q=Athens OR Brownsboro OR Dallas -filter:retweets&geocode=32.485101732205,-96.164224817066,100km&granularity=&accuracy=&count=100&tweet_mode=extended&since=2018-08-15&until=2018-08-17';
	//test("getfield",$getfield);
	
	
	$twitter = new TwitterAPIExchange($settings);
	
	if(stristr($_SERVER['SCRIPT_NAME'],"cron")) {
		test("twitter",$twitter);
	}
	
	$response =  $twitter->setGetfield($getfield)
	    ->buildOauth($url, $requestMethod)
	    ->performRequest();
	
	if(stristr($_SERVER['SCRIPT_NAME'],"cron")) {
		test("response",$response);
	}
	
	
	
	return json_decode($response);
}





function search_twitter_v2($query,$longitude="",$latitude="",$radius="",$oauth_access_token="",$oauth_access_token_secret="",$consumer_key="",$consumer_secret="") {
	
	if(!$_XXXXX_DISPLAY) global $_XXXXX_DISPLAY;
	if(!stristr($_XXXXX_DISPLAY,"DEMO")) {
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"cron"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"dev"))
	) {
		test("oauth_access_token",$oauth_access_token);
		test("oauth_access_token_secret",$oauth_access_token_secret);
		test("consumer_key",$consumer_key);
		test("consumer_secret",$consumer_secret);
	}
	}
	
	
	$search = $query;

	
	
	if($_SESSION['sentireport']['oauth_access_token']) $oauth_access_token = $_SESSION['sentireport']['oauth_access_token'];
	if($_SESSION['sentireport']['oauth_access_token_secret']) $oauth_access_token_secret = $_SESSION['sentireport']['oauth_access_token_secret'];
	if($_SESSION['sentireport']['consumer_key']) $consumer_key = $_SESSION['sentireport']['consumer_key'];
	if($_SESSION['sentireport']['consumer_secret']) $consumer_secret = $_SESSION['sentireport']['consumer_secret'];
	
	
	
	
	if(!$_XXXXX_DISPLAY) global $_XXXXX_DISPLAY;
	if(!stristr($_XXXXX_DISPLAY,"DEMO")) {
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"cron"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"dev"))
	) {
		test("oauth_access_token",$oauth_access_token);
		test("oauth_access_token_secret",$oauth_access_token_secret);
		test("consumer_key",$consumer_key);
		test("consumer_secret",$consumer_secret);
	}
	}
	
	
	
	############################################################################################
	############################################################################################
	### TWITTER:
	require_once("/BANGK!/_other/sentireport.com/gateway/sentireport_preferences.gate");
	if(!$ibm_premium_service) global $ibm_premium_service;
	
	if(!$_XXXXX_DISPLAY) global $_XXXXX_DISPLAY;
	if(!stristr($_XXXXX_DISPLAY,"DEMO")) {
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("1- ibm_premium_service",$ibm_premium_service);
	}
	}
		
	if($ibm_premium_service == TRUE) {
		
		if(!$_XXXXX_DISPLAY) global $_XXXXX_DISPLAY;
		if(!stristr($_XXXXX_DISPLAY,"DEMO")) {
		if(
			(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
			|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
			|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
		) {
			test("2- ibm_premium_service",$ibm_premium_service);
		}
		}
		
		if(!$ibm_watson_natural_language_PAID_PREMIUM_version) global $ibm_watson_natural_language_PAID_PREMIUM_version;
		if(!$ibm_watson_natural_language_PAID_PREMIUM_username) global $ibm_watson_natural_language_PAID_PREMIUM_username;
		if(!$ibm_watson_natural_language_PAID_PREMIUM_password) global $ibm_watson_natural_language_PAID_PREMIUM_password;
	
		$ibm_cloud_service_version = $ibm_watson_natural_language_PAID_PREMIUM_version;
		$ibm_cloud_service_username = $ibm_watson_natural_language_PAID_PREMIUM_username;
		$ibm_cloud_service_password = $ibm_watson_natural_language_PAID_PREMIUM_password;
	}
	############################################################################################
	############################################################################################	
		

	
	
	
	
	

	//test("000 search",$search);
	//test("000 longitude",$longitude);
	//test("000 latitude",$latitude);
	//test("000 radius",$radius);


	require_once("/BANGK!/_other/sentireport.com/gateway/vendor/j7mbo/twitter-api-php/TwitterAPIExchange.php");
	
	
	
	
	
	
	
	# $longitude = $incoming_vars['longitude'];
	# $latitude = $incoming_vars['latitude'];
	# $radius = $incoming_vars['radius'];
	# $search = $incoming_vars['search'];

	
	
	
	
	
	/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
	$settings = array(
	    'oauth_access_token' => $oauth_access_token,
	    'oauth_access_token_secret' => $oauth_access_token_secret,
	    'consumer_key' => $consumer_key,
	    'consumer_secret' => $consumer_secret
	);
	
	/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
	//$url = 'https://api.twitter.com/1.1/blocks/create.json';
	//$requestMethod = 'POST';
	//** POST fields required by the URL above. See relevant docs as above **/
	
	$postfields = array(
	    'screen_name' => 'Sentireport LLC', 
	    'skip_status' => '1'
	);
	
	
	
	$url = 'https://api.twitter.com/1.1/search/tweets.json';
	$requestMethod = 'GET';
	
	# $longitude = "-97.771258"; // austin
	# $latitude = "30.326374"; // austin
	# $radius = "100m";
	# $getfield = '?q=test&geocode=37.781157,-122.398720,100mi&count=100';
	
	
	# if(!$longitude) $longitude = "-97.771258"; // austin
	# if(!$latitude) $latitude = "30.326374"; // austin
	# if(!$radius) $radius = "20km";
	# if(!$search) $search = "";
	
	//test("search",$search);
	//test("longitude",$longitude);
	//test("latitude",$latitude);
	//test("radius",$radius);
	
	
	$return_count = "100";
	$disable_retweets = " -filter:retweets";
	$date_since = date("Y-m-d",strtotime("-7 days"));
	$date_until = date("Y-m-d",time());
	$search_datetime = "since=". $date_since . "&until=". $date_until;
	
	
	//test("disable_retweets",$disable_retweets);
	//test("date_since",$date_since);
	//test("date_until",$date_until);
	//test("search_datetime",$search_datetime);
	
	//$search_location = " -bio_contains:texas";
	//$search_city = "brushy creek";
	//$accuracy = "500ft";
	//$radius = "1000km";
	
	
	
	if( ($latitude) && ($longitude) ) {
		
		if(!$radius) $radius = "20km";
		$_XXXXX_geocode = $latitude .",". $longitude .",". $radius;
	}
	
	
	///$getfield = "?q=". $search . $disable_retweets . $search_location . "&geocode=". $_XXXXX_geocode ."&granularity=". $search_city ."&accuracy=". $accuracy ."&count=". $return_count ."&tweet_mode=extended&".$search_datetime;
	
	/// shorter version (minus "granularity", minus "accuracy")
	$getfield = "?q=". $search . $disable_retweets . $search_location . "&geocode=". $_XXXXX_geocode ."&count=". $return_count ."&tweet_mode=extended&".$search_datetime;
	//$getfield = "?q=". $search;
	
	//$getfield = "?q=". $search;
		
	if(stristr($_SERVER['SCRIPT_NAME'],"cron")) {
		test("v2-getfield",$getfield);
	}
	
	//$getfield = '?q=Athens OR Brownsboro OR Dallas -filter:retweets&geocode=32.485101732205,-96.164224817066,100km&granularity=&accuracy=&count=100&tweet_mode=extended&since=2018-08-15&until=2018-08-17';
	//test("getfield",$getfield);
	
	
	$twitter = new TwitterAPIExchange($settings);
	
	if(stristr($_SERVER['SCRIPT_NAME'],"cron")) {
		test("twitter",$twitter);
	}
	
	$response =  $twitter->setGetfield($getfield)
	    ->buildOauth($url, $requestMethod)
	    ->performRequest();
	
	if(stristr($_SERVER['SCRIPT_NAME'],"cron")) {
		test("response",$response);
	}
	
	
	
	return json_decode($response);
}




function get_twitter_trends($WOEID) {
	



	require_once("/BANGK!/_other/sentireport.com/gateway/vendor/j7mbo/twitter-api-php/TwitterAPIExchange.php");

	
	/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
	
	$settings = array(
	    'oauth_access_token' => "938813268042440704-CT62Ej00nz1ukzVfDQzhrHwIlCK6Rgj",
	    'oauth_access_token_secret' => "yC9kaTo35XLmw8RLRrrHltRj2eGpUR4qwp6C0NKhkgGQy",
	    'consumer_key' => "7zWfA5Ccsnc5U0QTDUCVFxPd6",
	    'consumer_secret' => "6GIQ6D767sooEjQIRT1ZlQqFz1Z6Ez3SSgj21He2yNLqeFBnY7"
	);
	/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
	$url = 'https://api.twitter.com/1.1/blocks/create.json';
	$requestMethod = 'POST';
	/** POST fields required by the URL above. See relevant docs as above **/
	$postfields = array(
	    'screen_name' => 'Sentireport', 
	    'skip_status' => '1'
	);
	
	
	
	$url = 'https://api.twitter.com/1.1/trends/place.json';
	
	$requestMethod = 'GET';
	
	$getfield = "?id=". $WOEID;
	
	//test("getfield",$getfield);
	
	
	$twitter = new TwitterAPIExchange($settings);
	$response =  $twitter->setGetfield($getfield)
	    ->buildOauth($url, $requestMethod)
	    ->performRequest();
	
	return object_to_array_v2(json_decode($response));
}


function get_twitter_trends_near($latitude,$longitude) {
	



	require_once("/BANGK!/_other/sentireport.com/gateway/vendor/j7mbo/twitter-api-php/TwitterAPIExchange.php");

	
	/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
	
	$settings = array(
	    'oauth_access_token' => "938813268042440704-CT62Ej00nz1ukzVfDQzhrHwIlCK6Rgj",
	    'oauth_access_token_secret' => "yC9kaTo35XLmw8RLRrrHltRj2eGpUR4qwp6C0NKhkgGQy",
	    'consumer_key' => "7zWfA5Ccsnc5U0QTDUCVFxPd6",
	    'consumer_secret' => "6GIQ6D767sooEjQIRT1ZlQqFz1Z6Ez3SSgj21He2yNLqeFBnY7"
	);
	
	/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
	# $url = 'https://api.twitter.com/1.1/blocks/create.json';
	# $requestMethod = 'POST';
	/** POST fields required by the URL above. See relevant docs as above **/
	
	$postfields = array(
	    'screen_name' => 'Sentireport', 
	    'skip_status' => '1'
	);
	
	
	
	$url = 'https://api.twitter.com/1.1/trends/closest.json';
	
	$requestMethod = 'GET';
	
	$getfield = "?lat=". $latitude . "&long=".$longitude;
	
	//test("getfield",$getfield);
	
	
	$twitter = new TwitterAPIExchange($settings);
	$response =  $twitter->setGetfield($getfield)
	    ->buildOauth($url, $requestMethod)
	    ->performRequest();
	
	return $response;
}




function get_twitter_trends_near_v2($latitude,$longitude) {
	



	require_once("/BANGK!/_other/sentireport.com/gateway/vendor/j7mbo/twitter-api-php/TwitterAPIExchange.php");

	
	/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
	
	$settings = array(
	    'oauth_access_token' => "938813268042440704-CT62Ej00nz1ukzVfDQzhrHwIlCK6Rgj",
	    'oauth_access_token_secret' => "yC9kaTo35XLmw8RLRrrHltRj2eGpUR4qwp6C0NKhkgGQy",
	    'consumer_key' => "7zWfA5Ccsnc5U0QTDUCVFxPd6",
	    'consumer_secret' => "6GIQ6D767sooEjQIRT1ZlQqFz1Z6Ez3SSgj21He2yNLqeFBnY7"
	);
	
	/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
	# $url = 'https://api.twitter.com/1.1/blocks/create.json';
	# $requestMethod = 'POST';
	/** POST fields required by the URL above. See relevant docs as above **/
	
	$postfields = array(
	    'screen_name' => 'Sentireport', 
	    'skip_status' => '1'
	);
	
	
	
	$url = 'https://api.twitter.com/1.1/trends/closest.json';
	
	$requestMethod = 'GET';
	
	$getfield = "?lat=". $latitude . "&long=".$longitude;
	
	//test("getfield",$getfield);
	
	
	$twitter = new TwitterAPIExchange($settings);
	$response =  $twitter->setGetfield($getfield)
	    ->buildOauth($url, $requestMethod)
	    ->performRequest();
	
	$twitter_trend_results = object_to_array(json_decode($response));
	//test("twitter_trend_results",$twitter_trend_results);
	
	
	
	$twitter_trend_city = $twitter_trend_results[0]['name'];
	//test("twitter_trend_city",$twitter_trend_city);
	
	
	$twitter_trend_state = $subscriber_details['state_iso2'];
	//test("twitter_trend_state",$twitter_trend_state);
	
	$WOEID_to_use = $twitter_trend_results[0]['woeid'];
	
	
	
	
	return $WOEID_to_use;
}


function get_WOEID($WOEID_city,$WOEID_state_iso2) {
	
	$WOEID_url = "http://query.yahooapis.com/v1/public/yql";
	
	$ch = curl_init();
	curl_setopt ( $ch, CURLOPT_URL, $WOEID_url );

	//Create And Save Cookies
    $tmpfname = dirname(__FILE__).'/cookie.txt';
    curl_setopt( $ch, CURLOPT_COOKIEJAR, $tmpfname);
    curl_setopt( $ch, CURLOPT_COOKIEFILE, $tmpfname);

	
	$parameters = 'q=select woeid from geo.places where text="'. $WOEID_city .','. $WOEID_state_iso2 .',"&format=json';
	
	if(isset($parameters)){
		curl_setopt ( $ch, CURLOPT_POST, 1);	
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $parameters); 
	}
    curl_setopt( $ch, CURLOPT_HEADER, false);
    curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );

    // EXECUTE
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}





function GetCenterFromDegrees($data)
{
	
	/**
		* Get a center latitude,longitude from an array of like geopoints
		*
		* @param array data 2 dimensional array of latitudes and longitudes
		* For Example:
		* $data = array
		* (
		*   0 = > array(45.849382, 76.322333),
		*   1 = > array(45.843543, 75.324143),
		*   2 = > array(45.765744, 76.543223),
		*   3 = > array(45.784234, 74.542335)
		* );
	**/


    if (!is_array($data)) return FALSE;

    $num_coords = count($data);

    $X = 0.0;
    $Y = 0.0;
    $Z = 0.0;

    foreach ($data as $coord)
    {
        $lat = $coord[0] * pi() / 180;
        $lon = $coord[1] * pi() / 180;

        $a = cos($lat) * cos($lon);
        $b = cos($lat) * sin($lon);
        $c = sin($lat);

        $X += $a;
        $Y += $b;
        $Z += $c;
    }

    $X /= $num_coords;
    $Y /= $num_coords;
    $Z /= $num_coords;

    $lon = atan2($Y, $X);
    $hyp = sqrt($X * $X + $Y * $Y);
    $lat = atan2($Z, $hyp);

	
	$output['latitude'] = $lat * 180 / pi();
	$output['longitude'] = $lon * 180 / pi();
    return $output;
}





function sentiscore_for_county($state_iso2,$county,$target="",$radius="") {

	//test("0 target",$target);
	
	$state = $state_iso2;

	$tmp_sql = "SELECT DISTINCT(city)
				FROM state_county_city
				WHERE county = '". $county ."'
				AND state = '". $state ."'
				;";
	$county_city_array = readarrayTHECASHIER($tmp_sql,"senti");
	
	//test("county_city_array_count",count($county_city_array));
	
	//test("county_city_array",$county_city_array);
	
	
	$county_city_details_array = array();
	
	foreach($county_city_array AS $key => $city) {
		
		$tmp_sql = "SELECT *
					FROM state_county_city
					WHERE city = '".$city['city'] ."'
					AND county = '". $county ."'
					AND state = '".$state ."'
					LIMIT 1
					;";
		//test("tmp_sql",$tmp_sql);
		$county_city_details_array[$key] = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		
		//test("county_city_details_array",$county_city_details_array);
		
		
		
	}
	
	
	//test("county_city_details_array",$county_city_details_array);
	//exit;
	
	
	
	/// GET CENTERPOINT
	
	$location_array = array();
	
	foreach($county_city_details_array AS $city_key => $city_details) {
		$latitude = $city_details['latitude'];
		$longitude = $city_details['longitude'];
		$location_array[$city_key] = array($latitude,$longitude);
	}
	
	//test("location_array",$location_array);
	
	$centerpoint_array = GetCenterFromDegrees($location_array);

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

	/// GET THE TWEETS
	$minimum_tweets_found = 1;
	$minimum_tweets_found_key = $minimum_tweets_found - 1;
	
	$longitude = $centerpoint_array['longitude'];
	$latitude = $centerpoint_array['latitude'];
	
	if(!$radius) $radius = "50km";
	
	$search_twitter_response['statuses'] = "";
	
	while(
		(!$search_twitter_response['statuses'][$minimum_tweets_found_key])
		&& ($radius != "end")
	) {
		
		
		
		
		//test("longitude",$longitude);
		//test("latitude",$latitude);
		//test("radius",$radius);
		
		$search_twitter_response = search_twitter($target,$longitude,$latitude,$radius);
		
		//test("4 search_twitter_response",$search_twitter_response);
		
		$search_twitter_response = object_to_array_v2($search_twitter_response);
		logger3("search_twitter_response",$search_twitter_response);
		
		if($search_twitter_response['errors'][0]['code']) {
			test("radius",$radius);
			test("target",$target); 
			test("search_twitter_response['errors'][0]['code']",$search_twitter_response['errors'][0]['code']); 
			exit;
		}
		
		if($radius == "10km") $radius = "20km";
		if($radius == "20km") $radius = "50km";
		if($radius == "50km") $radius = "100km";
		if($radius == "100km") $radius = "200km";
		if($radius == "200km") $radius = "500km";
		if($radius == "500km") $radius = "750km";
		if($radius == "750km") $radius = "1000km";
		if($radius == "750km") $radius = "end";
		//sleep(1);
		// temp fixed.
		//$radius = "end";
		
		
	}
	
	
	$search_twitter_response_array = $search_twitter_response['statuses'];
	
	
	

	/// DATABASE THE TWEETS:
	
	global $subscriber_details;
	global $_XXXXX_category;
	global $datetime_common_today;
	foreach($search_twitter_response_array AS $key => $tweet_details) {
		
		$tweet_details = object_to_array_v2($tweet_details);
		
		$_XXXXX_category_tweets_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXX_subscriber_hash = $subscriber_details['hash'];
		$_XXXXX_category = $_XXXXX_category;
		$_XXXXX_source = addslashes($tweet_details['source']);
		$_XXXXX_name = addslashes($tweet_details['user']['name']);
		$_XXXXX_screen_name = addslashes($tweet_details['user']['screen_name']);
		$_XXXXX_location = addslashes($tweet_details['user']['location']);
		$_XXXXX_followers_count = addslashes($tweet_details['user']['followers_count']);
		$_XXXXX_friends_count = addslashes($tweet_details['user']['friends_count']);
		$_XXXXX_listed_count = addslashes($tweet_details['user']['listed_count']);
		$_XXXXX_favourites_count = addslashes($tweet_details['user']['favourites_count']);
		$_XXXXX_statuses_count = addslashes($tweet_details['user']['statuses_count']);
		$_XXXXX_full_text = addslashes($tweet_details['full_text']);
		$_XXXXX_id_str = addslashes($tweet_details['id_str']);
		
		$_XXXXX_retweet_count = addslashes($tweet_details['retweet_count']);
		$_XXXXX_favorite_count = addslashes($tweet_details['favorite_count']);
		$_XXXXX_favorited = addslashes($tweet_details['favorited']);
		$_XXXXX_retweeted = addslashes($tweet_details['retweeted']);
		
		$_XXXXX_created_at = datetime_v2(strtotime($tweet_details['created_at']));
		$_XXXXX_datetime_created = $datetime_common_today;
		
		$tmp_sql = "INSERT INTO `category_tweets`
					(
						`category_tweets_id`
						, `hash`, `subscriber_hash`
						, `category`
						, `source`
						, `name`
						, `screen_name`
						, `location`
						, `followers_count`
						, `friends_count`
						, `listed_count`
						, `favourites_count`
						, `statuses_count`
						, `full_text`
						, `id_str`
						
						, `retweet_count`
						, `favorite_count`
						, `favorited`
						, `retweeted`
						
						, `created_at`
						, `datetime_created`
					) VALUES (
						'". $_XXXXX_category_tweets_id ."'
						, '". $_XXXXX_hash ."'
						, '". $_XXXX_subscriber_hash ."'
						, '". $_XXXXX_category ."'
						, '". $_XXXXX_source ."'
						, '". $_XXXXX_name ."'
						, '". $_XXXXX_screen_name ."'
						, '". $_XXXXX_location ."'
						, '". $_XXXXX_followers_count ."'
						, '". $_XXXXX_friends_count ."'
						, '". $_XXXXX_listed_count ."'
						, '". $_XXXXX_favourites_count ."'
						, '". $_XXXXX_statuses_count ."'
						, '". $_XXXXX_full_text ."'
						, '". $_XXXXX_id_str ."'
						
						, '". $_XXXXX_retweet_count ."'
						, '". $_XXXXX_favorite_count ."'
						, '". $_XXXXX_favorited ."'
						, '". $_XXXXX_retweeted ."'
						
						, '". $_XXXXX_created_at ."'
						, '". $_XXXXX_datetime_created ."'
					);";
		$insert_results = insertTHECASHIER($tmp_sql,"senti");
	}
		
	
	
	
	
	
	
	
	
	
	//test("search_twitter_response_array",$search_twitter_response_array);
	
	
	//exit;
	
	
	
	$accumulated_sentiment_score = 0;
	$total_scored_tweets = 0;
	

	foreach($search_twitter_response_array AS $post_key => $post_details) {
		
		logger3("post_details",$post_details);
	
		//exit;
	
		$text_or_url = $post_details["full_text"];
		$ibm_watson_natural_language_results = get_ibm_watson_natural_language($text_or_url,$ibm_cloud_service_username="",$ibm_cloud_service_password="",$ibm_cloud_service_version="",$source="text");
		
		$ibm_watson_natural_language_results_json_decode = json_decode($ibm_watson_natural_language_results);
		
		
		$ibm_watson_natural_language_results_array = object_to_array_v2($ibm_watson_natural_language_results_json_decode);
		
		
		logger3("ibm_watson_natural_language_results_array",$ibm_watson_natural_language_results_array);
		
		
		if($ibm_watson_natural_language_results_array[sentiment][document][score] != 0) {
			
			$sentiment_score_accumulated = $sentiment_score_accumulated + $ibm_watson_natural_language_results_array[sentiment][document][score];
			logger3("sentiment_score_accumulated",$sentiment_score_accumulated);
			
			
			$total_scored_tweets++;
			logger3("total_scored_tweets",$total_scored_tweets);
			
			
			$total_retweets = $total_retweets + $post_details['retweet_count'];
			
			$current_sentiscore = $sentiment_score_accumulated / $total_scored_tweets;
			logger3("current_sentiscore",$current_sentiscore);
			
			
		}
		
		
		
		
		
		//if($total_scored_tweets > 3) exit;
	}

	
	logger3("sentiscore",$current_sentiscore);
	
	$output['tweets'] = $total_scored_tweets;
	$output['retweets'] = $total_retweets;
	$output['sentiscore'] = $current_sentiscore;
	
	return $output;
	
}



function get_latitude_longitude_centerpoint_county($subscriber_hash) {

	
	if($_SESSION['sentireport']['subscriber_details_array']['hash'] != $subscriber_hash) {
	
		$tmp_sql = "SELECT *
					FROM subscribers
					WHERE hash = '". $subscriber_hash ."'
					;";
		//test("tmp_sql",$tmp_sql);
		$subscriber_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		//test("subscriber_details_array",$subscriber_details_array);
		
		$_SESSION['sentireport']['subscriber_details_array'] = $subscriber_details_array;
	
	} else {
		
		$subscriber_details_array = $_SESSION['sentireport']['subscriber_details_array'];
		
	}
	
	
	$tmp_sql = "SELECT * 
				FROM state_county_city 
				WHERE postal_code = '". $subscriber_details_array['location_postal_code'] ."'
				;";
	//test("tmp_sql",$tmp_sql);
	$subscriber_state_county_city_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
	//test("subscriber_state_county_city_details_array",$subscriber_state_county_city_details_array);
	

	

	
	$tmp_sql = "SELECT DISTINCT(city)
				FROM state_county_city
				WHERE county = '". $subscriber_state_county_city_details_array['county'] ."'
				AND state = '". $subscriber_state_county_city_details_array['state'] ."'
				;";
	//test("tmp_sql",$tmp_sql);
	$county_city_array = readarrayTHECASHIER($tmp_sql,"senti");
	//test("county_city_array",$county_city_array);
	
	
	
	$sentireport_get_cities = sentireport_get_cities($subscriber_hash);
	

	
	$county_city_details_array = array();
	
	foreach($sentireport_get_cities AS $key => $city) {
		
		$tmp_sql = "SELECT *
					FROM state_county_city
					WHERE city = '". $city ."'
					
					AND state = '".$subscriber_state_county_city_details_array['state'] ."'
					LIMIT 1
					;";
		//test("tmp_sql",$tmp_sql);
		$county_city_details_array[$key] = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		
		//test("county_city_details_array",$county_city_details_array);
		
	}
	
	
	//test("county_city_details_array",$county_city_details_array);
	//exit;
	
	
	
	/// GET CENTERPOINT
	
	$location_array = array();
	
	foreach($county_city_details_array AS $city_key => $city_details) {
		$latitude = $city_details['latitude'];
		$longitude = $city_details['longitude'];
		$location_array[$city_key] = array($latitude,$longitude);
	}
	
	//test("location_array",$location_array);
	
	return $centerpoint_array = GetCenterFromDegrees($location_array);
	
}	




function get_county_cities($subscriber_hash) {


	if($_SESSION['sentireport']['subscriber_details_array']['hash'] != $subscriber_hash) {
		
		$tmp_sql = "SELECT *
					FROM subscribers
					WHERE hash = '". $subscriber_hash ."'
					;";
		//test("tmp_sql",$tmp_sql);
		$subscriber_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		//test("subscriber_details_array",$subscriber_details_array);
		
		$_SESSION['sentireport']['subscriber_details_array'] = $subscriber_details_array;
	
	} else {
		
		$subscriber_details_array = $_SESSION['sentireport']['subscriber_details_array'];
		
	}
	
	
	$tmp_sql = "SELECT * 
				FROM state_county_city 
				WHERE postal_code = '". $subscriber_details_array['location_postal_code'] ."'
				;";
	//test("tmp_sql",$tmp_sql);
	$subscriber_state_county_city_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
	//test("subscriber_state_county_city_details_array",$subscriber_state_county_city_details_array);
	

	

	
	$tmp_sql = "SELECT DISTINCT(city)
				FROM state_county_city
				WHERE county = '". $subscriber_state_county_city_details_array['county'] ."'
				AND state = '". $subscriber_state_county_city_details_array['state'] ."'
				;";
	//test("tmp_sql",$tmp_sql);
	$county_city_array = readarrayTHECASHIER($tmp_sql,"senti");
	//test("county_city_array",$county_city_array);
	

	
	$county_city_array_output = array();
	
	foreach($county_city_array AS $key => $city) {
		
		//test("city",$city);
		
		$county_city_array_output[$key] = $city['city'];

	}
	
	return $county_city_array_output;

}	
	

function get_job_type_totals($subscriber_details,$job_type,$days_ago) {
											
	//test("subscriber_details",$subscriber_details);			
											
	$tmp_sql = "SELECT datetime_created
				FROM job_types
				ORDER BY datetime_created DESC
				LIMIT 1;
				";
	//test("tmp_sql",$tmp_sql);
	
	$job_types_datetime_created = getTHECASHIER($tmp_sql,"senti");
	
	$job_types_datetime_created = date("Y-m-d",strtotime($job_types_datetime_created));
	
	//test("job_types_datetime_created",$job_types_datetime_created);
	
	
	
	//test("0_days_ago",$days_ago);
	if(!$days_ago) $days_ago = 0;
	//test("1_days_ago",$days_ago);

	//$get_county_cities = get_county_cities($subscriber_hash);
	$subscriber_cities = sentireport_get_subscriber_cities($subscriber_details);
	
	//test("subscriber_cities",$subscriber_cities);
	
	$where_city = "";
	foreach ($subscriber_cities AS $city_key => $city) {
		
		if($city_key == 0) $where_city = "AND (city = ";
		
		if($city_key != 0) $where_city = $where_city . " OR city = ";
		
		$where_city = $where_city . "'". $city . "'";
	
	}
	$where_city = $where_city . ")";
	//test("where_city",$where_city);
	
	
	
	$where_job_type = "AND job_type LIKE '%". $job_type ."%'";
	
	if($job_type == "ALL") $where_job_type = "";
	
	$tmp_sql = "SELECT SUM(results)
				FROM job_types
				WHERE datetime_created LIKE '%". date("Y-m-d",strtotime($job_types_datetime_created . " -". $days_ago . " DAYS")) ."%'
				AND state_iso3 = '". $subscriber_details['state_iso2'] ."'
				$where_city
				$where_job_type 
				
				;";
	//test("tmp_sql",$tmp_sql);
	$job_type_total = getTHECASHIER($tmp_sql,"senti");
	//test("job_type_total",$job_type_total);
	
	//exit;
	
	return $job_type_total;
	
	

}



function get_job_salary_totals($subscriber_hash,$job_salary,$days_ago) {
											
											
											
	$tmp_sql = "SELECT datetime
				FROM data
				ORDER BY datetime DESC
				LIMIT 1;
				";
	$job_types_datetime_created = getTHECASHIER($tmp_sql,"senti");
	
	$job_types_datetime_created = date("Y-m-d",strtotime($job_types_datetime_created));
	
	//test("job_types_datetime_created",$job_types_datetime_created);
	
	
	if($_SESSION['sentireport']['subscriber_details_array']['hash'] != $subscriber_hash) {
		
		$tmp_sql = "SELECT *
					FROM subscribers
					WHERE hash = '". $subscriber_hash ."'
					;";
		//test("tmp_sql",$tmp_sql);
		$subscriber_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		//test("subscriber_details_array",$subscriber_details_array);
		
		$_SESSION['sentireport']['subscriber_details_array']['hash'] = $subscriber_hash;
		
		$state = $subscriber_details_array['state_iso2'];
	
	} else {
	
		$subscriber_hash = $_SESSION['sentireport']['subscriber_details_array']['hash'];
		$state = $subscriber_details_array['state_iso2'];
	
	}
	
	
	# $tmp_sql = "SELECT * 
	# 			FROM state_county_city 
	# 			WHERE postal_code = '". $subscriber_details_array['location_postal_code'] ."'
	# 			;";
	# //test("tmp_sql",$tmp_sql);
	# $subscriber_state_county_city_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
	# //test("subscriber_state_county_city_details_array",$subscriber_state_county_city_details_array);
	# $state = $subscriber_state_county_city_details_array['state'];
	

	
	
	
	
	if(!$days_ago) $days_ago = 0;


	//$get_county_cities = get_county_cities($subscriber_hash);
	$get_county_cities = sentireport_get_cities($subscriber_hash,$version="");
	
	//test("get_county_cities",$get_county_cities);
	
	$where_city = "";
	foreach ($get_county_cities AS $city_key => $city) {
		
		if($city_key == 0) $where_city = "AND (target_city = ";
		
		if($city_key != 0) $where_city = $where_city . " OR target_city = ";
		
		$where_city = $where_city . "'". $city . "'";
	
	}
	$where_city = $where_city . ")";
	//test("where_city",$where_city);
	
	
	
	$where_job_salary = "AND source_name LIKE '%". $job_salary ."%'";
	
	if($job_salary == "ALL") $where_job_salary = "";
	
	$tmp_sql = "SELECT SUM(results)
				FROM data
				WHERE datetime LIKE '%". date("Y-m-d",strtotime($job_types_datetime_created . " -". $days_ago . " DAYS")) ."%'
				AND target_state_iso2 = '". $state ."'
				$where_city
				$where_job_salary 
				;";
	//test("tmp_sql",$tmp_sql);
	$job_salary_total = getTHECASHIER($tmp_sql,"senti");
	//test("job_salary_total",$job_salary_total);
	
	return $job_salary_total;
	
	

}








function get_job_salary_totals_state($subscriber_hash,$job_salary,$days_ago) {
											
											
											
	$tmp_sql = "SELECT datetime
				FROM data
				ORDER BY datetime DESC
				LIMIT 1;
				";
	$job_types_datetime_created = getTHECASHIER($tmp_sql,"senti");
	
	$job_types_datetime_created = date("Y-m-d",strtotime($job_types_datetime_created));
	
	//test("job_types_datetime_created",$job_types_datetime_created);
	
	
	if($_SESSION['sentireport']['subscriber_details_array']['hash'] != $subscriber_hash) {
	
		$tmp_sql = "SELECT *
					FROM subscribers
					WHERE hash = '". $subscriber_hash ."'
					;";
		//test("tmp_sql",$tmp_sql);
		$subscriber_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		//test("subscriber_details_array",$subscriber_details_array);
		
		$_SESSION['sentireport']['subscriber_details_array']['hash'] = $subscriber_details_array;
		
		$state = $subscriber_details_array['state_iso2'];
	
	} else {
		
		$subscriber_details_array = $_SESSION['sentireport']['subscriber_details_array'];
		$state = $subscriber_details_array['state_iso2'];
		
	}
	
	
	
	# $tmp_sql = "SELECT * 
	# 			FROM state_county_city 
	# 			WHERE postal_code = '". $subscriber_details_array['location_postal_code'] ."'
	# 			;";
	# //test("tmp_sql",$tmp_sql);
	# $subscriber_state_county_city_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
	# //test("subscriber_state_county_city_details_array",$subscriber_state_county_city_details_array);
	# 
	# 
	# $state = $subscriber_state_county_city_details_array['state'];
	
	
	
	if(!$days_ago) $days_ago = 0;


	# $get_county_cities = get_county_cities($subscriber_hash);
	$get_county_cities = sentireport_get_cities($subscriber_hash,$version="");
	
	
	
	
	
	# $where_city = "";
	# foreach ($get_county_cities AS $city_key => $city) {
	# 	
	# 	if($city_key == 0) $where_city = "AND (target_city = ";
	# 	
	# 	if($city_key != 0) $where_city = $where_city . " OR target_city = ";
	# 	
	# 	$where_city = $where_city . "'". $city . "'";
	# 
	# }
	# $where_city = $where_city . ")";
	# //test("where_city",$where_city);
	
	
	
	$where_job_salary = "AND source_name LIKE '%". $job_salary ."%'";
	
	if($job_salary == "ALL") $where_job_salary = "";
	
	$tmp_sql = "SELECT SUM(results)
				FROM data
				WHERE datetime LIKE '%". date("Y-m-d",strtotime($job_types_datetime_created . " -". $days_ago . " DAYS")) ."%'
				AND target_state_iso2 = '". $state ."'
				
				$where_job_salary 
				;";
	//test("tmp_sql",$tmp_sql);
	$job_salary_total = getTHECASHIER($tmp_sql,"senti");
	//test("job_type_fulltime",$job_type_fulltime);
	
	return $job_salary_total;
	
	

}



function sentireport_get_cities($subscriber_hash,$version="") {
	
	//test("version",$version);
	
	if($_SESSION['sentireport']['subscriber_details_array']['hash'] != $subscriber_hash) {
											
		$tmp_sql = "SELECT *
		FROM subscribers
		WHERE hash = '". $subscriber_hash ."'
		;";
		//test("tmp_sql",$tmp_sql);
		$subscriber_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		//test("subscriber_details_array",$subscriber_details_array);
		
		$_SESSION['sentireport']['subscriber_details_array'] = $subscriber_details_array;
	
	} else {
	
		/// save a lookup.
		$subscriber_details_array = $_SESSION['sentireport']['subscriber_details_array'];	
	
	}
	
	
	
	//exit;
	
	if(!$version) {
	
		/// V3 (district_data-based)
		//test("subscriber_details_array['district_data_hash']",$subscriber_details_array['district_data_hash']);
		
		if($subscriber_details_array['district_data_hash']) {
		
		
			if($subscriber_details_array['district_data_hash'] != $_SESSION['sentireport']['district_details_array']['hash']) {
		
				$tmp_sql = "SELECT *
							FROM district_data
							WHERE hash = '". $subscriber_details_array['district_data_hash'] ."'
							;";
				//test("tmp_sql",$tmp_sql);
				$district_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
				//test("district_details_array",$district_details_array);
				
				$_SESSION['sentireport']['district_details_array'] = $district_details_array;
			
			} else {
				
				$district_details_array = $_SESSION['sentireport']['district_details_array'];
				
			}
			
			
			
			$cities_array = explode(",",$district_details_array['CITIES']);
			//test("cities_array",$cities_array);
			foreach($cities_array AS $key => $city_name) {
				if(trim($city_name)) {
					$final_city_array[] = trim($city_name);
				}
			}
			
			
			$cities_array = explode(",",$district_details_array['TOWNS']);
			//test("cities_array",$cities_array);
			foreach($cities_array AS $key => $city_name) {
				if(trim($city_name)) { 
					$final_city_array[] = trim($city_name);
				}
			}
			
			
			$cities_array = explode(",",$district_details_array['UNINCORPORATED_PLACES']);
			//test("cities_array",$cities_array);
			foreach($cities_array AS $key => $city_name) {
				if(trim($city_name)) {
					$final_city_array[] = trim($city_name);
				}
			}
			
			
			$cities_array = explode(",",$district_details_array['VILLAGES']);
			//test("cities_array",$cities_array);
			foreach($cities_array AS $key => $city_name) {
				if(trim($city_name)) {
					$final_city_array[] = trim($city_name);
				}
			}
			
			//test("final_city_array",$final_city_array);
			return array_values($final_city_array);
			
		}
		
			
	}	
	
	
	
	///  IF DISTRICT REP
	if($subscriber_details_array['location_district_number']) {	
		
		
		
		$get_district_details = get_district_details($subscriber_hash);
		//test("get_district_details",$get_district_details);
		
		$final_city_array = $get_district_details['cities'];
		//test("final_city_array",$final_city_array);
		
	
	///  ELSE COUNTY:
	} else {			
	
		$tmp_sql = "SELECT * 
		FROM state_county_city 
		WHERE postal_code = '". $subscriber_details_array['location_postal_code'] ."'
		;";
		//test("tmp_sql",$tmp_sql);
		$subscriber_state_county_city_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		//test("subscriber_state_county_city_details_array",$subscriber_state_county_city_details_array);
		
		$_SESSION['subscriber_state_county_city_details_array'] = $subscriber_state_county_city_details_array;
		
		
		
		$tmp_sql = "SELECT DISTINCT(city)
					FROM state_county_city
					WHERE county = '". $subscriber_state_county_city_details_array['county'] ."'
					AND state = '". $subscriber_state_county_city_details_array['state'] ."'
					;";
		//test("tmp_sql",$tmp_sql);
		$county_city_array = readarrayTHECASHIER($tmp_sql,"senti");
		//test("county_city_array",$county_city_array);
		
		
		$final_city_array = array();
		foreach($county_city_array AS $city_key => $city) {
			
			$final_city_array[$city_key] = $city['city'];												
			
		}
	
	} 
	
	
	
	
	
	return $final_city_array;
}


function get_district_details($subscriber_hash) {
	
	
	
	//test("subscriber_hash",$subscriber_hash);
	
	
	if($_SESSION['sentireport']['subscriber_details_array']['hash'] != $subscriber_hash) {
	
		$tmp_sql = "SELECT *
				FROM subscribers
				WHERE hash = '". $subscriber_hash ."'
				;";
		//test("tmp_sql",$tmp_sql);
		$subscriber_details = readTHECASHIER($tmp_sql,"senti");
		//test("subscriber_details",$subscriber_details);
		$subscriber_details = object_to_array_v2($subscriber_details);
		//test("subscriber_details",$subscriber_details);
		
		$_SESSION['sentireport']['subscriber_details_array'] = $subscriber_details;
		
	
	} else {
		
		$subscriber_details = $_SESSION['sentireport']['subscriber_details_array'];
		
	}
	
	


	# $subscriber_details['location_district_number'] = number_format($subscriber_details['location_district_number']);
	# 
	# $tmp_sql = "SELECT *
	# 			FROM district_data
	# 			WHERE STATE_ISO2 = '". $subscriber_details['state_iso2'] ."'
	# 			AND DISTRICT = '". $subscriber_details['location_district_number'] ."'
	# 			;";
	# test("tmp_sql",$tmp_sql);



	if($_SESSION['sentireport']['subscriber_details_array']['district_data_hash'] != $_SESSION['sentireport']['district_details_array']['hash']) {

		$tmp_sql = "SELECT *
					FROM district_data
					WHERE hash = '". $subscriber_details['district_data_hash'] ."'
					;";
		test("tmp_sql",$tmp_sql);
		$district_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		test("district_details_array",$district_details_array);
		
		$_SESSION['sentireport']['district_details_array'] = $district_details_array;
		
	
	} else {
		
		$district_details_array = $_SESSION['sentireport']['district_details_array'];
		
	}
		
		
			

	//test("district_details_array",$district_details_array);
	
	$return['postal_codes'] = array_values(array_map('trim',explode(",",$district_details_array['ZIP_CODES'])));
	
	$return['cities'] = array_values(array_map('trim',explode(",",$district_details_array['CITIES'])));
	
	$return['towns'] = array_values(array_map('trim',explode(",",$district_details_array['TOWNS'])));
	
	
	$return['unincorporated'] = array_values(array_map('trim',explode(",",$district_details_array['UNINCORPORATED_PLACES'])));
	
	
	
	$return['school_districts'] = array_values(array_map('trim',explode(",",$district_details_array['SCHOOL_DISTRICTS'])));
	
	
	$return['counties'] = array_values(array_map('trim',explode(",",$district_details_array['COUNTIES'])));

	return $return;
	
}



function get_data_crime_trailing_totals($subscriber_hash,$start_days_ago,$trailing_days) {
	
	$trailing_days = $trailing_days + $start_days_ago - 1;

	$sentireport_get_cities = sentireport_get_cities($subscriber_hash);
	
	//test("sentireport_get_cities",$sentireport_get_cities);
	
	
	
	foreach($sentireport_get_cities AS $city_key => $city) {
	
		if($city_key == 0) {
			$where_city = "WHERE (target_city = '". addslashes($city) ."'";
		} else {
			$where_city .= " OR target_city = '". addslashes($city) ."'";
		}
		
	}
	$where_city .= ")";
	
	// show all
	//$where_city = "";
	
	
	$key = $trailing_days - $start_days_ago;
	while($start_days_ago <= $trailing_days) {
		
		$tmp_sql = "SELECT hash
					FROM data_crime
					$where_city
					AND crime_datetime LIKE '%". date("Y-m-d",strtotime(" -". $trailing_days . " DAYS")) ."%'
					;";
		//test("tmp_sql",$tmp_sql);
		
		$data_crime[$key] = count(readarrayTHECASHIER($tmp_sql,"senti"));
		//test("data_crime",$data_crime);
		$trailing_days--;
		$key--;
	}
	
	return $data_crime;

}





function get_data_crime_mapping_details($subscriber_hash,$days) {
	
	

	$get_district_details = get_district_details($subscriber_hash);
	
	if(stristr($_SERVER['HTTP_HOST'],"cron_")) {
		test("get_district_details",$get_district_details);
	}
	
	
	foreach($get_district_details['postal_codes'] AS $key_postal_codes => $postal_code) {
	
		if($key_postal_codes == 0) {
			$where_postal_code = "WHERE (postal_code = '". addslashes($postal_code) ."'";
		} else {
			$where_postal_code .= " OR postal_code = '". addslashes($postal_code) ."'";
		}
		
	}
	$where_postal_code .= ")";
	
	
	
		
	$tmp_sql = "SELECT *
				FROM data_crime
				$where_postal_code
				AND datetime > '". date("Y-m-d 00:00:00",strtotime(" -". $days . " DAYS")) ."'
				;";
	if(stristr($_SERVER['HTTP_HOST'],"cron_")) {
		test("tmp_sql",$tmp_sql);
	}
	
	$data_crime = readarrayTHECASHIER($tmp_sql,"senti");
		
	
	
	return $data_crime;
}






function sentireport_get_subscriber_cities($subscriber_details_array) {
			

	//test("subscriber_details_array",$subscriber_details_array);
	
	if($subscriber_details_array['district_details']['CITIES']) {
		
		$list_of_cities = explode(",",$subscriber_details_array['district_details']['CITIES']);
		foreach($list_of_cities AS $key => $cities) {
			
			$final_city_array[] = trim($cities);
			
		}
		
		//test("final_city_array",$final_city_array);
		
		
		
		
	} else {
		
		//test("000_subscriber_details_array",$subscriber_details_array);
		
		
		
		///  IF DISTRICT REP
		if($subscriber_details_array['location_district_number']) {	
			
			
			//test("111_subscriber_details_array['hash']",$subscriber_details_array['hash']);
			
			$get_district_details = get_district_details($subscriber_details_array['hash']);
			
			//test("222_get_district_details",$get_district_details);
			
			$final_city_array = array_filter(array_merge($get_district_details['cities'],$get_district_details['towns'],$get_district_details['unincorporated']));
			
		
		
		
		///  ELSE COUNTY:
		} else {			
		
			$tmp_sql = "SELECT DISTINCT(city)
						FROM state_county_city
						WHERE county = '". $subscriber_state_county_city_details_array['county'] ."'
						AND state = '". $subscriber_details_array['state_iso2'] ."'
						;";
			//test("tmp_sql",$tmp_sql);
			$county_city_array = readarrayTHECASHIER($tmp_sql,"senti");
			//test("county_city_array",$county_city_array);
			
			
			$final_city_array = array();
			foreach($county_city_array AS $city_key => $city) {
				
				$final_city_array[$city_key] = $city['city'];												
				
			}
		
		} 
		
		
		
		
		//test("final_city_array",$final_city_array);
		//exit;
	}
	
	
	
	
	return array_values($final_city_array);
}





function sentireport_get_subscriber_district_details($subscriber_details) {
	
		

	if($subscriber_details['district_data_hash'] != $_SESSION['sentireport']['district_details_array']['hash']) {
		
		$tmp_sql = "SELECT *
					FROM district_data
					WHERE DISTRICT = '". $subscriber_details['location_district_number'] ."'
					AND state_iso2 = '". $subscriber_details['state_iso2'] ."'
					;";
		
		$district_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		
		$_SESSION['sentireport']['district_details_array'] = $district_details_array;
	
	} else {
		
		$district_details_array = $_SESSION['sentireport']['district_details_array'];
		
	}
	
	
	
	//test("district_details_array",$district_details_array);
	
	$return['postal_codes'] = array_map('trim',explode(",",$district_details_array['ZIP_CODES']));
	
	$return['cities'] = array_map('trim',explode(",",$district_details_array['CITIES']));
	
	$return['towns'] = array_map('trim',explode(",",$district_details_array['TOWNS']));
	
	
	$return['unincorporated'] = array_map('trim',explode(",",$district_details_array['UNINCORPORATED_PLACES']));
	
	
	
	$return['school_districts'] = array_map('trim',explode(",",$district_details_array['SCHOOL_DISTRICTS']));
	
	
	$return['counties'] = array_map('trim',explode(",",$district_details_array['COUNTIES']));

	return $return;
	
}





function get_subscriber_latitude_longitude_centerpoint($subscriber_details_array) {


	//test("subscriber_details_array",$subscriber_details_array);
	
	$centerpoint_version = 2;
	
	
	if($centerpoint_version == 1) {
		
		//$sentireport_get_cities = sentireport_get_cities($subscriber_details_array['hash']);
		$sentireport_get_cities = sentireport_get_subscriber_cities($subscriber_details_array);
		//test("sentireport_get_cities",$sentireport_get_cities);
		
		
		$county_city_details_array = array();
		
		foreach($sentireport_get_cities AS $key => $city) {
			
			$tmp_sql = "SELECT *
						FROM state_county_city
						WHERE city = '". $city ."'
						AND state = '". $subscriber_details_array['state_iso2'] ."'
						LIMIT 1
						;";
			//test("tmp_sql",$tmp_sql);
			
			$county_city_details_array[$key] = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
			
			//test("county_city_details_array",$county_city_details_array);
			
		}
		
		
		//test("county_city_details_array",$county_city_details_array);
		//exit;
		
		
		
		/// GET CENTERPOINT
		
		$location_array = array();
		
		foreach($county_city_details_array AS $city_key => $city_details) {
			
			//test("city_details",$city_details);
			
			if(
				($city_details['latitude'])
				&& ($city_details['longitude'])
			) {
				$latitude = $city_details['latitude'];
				$longitude = $city_details['longitude'];
				$location_array[$city_key] = array($latitude,$longitude);
				
				$_SESSION['sentireport']['twitter']['cities_to_search'][$city_key] = $city_details['city'];
				
				
				
			}
		}
		
		//test("location_array",$location_array);
		//exit;
		
		return $centerpoint_array = GetCenterFromDegrees($location_array);
	
	
	} else if($centerpoint_version == 2) {
		
		logger3("get_subscriber_latitude_longitude_centerpoint(subscriber_details_array['district_details'])",$subscriber_details_array['district_details']);
		
		
		if(
			($subscriber_details_array['district_data_hash'])
			&& ($subscriber_details_array['district_data_hash'] == $_SESSION['sentireport']['district_details_array']['hash'])
		) {
			
			$subscriber_details_array['district_details'] = $_SESSION['sentireport']['district_details_array'];
			
		}
		
		
		
		if(!$subscriber_details_array['district_details']) {
	
			$tmp_sql = "SELECT *
						FROM district_data
						WHERE hash = '". $subscriber_details_array['district_data_hash'] ."'
						;";
			
			logger3("get_subscriber_latitude_longitude_centerpoint(tmp_sql)",$tmp_sql);
				
			$subscriber_details_array['district_details'] = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
			
			$_SESSION['sentireport']['district_details_array'] = $subscriber_details_array['district_details'];
			
			logger3("subscriber_details_array['district_details'](tmp_sql)",$subscriber_details_array['district_details']);
			
		}
		
		$centerpoint['latitude'] = $subscriber_details_array['district_details']['centerpoint_latitude'];
		$centerpoint['longitude'] = $subscriber_details_array['district_details']['centerpoint_longitude'];
		return $centerpoint;
		
	}

}	


function run_twitter_category_sentiscore_routine($category,$query,$latitude,$longitude,$radius="") {


	global $subscriber_details;
	$_XXXXX_category = $category;
	global $datetime_common_today;
	
	
	
	
	#######################################################
	#######################################################
	#######################################################
	### STEP 1:  GET THE TWEETS
	
	$minimum_tweets_found = 1;
	$minimum_tweets_found_key = $minimum_tweets_found - 1;

	
	if(!$radius) $radius = "50km";
	
	$search_twitter_response['statuses'] = "";
	
	while(
		(!$search_twitter_response['statuses'][$minimum_tweets_found_key])
		&& ($radius != "end")
	) {
		
		
		
		//test("query",$query);
		//test("longitude",$longitude);
		//test("latitude",$latitude);
		//test("radius",$radius);
		
		$search_twitter_response = search_twitter($query,$longitude,$latitude,$radius);
		
		//test("4 search_twitter_response",$search_twitter_response);
		
		$search_twitter_response = object_to_array_v2($search_twitter_response);
		//logger3("search_twitter_response",$search_twitter_response);
		
		if($search_twitter_response['errors'][0]['code']) {
			logger3("radius",$radius);
			logger3("query",$query); 
			logger3("search_twitter_response['errors'][0]['code']",$search_twitter_response['errors'][0]['code']); 
			exit;
		}
		
		if($radius == "10km") $radius = "20km";
		if($radius == "20km") $radius = "50km";
		if($radius == "50km") $radius = "100km";
		if($radius == "100km") $radius = "200km";
		if($radius == "200km") $radius = "500km";
		if($radius == "500km") $radius = "750km";
		if($radius == "750km") $radius = "1000km";
		if($radius == "750km") $radius = "end";
		//sleep(1);
		// temp fixed.
		//$radius = "end";
		
		
	}
	
	
	$search_twitter_response_array = $search_twitter_response['statuses'];
	
	//test("$search_twitter_response_array",$search_twitter_response_array);
	//exit;
	

	#######################################################
	#######################################################
	#######################################################
	### STEP 2:  SENTISCORE AND DATABASE EACH TWEETS
	

	$total_scored_tweets = 0;
	$accumulated_sentiment_score = 0;
	foreach($search_twitter_response_array AS $key => $tweet_details) {
		
		
		$tweet_details = object_to_array_v2($tweet_details);
		
		//test("tweet_details",$tweet_details);
		
		$tmp_sql = "SELECT *
					FROM category_tweets
					WHERE id_str = '". $tweet_details['id_str'] ."'
					;";
		//test("tmp_sql",$tmp_sql);
		$tweet_exists = object_to_array(readTHECASHIER($tmp_sql,"senti"));
		//test("tweet_exists",$tweet_exists);
		
		//exit;
		
		if(!$tweet_exists['hash']) {
		
		
		
		
			//exit;
			##################################
			### GET THE TWEET SENTIMENT SCORE:
			##################################
			
			$text_string_to_scrore = $tweet_details["full_text"];
			
			//test("text_string_to_scrore",$text_string_to_scrore);
			
			$_XXXXX_sentiscore = get_ibm_sentiment_score($text_string_to_scrore,$ibm_username="",$ibm_password="",$ibm_version="");
			
			//test("_XXXXX_sentiscore",$_XXXXX_sentiscore);
			
			//exit;
		
					
			############################################
			### DATABASE THE TWEET DETAILS + SENTISCORE:
			############################################
			
			$_XXXXX_category_tweets_id = "";
			$_XXXXX_hash = hash_me();
			$_XXXX_subscriber_hash = $subscriber_details['hash'];
			$_XXXXX_category = $_XXXXX_category;
			$_XXXXX_source = addslashes($tweet_details['source']);
			$_XXXXX_name = addslashes($tweet_details['user']['name']);
			$_XXXXX_screen_name = addslashes($tweet_details['user']['screen_name']);
			$_XXXXX_location = addslashes($tweet_details['user']['location']);
			$_XXXXX_followers_count = addslashes($tweet_details['user']['followers_count']);
			$_XXXXX_friends_count = addslashes($tweet_details['user']['friends_count']);
			$_XXXXX_listed_count = addslashes($tweet_details['user']['listed_count']);
			$_XXXXX_favourites_count = addslashes($tweet_details['user']['favourites_count']);
			$_XXXXX_statuses_count = addslashes($tweet_details['user']['statuses_count']);
			$_XXXXX_full_text = addslashes($tweet_details['full_text']);
			$_XXXXX_id_str = addslashes($tweet_details['id_str']);
			
			$_XXXXX_retweet_count = addslashes($tweet_details['retweet_count']);
			$_XXXXX_favorite_count = addslashes($tweet_details['favorite_count']);
			$_XXXXX_favorited = addslashes($tweet_details['favorited']);
			$_XXXXX_retweeted = addslashes($tweet_details['retweeted']);
			
			$_XXXXX_created_at = datetime_v2(strtotime($tweet_details['created_at']));
			$_XXXXX_datetime_created = $datetime_common_today;
			
			$tmp_sql = "INSERT INTO `category_tweets`
						(
							`category_tweets_id`
							, `hash`
							, `subscriber_hash`
							, `category`
							, `source`
							, `name`
							, `screen_name`
							, `location`
							, `followers_count`
							, `friends_count`
							, `listed_count`
							, `favourites_count`
							, `statuses_count`
							, `full_text`
							, `id_str`
							
							, `retweet_count`
							, `favorite_count`
							, `favorited`
							, `retweeted`
							
							, `sentiscore`
							
							, `created_at`
							, `datetime_created`
						) VALUES (
							'". $_XXXXX_category_tweets_id ."'
							, '". $_XXXXX_hash ."'
							, '". $_XXXX_subscriber_hash ."'
							, '". $_XXXXX_category ."'
							, '". $_XXXXX_source ."'
							, '". $_XXXXX_name ."'
							, '". $_XXXXX_screen_name ."'
							, '". $_XXXXX_location ."'
							, '". $_XXXXX_followers_count ."'
							, '". $_XXXXX_friends_count ."'
							, '". $_XXXXX_listed_count ."'
							, '". $_XXXXX_favourites_count ."'
							, '". $_XXXXX_statuses_count ."'
							, '". $_XXXXX_full_text ."'
							, '". $_XXXXX_id_str ."'
							
							, '". $_XXXXX_retweet_count ."'
							, '". $_XXXXX_favorite_count ."'
							, '". $_XXXXX_favorited ."'
							, '". $_XXXXX_retweeted ."'
							
							
							, '". $_XXXXX_sentiscore ."'
							
							, '". $_XXXXX_created_at ."'
							, '". $_XXXXX_datetime_created ."'
						);";
			logger3("tmp_sql",$tmp_sql);
			$insert_results = insertTHECASHIER($tmp_sql,"senti");
			logger3("insert_results",$insert_results);
		
		
		
			
		
		} else {
			
			$_XXXXX_sentiscore = $tweet_exists['sentiscore'];
			$tweet_details['retweet_count'] = $tweet_exists['retweet_count'];
			
		}
			
		
		
		#################################################
		### TRACK ACCUMULATED TWEET STATS + SENTISCORES:
		#################################################
		
		if($_XXXXX_sentiscore != 0) {
			
			$sentiment_score_accumulated = $sentiment_score_accumulated + $_XXXXX_sentiscore;
			logger3("sentiment_score_accumulated",$sentiment_score_accumulated);
			
			
			$total_scored_tweets++;
			logger3("total_scored_tweets",$total_scored_tweets);
			
			
			$total_retweets = $total_retweets + $tweet_details['retweet_count'];
			
			$current_sentiscore = $sentiment_score_accumulated / $total_scored_tweets;
			logger3("current_sentiscore",$current_sentiscore);
			
			
		}	
	}
	
	##############################################################
	##############################################################
	##############################################################
	### STEP 3:  DATABASE THE ACCUMULATED CATEGORY STATS + SCORES
	
	
	
	$_XXXXX_sentiscore_categories_id = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_subscriber_hash = $subscriber_details['hash'];
	$_XXXXX_category = $_XXXXX_category;
	$_XXXXX_number_of_tweets = $total_scored_tweets;
	$_XXXXX_number_of_retweets = $total_retweets;
	$_XXXXX_sentiscore = $current_sentiscore;
	$_XXXXX_datetime_created = $datetime_common_today;
	
	$tmp_sql = "INSERT INTO `twitter_category_sentiscores`
				(
					`sentiscore_categories_id`
					, `hash`
					, `subscriber_hash`
					, `category`
					, `number_of_tweets`
					, `number_of_retweets`
					, `sentiscore`
					, `datetime_created`
				) VALUES (
					'". $_XXXXX_sentiscore_categories_id ."'
					, '". $_XXXXX_hash ."'
					, '". $_XXXXX_subscriber_hash ."'
					, '". $_XXXXX_category ."'
					, '". $_XXXXX_number_of_tweets ."'
					, '". $_XXXXX_number_of_retweets ."'
					, '". $_XXXXX_sentiscore ."'
					, '". $_XXXXX_datetime_created ."'
				);";
	logger3("tmp_sql",$tmp_sql);
	$insert_results = insertTHECASHIER($tmp_sql,"senti");
	logger3("insert_results",$insert_results);
}





function run_twitter_trends_sentiscore_routine($WOEID,$hashtag_details_array,$latitude,$longitude,$radius="") {

	//test("hashtag_details_array",$hashtag_details_array);
	
	global $subscriber_details;
	$_XXXXX_category = "Trending Hashtags";
	global $datetime_common_today;
	
	
	
	
	#######################################################
	#######################################################
	#######################################################
	### STEP 1:  GET THE TWEETS
	
	$minimum_tweets_found = 1;
	//test("minimum_tweets_found",$minimum_tweets_found);
	
	$minimum_tweets_found_key = $minimum_tweets_found - 1;
	//test("minimum_tweets_found_key",$minimum_tweets_found_key);

	
	if(!$radius) $radius = "250km";
	//test("radius",$radius);
	
	$search_twitter_response['statuses'] = "";
	//test("search_twitter_response['statuses']",$search_twitter_response['statuses']);
	
	while(
		(!$search_twitter_response['statuses'][$minimum_tweets_found_key])
		&& ($radius != "end")
	) {
		
		//test("search_twitter_response['statuses'][$minimum_tweets_found_key]",$search_twitter_response['statuses'][$minimum_tweets_found_key]);
		//test("radius",$radius);
		
		//test("hashtag_details_array",$hashtag_details_array);
		//test("longitude",$longitude);
		//test("latitude",$latitude);
		//test("radius",$radius);
		
		$query = $hashtag_details_array['name'];
		$search_twitter_response = search_twitter($query,$longitude,$latitude,$radius);
		
		//test("4 search_twitter_response",$search_twitter_response);
		
		$search_twitter_response = object_to_array_v2($search_twitter_response);
		//test("search_twitter_response",$search_twitter_response);
		
		if($search_twitter_response['errors'][0]['code']) {
			logger3("radius",$radius);
			logger3("hashtag_details_array",$hashtag_details_array); 
			logger3("search_twitter_response['errors'][0]['code']",$search_twitter_response['errors'][0]['code']); 
			exit;
		}
		
		if($radius == "10km") $radius = "20km";
		if($radius == "20km") $radius = "50km";
		if($radius == "50km") $radius = "100km";
		if($radius == "100km") $radius = "250km";
		if($radius == "250km") $radius = "1000km";
		if($radius == "1000km") $radius = "end";
		//sleep(1);
		// temp fixed.
		//$radius = "end";
		
		
	}
	
	
	$search_twitter_response_array = $search_twitter_response['statuses'];
	
	//test("search_twitter_response_array",$search_twitter_response_array);
	//exit;
	

	#######################################################
	#######################################################
	#######################################################
	### STEP 2:  SENTISCORE AND DATABASE EACH TWEETS
	


	$total_scored_tweets = 0;
	$accumulated_sentiment_score = 0;
	foreach($search_twitter_response_array AS $key_score_tweets => $tweet_details) {
		
		
		
		
		$tweet_details = object_to_array_v2($tweet_details);
		
		
		//test("tweet_details",$tweet_details);
		
		$tmp_sql = "SELECT *
					FROM category_tweets
					WHERE id_str = '". $tweet_details['id_str'] ."'
					;";
		//test("tmp_sql",$tmp_sql);
		$tweet_exists = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		//test("tweet_exists",$tweet_exists);
		
		//exit;
		
		logger3("tweet_exists['hash']",$tweet_exists['hash']);
		
		
		if(!$tweet_exists['hash']) {  //don't score again, but save the new tweet details:
		
		
			//exit;
			##################################
			### GET THE TWEET SENTIMENT SCORE:
			##################################
			
			$text_string_to_scrore = $tweet_details["full_text"];
			
			//test("text_string_to_scrore",$text_string_to_scrore);
			
			$_XXXXX_sentiscore = get_ibm_sentiment_score($text_string_to_scrore,$ibm_username="",$ibm_password="",$ibm_version="");
			
			//test("run_twitter_trends_sentiscore_routine: _XXXXX_sentiscore",$_XXXXX_sentiscore);
			
			//exit;
		
		} else {
			
			
			$_XXXXX_sentiscore = $tweet_exists['sentiscore'];
			
		}
		
		//test("_XXXXX_sentiscore",$_XXXXX_sentiscore);
		
		//exit;
					
		############################################
		### DATABASE THE TWEET DETAILS + SENTISCORE:
		############################################
		
		$_XXXXX_category_tweets_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXX_subscriber_hash = $subscriber_details['hash'];
		
		$_XXXXX_category = addslashes("Trending Hashtag");
		
		$_XXXXX_hashtag = addslashes($hashtag_details_array['name']);
		$_XXXXX_WOEID = $WOEID;
		
		$_XXXXX_source = addslashes($tweet_details['source']);
		$_XXXXX_name = addslashes($tweet_details['user']['name']);
		$_XXXXX_screen_name = addslashes($tweet_details['user']['screen_name']);
		$_XXXXX_location = addslashes($tweet_details['user']['location']);
		$_XXXXX_followers_count = addslashes($tweet_details['user']['followers_count']);
		$_XXXXX_friends_count = addslashes($tweet_details['user']['friends_count']);
		$_XXXXX_listed_count = addslashes($tweet_details['user']['listed_count']);
		$_XXXXX_favourites_count = addslashes($tweet_details['user']['favourites_count']);
		$_XXXXX_statuses_count = addslashes($tweet_details['user']['statuses_count']);
		$_XXXXX_full_text = addslashes($tweet_details['full_text']);
		$_XXXXX_id_str = addslashes($tweet_details['id_str']);
		
		$_XXXXX_retweet_count = addslashes($tweet_details['retweet_count']);
		$_XXXXX_favorite_count = addslashes($tweet_details['favorite_count']);
		$_XXXXX_favorited = addslashes($tweet_details['favorited']);
		$_XXXXX_retweeted = addslashes($tweet_details['retweeted']);
		
		$_XXXXX_created_at = datetime_v2(strtotime($tweet_details['created_at']));
		$_XXXXX_datetime_created = $datetime_common_today;
		
		$tmp_sql = "INSERT INTO `category_tweets`
					(
						`category_tweets_id`
						, `hash`
						, `subscriber_hash`
						, `category`
						
						, `hashtag`
						, `WOEID`
						
						, `source`
						, `name`
						, `screen_name`
						, `location`
						, `followers_count`
						, `friends_count`
						, `listed_count`
						, `favourites_count`
						, `statuses_count`
						, `full_text`
						, `id_str`
						
						, `retweet_count`
						, `favorite_count`
						, `favorited`
						, `retweeted`
						
						, `sentiscore`
						
						, `created_at`
						, `datetime_created`
					) VALUES (
						'". $_XXXXX_category_tweets_id ."'
						, '". $_XXXXX_hash ."'
						, '". $_XXXX_subscriber_hash ."'
						, '". $_XXXXX_category ."'
						
						, '". $_XXXXX_hashtag ."'
						, '". $_XXXXX_WOEID ."'
						
						, '". $_XXXXX_source ."'
						, '". $_XXXXX_name ."'
						, '". $_XXXXX_screen_name ."'
						, '". $_XXXXX_location ."'
						, '". $_XXXXX_followers_count ."'
						, '". $_XXXXX_friends_count ."'
						, '". $_XXXXX_listed_count ."'
						, '". $_XXXXX_favourites_count ."'
						, '". $_XXXXX_statuses_count ."'
						, '". $_XXXXX_full_text ."'
						, '". $_XXXXX_id_str ."'
						
						, '". $_XXXXX_retweet_count ."'
						, '". $_XXXXX_favorite_count ."'
						, '". $_XXXXX_favorited ."'
						, '". $_XXXXX_retweeted ."'
						
						
						, '". $_XXXXX_sentiscore ."'
						
						, '". $_XXXXX_created_at ."'
						, '". $_XXXXX_datetime_created ."'
					);";
		logger3("tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql,"senti");
		logger3("insert_results",$insert_results);
		

		
		
			


		#################################################
		### TRACK ACCUMULATED TWEET STATS + SENTISCORES:
		#################################################
		
		if($_XXXXX_sentiscore != 0) {
			
			$sentiment_score_accumulated = $sentiment_score_accumulated + $_XXXXX_sentiscore;
			logger3("sentiment_score_accumulated",$sentiment_score_accumulated);
			
			
			$total_scored_tweets++;
			logger3("total_scored_tweets",$total_scored_tweets);
			
			
			$total_retweets = $total_retweets + $tweet_details['retweet_count'];
			
			$current_sentiscore = $sentiment_score_accumulated / $total_scored_tweets;
			logger3("current_sentiscore",$current_sentiscore);
			
			
		}		

		
		/// LIMIT TWEETS TO SCORE PER HASHTAG (includes previously scored tweets -- so MAX will be the limit)
		//test("_SESSION['sentireport']['run_twitter_trends_sentiscore_routine']['limits_tweets_to_score_per_hashtag']",$_SESSION['sentireport']['run_twitter_trends_sentiscore_routine']['limits_tweets_to_score_per_hashtag']);
		
		logger3("$total_scored_tweets",$total_scored_tweets);
		
		if($total_scored_tweets == $_SESSION['sentireport']['run_twitter_trends_sentiscore_routine']['limits_tweets_to_score_per_hashtag']) {
			break; 
		}

	}
	
	
	##############################################################
	##############################################################
	##############################################################
	### STEP 3:  DATABASE THE ACCUMULATED HASHTAG TRENDS STATS + SCORES
	

	
	
	$_XXXXX_twitter_trends_id = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_subscriber_hash = ""; // not used - use WOEID for trends
	$_XXXXX_WOEID = $WOEID;
	$_XXXXX_hashtag = addslashes($hashtag_details_array['name']);
	$_XXXXX_tweet_volume = $hashtag_details_array['tweet_volume'];
	$_XXXXX_number_of_tweets = $tweet_details['tweets'];
	$_XXXXX_number_of_retweets = $tweet_details['retweets'];
	$_XXXXX_sentiscore = $tweet_details['sentiscore'];
	$_XXXXX_datetime_created = $datetime_common_today;
	$tmp_sql = "INSERT INTO `twitter_trends`
				(
					`twitter_trends_id`
					, `hash`
					, `subscriber_hash`
					, `WOEID`
					, `hashtag`
					, `tweet_volume`
					, `number_of_tweets`
					, `number_of_retweets`
					, `sentiscore`
					, `datetime_created`
				) VALUES (
					
					'". $_XXXXX_twitter_trends_id . "'
					, '". $_XXXXX_hash . "'
					, '". $_XXXXX_subscriber_hash . "'
					, '". $_XXXXX_WOEID . "'
					, '". $_XXXXX_hashtag . "'
					, '". $_XXXXX_tweet_volume . "'
					, '". $_XXXXX_number_of_tweets ."'
					, '". $_XXXXX_number_of_retweets ."'
					, '". $_XXXXX_sentiscore . "'
					, '". $_XXXXX_datetime_created . "'
	
				);";
	logger3("tmp_sql",$tmp_sql);
	$insert_results = insertTHECASHIER($tmp_sql,"senti");
	logger3("insert_results",$insert_results);
	
	
	//exit;
	
}










function get_ibm_sentiment_score($text_string_to_scrore,$ibm_username="",$ibm_password="",$ibm_version="") {
	
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("text_string_to_scrore",$text_string_to_scrore);
	}
		


	if(!$ibm_cloud_service_version) $ibm_cloud_service_version = "2018-03-16";
	if(!$ibm_cloud_service_username) $ibm_cloud_service_username = $_SESSION['sentireport']['ibm_natural_language']['service_username'];
	if(!$ibm_cloud_service_password) $ibm_cloud_service_password = $_SESSION['sentireport']['ibm_natural_language']['service_password'];
	
	if(!$text_string_to_scrore) return FALSE;
	
	
	
	
	
	############################################################################################
	############################################################################################
	### IBM DISCOVERY NEWS
	require_once("/BANGK!/_other/sentireport.com/gateway/sentireport_preferences.gate");
	if(!$ibm_premium_service) global $ibm_premium_service;
	
	if(!$_XXXXX_DISPLAY) global $_XXXXX_DISPLAY;
	if(!stristr($_XXXXX_DISPLAY,"DEMO")) {
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("1- ibm_premium_service",$ibm_premium_service);
	}
	}
	if($ibm_premium_service == TRUE) {
		
		
		if(!$_XXXXX_DISPLAY) global $_XXXXX_DISPLAY;
		if(!stristr($_XXXXX_DISPLAY,"DEMO")) {
		if(
			(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
			|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
			|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
		) {
			test("2- ibm_premium_service",$ibm_premium_service);
		}
		}
		
		if(!$ibm_watson_natural_language_PAID_PREMIUM_version) global $ibm_watson_natural_language_PAID_PREMIUM_version;
		if(!$ibm_watson_natural_language_PAID_PREMIUM_username) global $ibm_watson_natural_language_PAID_PREMIUM_username;
		if(!$ibm_watson_natural_language_PAID_PREMIUM_password) global $ibm_watson_natural_language_PAID_PREMIUM_password;
	
		$ibm_cloud_service_version = $ibm_watson_natural_language_PAID_PREMIUM_version;
		$ibm_cloud_service_username = $ibm_watson_natural_language_PAID_PREMIUM_username;
		$ibm_cloud_service_password = $ibm_watson_natural_language_PAID_PREMIUM_password;
	}
	############################################################################################
	############################################################################################	
		
	
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("ibm_cloud_service_version",$ibm_cloud_service_version);
	}
	
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("ibm_cloud_service_username",$ibm_cloud_service_username);
	}
	
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("ibm_cloud_service_password",$ibm_cloud_service_password);
	}
	
	//test("ibm_cloud_service_version",$ibm_cloud_service_version);
	//test("ibm_cloud_service_username",$ibm_cloud_service_username);
	//test("ibm_cloud_service_password",$ibm_cloud_service_password);
	
	//exit;
	
	
	
	$url_encoded_text_string = urlencode($text_string_to_scrore);

	//$features = "sentiment,keywords"; // also works

	$features = "sentiment";
	//$features = "sentiment,relations,categories,concepts,emotion,entities,keywords,metadata,semantic_roles";
	//$features = "sentiment,relations,categories,concepts,emotion,entities,keywords,,semantic_roles";

	$URL = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=". $ibm_cloud_service_version ."&text=" . $url_encoded_text_string . "&features=" . $features;

	if(!$_XXXXX_DISPLAY) global $_XXXXX_DISPLAY;
	if(!stristr($_XXXXX_DISPLAY,"DEMO")) {
	if(stristr($_SERVER['SCRIPT_NAME'],"cron_twitter_categories.gate")) {
		test("URL",$URL);
	}
	}
	
	//
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_INTERFACE,'74.81.189.99');
	curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
	
	curl_setopt($ch, CURLOPT_USERPWD, "$ibm_cloud_service_username:$ibm_cloud_service_password");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_URL, $URL);
	$result = curl_exec($ch);
	
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("result",$result);
	}
	
	
	if ($result === FALSE) {
	    test('natural-language-understanding Error: ' . curl_error($ch));
	}
	curl_close($ch);
	
	$result_array = object_to_array_v2(json_decode($result));
	
	if(
		(stristr($_SERVER['SCRIPT_NAME'],"CRON"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"TEST"))
		|| (stristr($_SERVER['SCRIPT_NAME'],"DEV"))
	) {
		test("result_array",$result_array);
	}
	
	return $result_array['sentiment']['document']['score'];

}



function newCURL_20180822($url,$ip=""){
	
		if(!$ip) $ip = "74.81.189.3";
		
		test("___ip",$ip);
		
		$cookie_file = tempnam("/tmp", "CURLCOOKIE");

		$ch = curl_init();

		curl_setopt ( $ch, CURLOPT_COOKIEJAR, $cookie_file); 
			
		$ch = curl_init();
		curl_setopt( $ch, CURLOPT_URL, $url );
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt( $ch, CURLOPT_INTERFACE, $ip);
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
		
		// I've tried excluding this line, setting it to gzip, and empty string
		curl_setopt( $ch, CURLOPT_ENCODING, '' ); 
		curl_setopt( $ch, CURLOPT_HEADER, 0);
		
		$response = curl_exec( $ch  );
		$content_type = curl_getinfo( $ch, CURLINFO_CONTENT_TYPE );
		
		return $response;
	}


function get_postal_code_details($postal_code,$ip="",$version="") {

	
	
	if(!$ip) $ip = "74.81.189.3";
	if(!$version) $version = 2;
	
	
	test("postal_code",$postal_code);
	test("ip",$ip);
	test("version",$version);
	
	
	if($version == 1) {
		
		////////////////////////
		/// melissadata.com
		////////////////////////
	
		$url = "https://www.melissadata.com/lookups/GeoCoder.asp?InData=". $postal_code . "&submit=Search";
		$page_contents = newCURL_20180822($url,$ip);	
		
		
		test("page_contents",$page_contents);
		
		$page_contents_exploded = explode("Latitude </td><td class='padd'>",$page_contents);
		$page_contents_exploded = explode("</td>",$page_contents_exploded[1]);
		$return['latitude'] = $latitude = $page_contents_exploded[0];
		//test("latitude",$latitude);
		
		
		$page_contents_exploded = explode("Longitude </td><td class='padd'>",$page_contents);
		$page_contents_exploded = explode("</td>",$page_contents_exploded[1]);
		$return['longitude'] = $longitude = $page_contents_exploded[0];
		//test("longitude",$longitude);
		
		$page_contents_exploded = explode("County Name </td><td class='padd'>",$page_contents);
		$page_contents_exploded = explode("</td>",$page_contents_exploded[1]);
		$return['county'] = $FIPS = $page_contents_exploded[0];
		//test("county",$FIPS);
		
		
		
		$page_contents_exploded = explode("County FIPS Code </td><td class='padd'>",$page_contents);
		$page_contents_exploded = explode("</td>",$page_contents_exploded[1]);
		$return['FIPS'] = $FIPS = $page_contents_exploded[0];
		//test("FIPS",$FIPS);
	
		return $return;
	
	}
	
	
	
	if($version == 2) {

		
		////////////////////////
		/// zip-info.com
		////////////////////////
			
		//$url = "https://www.melissadata.com/lookups/GeoCoder.asp?InData=". $postal_code . "&submit=Search";
		$url = "http://www.zip-info.com/cgi-local/zipsrch.exe?cnty=cnty&ac=ac&tz=tz&ll=ll&msa=msa&pop=pop&zip=". $postal_code ."&Go=Go";
		//test("url",$url);
		
		
		$page_contents = newCURL_20180822($url,$ip);	
		
		
		test("page_contents",$page_contents);
		
		//exit;
		
		$page_contents_exploded = explode("<td align=center>",$page_contents);
		
		
		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[3]);
		$return['city_name'] = $final_page_contents_exploded[0];

		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[4]);
		$return['state_iso2'] = $final_page_contents_exploded[0];
		
		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[5]);
		$return['zip_code'] = $final_page_contents_exploded[0];
		
		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[6]);
		$return['county_name'] = $final_page_contents_exploded[0];
		
		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[7]);
		$return['fips_code'] = $final_page_contents_exploded[0];
		
		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[8]);
		$return['area_code'] = $final_page_contents_exploded[0];
		
		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[9]);
		$return['time_zone'] = $final_page_contents_exploded[0];
		
		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[10]);
		$return['daylight_time'] = $final_page_contents_exploded[0];
		
		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[11]);
		$return['latitude'] = $final_page_contents_exploded[0];
		
		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[12]);
		$return['longitude'] = $final_page_contents_exploded[0];
		
		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[13]);
		$return['MSA_PMSA'] = $final_page_contents_exploded[0];
		
		$final_page_contents_exploded = explode("</font>",$page_contents_exploded[14]);
		$return['Census_2012_Population'] = $final_page_contents_exploded[0];
		
		
		

	
		return $return;
	
	}
	
	
	
	
	if($version == 3) {
	
		$url = "https://www.area-codes.com/zip-code/zip-code-". $postal_code .".asp";
		
		$page_contents = newCURL_20180822($url,$ip);
		
		//test("page_contents",$page_contents);
		
		
		
		$page_contents_exploded = explode('Latitude:</strong></td><td width="25%">',$page_contents);
		$latitude = explode('</td>',$page_contents_exploded[1]);
		$return['latitude'] = $latitude[0];
		
		$page_contents_exploded = explode('Longitude:</strong></td><td width="25%">',$page_contents);
		$longitude = explode('</td>',$page_contents_exploded[1]);
		
		$return['longitude'] = $longitude[0];
		//test("return",$return);
		
		return $return;
	
	
	
	}
	
	
	//exit;

}


function get_sentireport_subscriber_details($subscriber_hash) {


	if($_SESSION['sentireport']['subscriber_details_array']['hash'] != $subscriber_hash) {
		
		$tmp_sql = "SELECT *
					FROM subscribers
					WHERE hash = '". $subscriber_hash ."'
					;";
		//test("tmp_sql",$tmp_sql);
		
		$results = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		//test("results",$results);
		
		$_SESSION['sentireport']['subscriber_details_array'] = $results;
		
		return $results;
	
	} else {
		
		return $_SESSION['sentireport']['subscriber_details_array'];
		
	}
}





function sentireport_district_cities($district_hash) {


	if($district_hash != $_SESSION['sentireport']['district_details_array']['hash']) {
		
		$tmp_sql = "SELECT *
			FROM district_data
			WHERE hash = '". $district_hash ."'
			;";
		//test("tmp_sql",$tmp_sql);
		$district_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
		//test("district_details_array",$district_details_array);
		
		$_SESSION['sentireport']['district_details_array'] = $district_details_array;
	
	} else {
		
		$district_details_array = $_SESSION['sentireport']['district_details_array'];
		
	}
	
	
	$cities_array = explode(",",$district_details_array['CITIES']);
	//test("cities_array",$cities_array);
	foreach($cities_array AS $key => $city_name) {
		if(trim($city_name)) {
			$final_city_array[] = trim($city_name);
		}
	}
	
	
	$cities_array = explode(",",$district_details_array['TOWNS']);
	//test("cities_array",$cities_array);
	foreach($cities_array AS $key => $city_name) {
		if(trim($city_name)) { 
			$final_city_array[] = trim($city_name);
		}
	}
	
	
	$cities_array = explode(",",$district_details_array['UNINCORPORATED_PLACES']);
	//test("cities_array",$cities_array);
	foreach($cities_array AS $key => $city_name) {
		if(trim($city_name)) {
			$final_city_array[] = trim($city_name);
		}
	}
	
	
	$cities_array = explode(",",$district_details_array['VILLAGES']);
	//test("cities_array",$cities_array);
	foreach($cities_array AS $key => $city_name) {
		if(trim($city_name)) {
			$final_city_array[] = trim($city_name);
		}
	}
	
	//test("final_city_array",$final_city_array);
	return array_values($final_city_array);


}


function sentireport_district_details($district_hash) {
	
	if($district_hash != $_SESSION['sentireport']['district_details_array']['hash']) {
		
		$tmp_sql = "SELECT *
			FROM district_data
			WHERE hash = '". $district_hash ."'
			;";
		//test("tmp_sql",$tmp_sql);
		$district_details_array = object_to_array_v2(readTHECASHIER($tmp_sql,"senti"));
	
	
	} else {
		
		$district_details_array = $_SESSION['sentireport']['district_details_array'];
		
	}
	
	
	
	return $district_details_array;

}





function pretty_disrict_string($district_details_array) {
						      
																      
    $district = prettySTATE($district_details_array['STATE_ISO2']);

    //logger3("district",$district);
    
    
    if( (strlen($district_details_array['DISTRICT'])) <= 4) {
      
      $district = "District ". $district_details_array['DISTRICT'];
    
    } else if( (strlen($district_details_array['DISTRICT'])) > 4) {
      
      $district = $district_details_array['DISTRICT'];
    }
    

    
    if(
      (!stristr($district,prettySTATE($district_details_array['STATE_ISO2'])))
      && (!stristr($district,$district_details_array['STATE_ISO2']))
    ) {
      $activate_your_district = $district_details_array['STATE_ISO2'] ." ". $district;
    } else {
    
      $activate_your_district = $district;
    
    }
    
    return $activate_your_district;

}





function letters_and_numbers_only($string) {
	
	
	
	if(is_array($string)) {
		
		//test("0",1);
		$new_array = array();
		foreach($string AS $key => $value) {
			
			
			$value = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
			$value = preg_replace("/[^A-Za-z0-9 ]/", "", $value);
			$value = str_ireplace("  ", " ", $value);
			$new_array[] = $value;
			
		}
		
		$string = $new_array;
	
	} else {
	
		//test("0",2);
		$string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
		$string = preg_replace("/[^A-Za-z0-9 ]/", "", $string);
		$string = str_ireplace("  ", " ", $string);
	
	}
	
	
	return $string;
	
}



function letters_and_numbers_only_v2($string) {
	
	
	
	if(is_array($string)) {
		
		//test("0",1);
		$new_array = array();
		foreach($string AS $key => $value) {
			
			
			$value = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
			$value = preg_replace("/[^A-Za-z0-9]/", "", $value);
			$value = str_ireplace("  ", " ", $value);
			$new_array[] = $value;
			
		}
		
		$string = $new_array;
	
	} else {
	
		//test("0",2);
		$string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
		$string = preg_replace("/[^A-Za-z0-9]/", "", $string);
		$string = str_ireplace("  ", " ", $string);
	
	}
	
	
	return $string;
	
}


function letters_and_numbers_and_spaces($string) {
	
	
	
	if(is_array($string)) {
		
		//test("0",1);
		$new_array = array();
		foreach($string AS $key => $value) {
			
			
			$value = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
			$value = preg_replace("/[^A-Za-z0-9\w\ ]/", "", $value);
			$value = str_ireplace("  ", " ", $value);
			$new_array[] = $value;
			
		}
		
		$string = $new_array;
	
	} else {
	
		//test("0",2);
		$string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
		$string = preg_replace("/[^a-zA-Z0-9\-,;.':()[]\"\s]/", "", $string);
		$string = str_ireplace("  ", " ", $string);
	
	}
	
	
	return $string;
	
}


function search_array_for_value($value,$array) {
	
	//test("array",$array);
		
   foreach ($array as $key => $sub_array) {
	   
	   //test("sub_array",$sub_array);
	   
	   $value_found = array_search($value,$sub_array);
	  
	   
	   //test("value_found",$value_found);
	   	   
	   if($value_found) return $key;
	   
   }
}












function insert_google_analyitics($google_analytics_id="",$google_analytics_tag="") {


	if(!$google_analytics_id) $google_analytics_id = trim($_SESSION['template']['company']['google_analytics_id']);
	
	
	//$add_async = "async";
	
	
	echo "
		<!-- Global site tag (gtag.js) - Google Ads: 754799431 -->
		<script ". $add_async ." src='https://www.googletagmanager.com/gtag/js?id=". $google_analytics_id ."'></script>
		<script>
			window.dataLayer = window.dataLayer || [];
			function gtag(){dataLayer.push(arguments);}
			gtag('js', new Date());
		
			gtag('config', '". $google_analytics_id ."');
		</script>
	";
	
	
		
	if($google_analytics_tag) {
		echo "
		<!-- Event snippet for SUCCESSFUL REGISTRATION conversion page -->
		<script>
			gtag('event', 'conversion', {'send_to': '". $google_analytics_id ."/". $google_analytics_tag ."'});
		</script>
	";
		
		
	}
}




function OCR_and_search($url_path_to_original_image,$new_filename,$keyword_1="",$keyword_2="",$keyword_3="",$keyword_4="",$keyword_5="",$keyword_6="",$keyword_7="",$keyword_8="",$keyword_9="",$keyword_10="") {
	
	
	test("url_path_to_original_image",$url_path_to_original_image);
	test("new_filename",$new_filename);
	//// test("keyword_1",$keyword_1);
	//// test("keyword_1",$keyword_2);
	//// test("keyword_1",$keyword_3);
	//// test("keyword_1",$keyword_4);
	//// test("keyword_1",$keyword_5);
	//// test("keyword_1",$keyword_6);
	//// test("keyword_1",$keyword_7);
	//// test("keyword_1",$keyword_8);
	//// test("keyword_1",$keyword_9);
	//// test("keyword_1",$keyword_10);
	
	
	
	$response = "Invalid Source File";
	if($url_path_to_original_image) {
	


		$im = new imagick( $url_path_to_original_image ); 
	
		$image_size = $im->getImageSize();
	
		test("image_size",$image_size);
	
		while($image_size > 3800000) {
			
			test("image_size",$image_size);
			
			$current_width = $im->getImageWidth();
			//// test("convert_image_to_jpeg(current_width)",$current_width);
			
			$current_height = $im->getImageHeight();
			//// test("convert_image_to_jpeg(current_height)",$current_height);
			
			$new_width = $current_width * .6;
			//// test("convert_image_to_jpeg(new_width)",$new_width);
			
			$new_height = $current_height * .6;
			//// test("convert_image_to_jpeg(new_height)",$new_height);
			
			$im->resizeImage($new_width, $new_height, imagick::FILTER_LANCZOS, 1);
			$im->writeImage("/BANGK!/authorizations/ids/". $new_filename); 
			$im->clear();
			$im->destroy(); 
			
			$im = new imagick( "/BANGK!/authorizations/ids/". $new_filename );
			
			
			$image_size = $im->getImageSize();
			
			//// test("convert_image_to_jpeg(image_size)",$image_size);
			
		}
	
		test("--local_path_to_new_jpg)",$local_path_to_new_jpg);
	
	
	
		//// test("time(2)",time());
	
	
	
	
		//////////////////////////////////////////////////////
		/// START: OCR CHECK
		
	
				
		//$filename = "44c50c95022f7bb785cc1dbb1e20713f_photo_id.jpg";
		$filename = $new_filename;
		
				
	
		test("OCR_CHECK(1) filename",$filename);
		
		$path_to_image = "https://authorizations.intelitruth.com/ids/" . $filename;
		test("Source Document to OCR",$path_to_image);
		//sleep(2);
		
		//$local_path_to_new_jpg;
		
		//$microsoft_azure_ocr_response = microsoft_azure_ocr($path_to_image,$microsoft_azure_ocr_key="");
		$microsoft_azure_ocr_response = microsoft_azure_ocr_v2($path_to_image,$microsoft_azure_ocr_key="");
		test("OCR_CHECK(3) microsoft_azure_ocr_response",$microsoft_azure_ocr_response);
		
		
		//// test("time(3)",time());
		
		
		$microsoft_azure_ocr_response = object_to_array_v2($microsoft_azure_ocr_response);
		test("1-microsoft_azure_ocr_response",$microsoft_azure_ocr_response);
		
		$microsoft_azure_ocr_response_json = json_encode($microsoft_azure_ocr_response);
		test("2-microsoft_azure_ocr_response_json",$microsoft_azure_ocr_response_json);
		
		
		# $tmp_sql = "SELECT *
		# 		FROM members
		# 		WHERE hash = '". $incoming_vars['member_hash'] ."'
		# 		";
		# logger3("OCR_CHECK(4) tmp_sql",$tmp_sql);
		# 
		# $member_details = readTHECASHIER($tmp_sql);
		# logger3("OCR_CHECK(5) member_details",$member_details);
		
		
		
		$response = array();
		
		$response['total']['found'] = 0;
		$response['total']['not_found'] = 0;
	
		if($keyword_1) {
		$key = 0;
		$response['details'][$key]['keyword'] = $keyword_1;
		// $response['details'][$key]['not_found'] = 1;
		$response['details'][$key]['found'] = 0;
		if(stristr($microsoft_azure_ocr_response_json,$response['details'][$key]['keyword'])) {
			// $response['details'][$key]['not_found'] = 0;
			$response['details'][$key]['found'] = 1;
			$response['total']['found'] = $response['total']['found'] + 1;
		} else {
			$response['total']['not_found'] = $response['total']['not_found'] + 1;
		}
		}
		
		
		if($keyword_2) {
		$key = $key + 1;
		$response['details'][$key]['keyword'] = $keyword_2;
		// $response['details'][$key]['not_found'] = 1;
		$response['details'][$key]['found'] = 0;
		if(stristr($microsoft_azure_ocr_response_json,$response['details'][$key]['keyword'])) {
			// $response['details'][$key]['not_found'] = 0;
			$response['details'][$key]['found'] = 1;
			$response['total']['found'] = $response['total']['found'] + 1;
		} else {
			$response['total']['not_found'] = $response['total']['not_found'] + 1;
		}
		}
		
		
		
		if($keyword_3) {
		$key = $key + 1;
		$response['details'][$key]['keyword'] = $keyword_3;
		// $response['details'][$key]['not_found'] = 1;
		$response['details'][$key]['found'] = 0;
		if(stristr($microsoft_azure_ocr_response_json,$response['details'][$key]['keyword'])) {
			// $response['details'][$key]['not_found'] = 0;
			$response['details'][$key]['found'] = 1;
			$response['total']['found'] = $response['total']['found'] + 1;
		} else {
			$response['total']['not_found'] = $response['total']['not_found'] + 1;
		}
		}
		
		
		if($keyword_4) {
		$key = $key + 1;
		$response['details'][$key]['keyword'] = $keyword_4;
		// $response['details'][$key]['not_found'] = 1;
		$response['details'][$key]['found'] = 0;
		if(stristr($microsoft_azure_ocr_response_json,$response['details'][$key]['keyword'])) {
			// $response['details'][$key]['not_found'] = 0;
			$response['details'][$key]['found'] = 1;
			$response['total']['found'] = $response['total']['found'] + 1;
		} else {
			$response['total']['not_found'] = $response['total']['not_found'] + 1;
		}
		}
		
		
		
		if($keyword_5) {
		$key = $key + 1;
		$response['details'][$key]['keyword'] = $keyword_5;
		// $response['details'][$key]['not_found'] = 1;
		$response['details'][$key]['found'] = 0;
		if(stristr($microsoft_azure_ocr_response_json,$response['details'][$key]['keyword'])) {
			// $response['details'][$key]['not_found'] = 0;
			$response['details'][$key]['found'] = 1;
			$response['total']['found'] = $response['total']['found'] + 1;
		} else {
			$response['total']['not_found'] = $response['total']['not_found'] + 1;
		}
		}
		
		
		if($keyword_6) {
		$key = $key + 1;
		$response['details'][$key]['keyword'] = $keyword_6;
		// $response['details'][$key]['not_found'] = 1;
		$response['details'][$key]['found'] = 0;
		if(stristr($microsoft_azure_ocr_response_json,$response['details'][$key]['keyword'])) {
			// $response['details'][$key]['not_found'] = 0;
			$response['details'][$key]['found'] = 1;
			$response['total']['found'] = $response['total']['found'] + 1;
		} else {
			$response['total']['not_found'] = $response['total']['not_found'] + 1;
		}
		}
		
		
		
		if($keyword_7) {
		$key = $key + 1;
		$response['details'][$key]['keyword'] = $keyword_7;
		// $response['details'][$key]['not_found'] = 1;
		$response['details'][$key]['found'] = 0;
		if(stristr($microsoft_azure_ocr_response_json,$response['details'][$key]['keyword'])) {
			// $response['details'][$key]['not_found'] = 0;
			$response['details'][$key]['found'] = 1;
			$response['total']['found'] = $response['total']['found'] + 1;
		} else {
			$response['total']['not_found'] = $response['total']['not_found'] + 1;
		}
		}
		
		
		
		if($keyword_8) {
		$key = $key + 1;
		$response['details'][$key]['keyword'] = $keyword_8;
		// $response['details'][$key]['not_found'] = 1;
		$response['details'][$key]['found'] = 0;
		if(stristr($microsoft_azure_ocr_response_json,$response['details'][$key]['keyword'])) {
			// $response['details'][$key]['not_found'] = 0;
			$response['details'][$key]['found'] = 1;
			$response['total']['found'] = $response['total']['found'] + 1;
		} else {
			$response['total']['not_found'] = $response['total']['not_found'] + 1;
		}
		}
		
		
		
		if($keyword_9) {
		$key = $key + 1;
		$response['details'][$key]['keyword'] = $keyword_9;
		// $response['details'][$key]['not_found'] = 1;
		$response['details'][$key]['found'] = 0;
		if(stristr($microsoft_azure_ocr_response_json,$response['details'][$key]['keyword'])) {
			// $response['details'][$key]['not_found'] = 0;
			$response['details'][$key]['found'] = 1;
			$response['total']['found'] = $response['total']['found'] + 1;
		} else {
			$response['total']['not_found'] = $response['total']['not_found'] + 1;
		}
		}
		
		
		if($keyword_10) {
		$key = $key + 1;
		$response['details'][$key]['keyword'] = $keyword_10;
		// $response['details'][$key]['not_found'] = 1;
		$response['details'][$key]['found'] = 0;
		if(stristr($microsoft_azure_ocr_response_json,$response['details'][$key]['keyword'])) {
			// $response['details'][$key]['not_found'] = 0;
			$response['details'][$key]['found'] = 1;
			$response['total']['found'] = $response['total']['found'] + 1;
		} else {
			$response['total']['not_found'] = $response['total']['not_found'] + 1;
		}
		}
	}
	
	
	return $response;
	
}	
	
	

function longitude_latitude_of_profiles_per_enterprise($_XXXXX_whitelabel_business_account_hash="",$_XXXXX_template_company_hash="") {

	if(!$_XXXXX_template_company_hash) $_XXXXX_template_company_hash = $_SESSION['template']['company']['hash'];
	//$_XXXXX_template_company_hash = "133d0a9f43c9465c8f716ce32628e126"; // intelitruth
	//$_XXXXX_whitelabel_business_account_hash = "0159985267bebdf90d22c242941cd8bb";
	
	//$ADD_LIMIT = "LIMIT 5";
	$ADD_PER_CLIENT = "AND whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'"; // UNCOMMENT FOR ENTERPRISE LEVEL
	
	$tmp_sql = "SELECT hash
				FROM members
				WHERE template_company_hash = '". $_XXXXX_template_company_hash ."'
				$ADD_PER_CLIENT
				$ADD_LIMIT
				;";
	//test("tmp_sql",$tmp_sql);
	$member_hash_array = arrayTHECASHIER($tmp_sql);
	//test("member_hash_array",$member_hash_array);
	$record_count = 0;
	$longitude_latitude_array = "";
	$longitude_latitude_array = array();
	foreach($member_hash_array AS $key_member_hash => $member_hash) {
		
		$tmp_sql = "SELECT *
					FROM ips
					WHERE member_hash = '". $member_hash ."'
					AND ip != ''
					ORDER BY created DESC
					LIMIT 1
					;";
		//test("tmp_sql",$tmp_sql);
		$tmp_ip_details = object_to_array_v2(readTHECASHIER($tmp_sql));
		//test("0-tmp_ip_details",$tmp_ip_details);
		
		if($tmp_ip_details['ip']) {
			
			if(!$tmp_ip_details['longitude']) {
				
				$ip2location = "";
				$ip2location = ip2location($tmp_ip_details['ip']);
				//test("1-ip2location",$ip2location);
				
				if(
					($ip2location['longitude'])
					&& ($ip2location['latitude'])
				) {
					$tmp_sql = "UPDATE ips
								SET longitude = '". $ip2location['longitude'] ."'
								, latitude = '". $ip2location['latitude'] ."'
								WHERE ip = '". $tmp_ip_details['ip'] ."'
								;";
					//test("2-tmp_sql",$tmp_sql);
					$update_results = updateTHECASHIER($tmp_sql);
					//test("3-update_results",$update_results);
					
					$tmp_ip_details['longitude'] = $ip2location['longitude'];
					$tmp_ip_details['latitude'] = $ip2location['latitude'];
					$tmp_ip_details['postal_code'] = $ip2location['zip_code'];
					$tmp_ip_details['iso3'] = $ip2location['iso3'];
					
					
				} else {
					
					
					$tml_sql = "UPDATE ips
								SET longitude = 'IP2LOCATION_UNKNOWN'
								, latitude = 'IP2LOCATION_UNKNOWN'
								WHERE ip = '". $tmp_ip_details['ip'] ."'
								;";
					//test("4-tmp_sql",$tmp_sql);
					$update_results = updateTHECASHIER($tmp_sql);
					//test("5-update_results",$update_results);
					
					
					$tmp_ip_details['longitude'] = "IP2LOCATION_UNKNOWN";
					$tmp_ip_details['latitude'] = "IP2LOCATION_UNKNOWN";
					
				}
			}
		}
		
		
		$member_hash_ips_array[$key_member_hash] = $tmp_ip_details;
		
		
		
	}
	
	
	//test("member_hash_ips_array",$member_hash_ips_array);
	
	foreach($member_hash_ips_array AS $key => $location_details) {
		
		//test("location_details",$location_details);
		
			
			
			if(
				($location_details['longitude'])
				&& ($location_details['longitude'] != "IP2LOCATION_UNKNOWN")
			) {
				
				$longitude_latitude_array[$record_count]['longitude'] = $location_details['longitude'];
				$longitude_latitude_array[$record_count]['latitude'] = $location_details['latitude'];
				
				//test("longitude_latitude_array[$record_count]",$longitude_latitude_array[$record_count]);
				
				
				$record_count = $record_count + 1;
			}
			
			
		
	}
	
	
	//test("longitude_latitude_array",$longitude_latitude_array);
	return $longitude_latitude_array;
	
	
}





function get_last_4_weeks_of_profiles_count($_XXXXX_whitelabel_business_account_hash,$_XXXXX_template_company_hash="") {

	if(!$_XXXXX_template_company_hash) $_XXXXX_template_company_hash = $_SESSION['template']['company']['hash'];

	$time_now = time();
	
	$datetime_now = datetime_v2($time_now);
	//test("datetime_now",$datetime_now);
	
	
	$datetime_week_1 = datetime_v2(strtotime("-7 days",$time_now));
	//test("datetime_week_1",$datetime_week_1);
	
	$datetime_week_2 = datetime_v2(strtotime("-14 days",$time_now));
	//test("datetime_week_2",$datetime_week_2);
	
	$datetime_week_3 = datetime_v2(strtotime("-21 days",$time_now));
	//test("datetime_week_3",$datetime_week_3);
	
	$datetime_week_4 = datetime_v2(strtotime("-28 days",$time_now));
	//test("$datetime_week_4",$datetime_week_4);
	
	$tmp_sql = "SELECT count(hash)
				FROM members
				WHERE template_company_hash = '". $_XXXXX_template_company_hash ."'
				AND whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
				AND created > '". $datetime_week_1 ."'
				AND created <= '". $datetime_nowtime_now ."'
				;";
	//test("tmp_sql",$tmp_sql);
	$tmp_results = getTHECASHIER($tmp_sql);
	if(!$tmp_results) $tmp_results = 0;
	$week[0] = $tmp_results;
	//test("week",$week);
	
	
	
	$tmp_sql = "SELECT count(hash)
				FROM members
				WHERE template_company_hash = '". $_XXXXX_template_company_hash ."'
				AND whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
				AND created > '". $datetime_week_2 ."'
				AND created <= '". $datetime_week_1 ."'
				;";
	//test("tmp_sql",$tmp_sql);
	$tmp_results = getTHECASHIER($tmp_sql);
	if(!$tmp_results) $tmp_results = 0;
	$week[1] = $tmp_results;
	//test("week",$week);
	
	
	
	
	$tmp_sql = "SELECT count(hash)
				FROM members
				WHERE template_company_hash = '". $_XXXXX_template_company_hash ."'
				AND whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
				AND created > '". $datetime_week_3 ."'
				AND created <= '". $datetime_week_2 ."'
				;";
	//test("tmp_sql",$tmp_sql);
	$tmp_results = getTHECASHIER($tmp_sql);
	if(!$tmp_results) $tmp_results = 0;
	$week[2] = $tmp_results;
	//test("week",$week);
	
	
	
	$tmp_sql = "SELECT count(hash)
				FROM members
				WHERE template_company_hash = '". $_XXXXX_template_company_hash ."'
				AND whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
				AND created > '". $datetime_week_4 ."'
				AND created <= '". $datetime_week_3 ."'
				;";
	//test("tmp_sql",$tmp_sql);
	$tmp_results = getTHECASHIER($tmp_sql);
	if(!$tmp_results) $tmp_results = 0;
	$week[3] = $tmp_results;
	//test("week",$week);
	
	return $week;

}
	
	

function get_last_12_months_of_profiles_count($_XXXXX_whitelabel_business_account_hash,$_XXXXX_template_company_hash="") {

	if(!$_XXXXX_template_company_hash) $_XXXXX_template_company_hash = $_SESSION['template']['company']['hash'];

	//test("_XXXXX_whitelabel_business_account_hash",$_XXXXX_whitelabel_business_account_hash);
	//test("_XXXXX_template_company_hash",$_XXXXX_template_company_hash);

	$time_now = time();
	
	$datetime_month[0] = datetime_v2($time_now);
	$datetime_month[1] = datetime_v2(strtotime("-1 month",$time_now));
	$datetime_month[2] = datetime_v2(strtotime("-2 months",$time_now));
	$datetime_month[3] = datetime_v2(strtotime("-3 months",$time_now));
	$datetime_month[4] = datetime_v2(strtotime("-4 months",$time_now));
	$datetime_month[5] = datetime_v2(strtotime("-5 months",$time_now));
	$datetime_month[6] = datetime_v2(strtotime("-6 months",$time_now));
	$datetime_month[7] = datetime_v2(strtotime("-7 months",$time_now));
	$datetime_month[8] = datetime_v2(strtotime("-8 months",$time_now));
	$datetime_month[9] = datetime_v2(strtotime("-9 months",$time_now));
	$datetime_month[10] = datetime_v2(strtotime("-10 months",$time_now));
	$datetime_month[11] = datetime_v2(strtotime("-11 months",$time_now));
	$datetime_month[12] = datetime_v2(strtotime("-12 months",$time_now));
	
	
	
	$tmp_month = 0;
	while($tmp_month <= 11) {
		
		$last_month = $tmp_month;
		$tmp_month = $tmp_month + 1;
		$tmp_sql = "SELECT count(hash)
					FROM members
					WHERE template_company_hash = '". $_XXXXX_template_company_hash ."'
					AND whitelabel_business_account_hash = '". $_XXXXX_whitelabel_business_account_hash ."'
					AND created > '". $datetime_month[$tmp_month] ."'
					AND created <= '". $datetime_month[$last_month] ."'
					;";
		//test("tmp_sql",$tmp_sql);
		$tmp_results = getTHECASHIER($tmp_sql);
		if(!$tmp_results) $tmp_results = 0;
		$month[$last_month] = $tmp_results;
		//test("month",$month);
		
	}
	

	
	
	
	
	return $month;

}







function get_list_of_signatures_array($member_hash) {

	
	
	
	///// ids_personal
	if(!$member_hash) return FALSE;

	$tmp_sql = "SELECT *
				FROM ids_personal
				WHERE member_hash = '". $member_hash ."'
				AND additional_personal_documents_json_array LIKE '%signature%'
				ORDER BY datetime_created DESC
				;";
	//test("tmp_sql",$tmp_sql);
	$ids_personal_array = object_to_array_v2(readarrayTHECASHIER($tmp_sql));
	
	
	
	foreach($ids_personal_array AS $ids_personal_array_key => $ids_personal_details) {
		
		$ids_personal_details = object_to_array_v2($ids_personal_details);
		//test("ids_personal_details",$ids_personal_details);
		
		$additional_personal_documents_array_json_decoded = json_decode($ids_personal_details['additional_personal_documents_json_array']);
		
		$additional_personal_documents_array_json_decoded = object_to_array_v2($additional_personal_documents_array_json_decoded);
		
		foreach($additional_personal_documents_array_json_decoded AS $additional_personal_documents_array_json_decoded_key => $additional_personal_documents_details) {
			
			
			$additional_personal_documents_details = object_to_array_v2($additional_personal_documents_details);
			
			//test("x-additional_personal_documents_details",$additional_personal_documents_details);
			
			
			//test("5A-additional_personal_documents_details['document_description']",$additional_personal_documents_details['document_description']);
			
			if(stristr($additional_personal_documents_details['document_description'],"signature")) {
				
				//test("5B-additional_personal_documents_details['document_description']",$additional_personal_documents_details['document_description']);
			
				foreach($additional_personal_documents_details['local_document'] AS $additional_personal_documents_array_json_decoded_key => $additional_personal_documents_url) {
					
					//$additional_personal_documents_details = object_to_array_v2($additional_personal_documents_details);
					
					//test("7-additional_personal_documents_details",$additional_personal_documents_details);
					
					$final_list_of_signature_image_files['personal'][] = $additional_personal_documents_url;
				}
			}
		}

	}
	
	

	$tmp_sql = "SELECT *
				FROM ids_business
				WHERE member_hash = '". $member_hash ."'
				AND additional_business_documents_json_array LIKE '%signature%'
				ORDER BY datetime_created DESC
				;";
	//test("tmp_sql",$tmp_sql);
	$ids_business_array = object_to_array_v2(readarrayTHECASHIER($tmp_sql));
	//test("ids_business_array",$ids_business_array);
	
	
	foreach($ids_business_array AS $ids_business_array_key => $ids_business_details) {
		
		$ids_business_details = object_to_array_v2($ids_business_details);
		//test("ids_personal_details",$ids_personal_details);
		
		$additional_business_documents_array_json_decoded = json_decode($ids_business_details['additional_business_documents_json_array']);
		
		$additional_business_documents_array_json_decoded = object_to_array_v2($additional_business_documents_array_json_decoded);
		
		foreach($additional_business_documents_array_json_decoded AS $additional_business_documents_array_json_decoded_key => $additional_business_documents_details) {
			
			
			$additional_business_documents_details = object_to_array_v2($additional_business_documents_details);
			
			//test("x-additional_personal_documents_details",$additional_personal_documents_details);
			
			
			//test("5A-additional_personal_documents_details['document_description']",$additional_personal_documents_details['document_description']);
			
			if(stristr($additional_business_documents_details['document_description'],"signature")) {
				
				//test("5B-additional_personal_documents_details['document_description']",$additional_personal_documents_details['document_description']);
			
				foreach($additional_business_documents_details['local_document'] AS $additional_business_documents_array_json_decoded_key => $additional_business_documents_url) {
					
					//$additional_personal_documents_details = object_to_array_v2($additional_personal_documents_details);
					
					//test("7-additional_personal_documents_details",$additional_personal_documents_details);
					
					$final_list_of_signature_image_files['business'][] = $additional_business_documents_url;
				}
			}
		}

	}
	
	
	
	
	
	
	
	
	//test("final_list_of_signature_image_files",$final_list_of_signature_image_files);
	
	return array_unique($final_list_of_signature_image_files);

}





function update_whitelabel_preferences($whitelabel_business_account_hash,$preference_name,$preference_value) {


	$_XXXXX_whitelabel_preferences = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
	$_XXXXX_preference_name = $preference_name;
	$_XXXXX_preference_value = $preference_value;
	$_XXXXX_datetime_created = datetime_v2();
	$_XXXXX_datetime_updated = $_XXXXX_datetime_created;
					
					
					
	
	$tmp_sql = "INSERT INTO `whitelabel_preferences`
		(
			`whitelabel_preferences`
			, `hash`
			, `whitelabel_business_account_hash`
			, `preference_name`
			, `preference_value`
			, `datetime_created`
			, `datetime_updated`
		) VALUES (
			'". $_XXXXX_whitelabel_preferences ."'
			,'". $_XXXXX_hash ."'
			,'". $_XXXXX_whitelabel_business_account_hash ."'
			,'". $_XXXXX_preference_name ."'
			,'". $_XXXXX_preference_value ."'
			,'". $_XXXXX_datetime_created ."'
			,'". $_XXXXX_datetime_updated ."'
		)";
	$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");


}






function IEW_get_whitelabel_preferences($whitelabel_business_account_hash,$preference_name) {

	//test("whitelabel_business_account_hash",$whitelabel_business_account_hash);
	//test("preference_name",$preference_name);
	
	if(!$whitelabel_business_account_hash) return false;
	if(!$preference_name) return false;
				
					
	$tmp_sql = "SELECT preference_value
				FROM whitelabel_preferences
				WHERE whitelabel_business_account_hash = '". addslashes($whitelabel_business_account_hash) ."'
				AND preference_name = '". addslashes($preference_name) ."'
				ORDER BY datetime_created DESC
				LIMIT 1
 				;";
	//test("preference_name",$preference_name);	
	$get_results = getTHECASHIER($tmp_sql,"intelitruth");
	$get_results = trim($get_results);
	if(empty($get_results)) return false;
	return $get_results;

}




function proxy_detection($REMOTE_ADDR="") {


	if(!$REMOTE_ADDR) $REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
	
	### $test_HTTP_proxy_headers = array(
	### 	'HTTP_VIA',
	### 	'VIA',
	### 	'Proxy-Connection',
	### 	'HTTP_X_FORWARDED_FOR',  
	### 	'HTTP_FORWARDED_FOR',
	### 	'HTTP_X_FORWARDED',
	### 	'HTTP_FORWARDED',
	### 	'HTTP_CLIENT_IP',
	### 	'HTTP_FORWARDED_FOR_IP',
	### 	'X-PROXY-ID',
	### 	'MT-PROXY-ID',
	### 	'X-TINYPROXY',
	### 	'X_FORWARDED_FOR',
	### 	'FORWARDED_FOR',
	### 	'X_FORWARDED',
	### 	'FORWARDED',
	### 	'CLIENT-IP',
	### 	'CLIENT_IP',
	### 	'PROXY-AGENT',
	### 	'HTTP_X_CLUSTER_CLIENT_IP',
	### 	'FORWARDED_FOR_IP',
	### 	'HTTP_PROXY_CONNECTION');
	### 	
	### 	foreach($test_HTTP_proxy_headers as $header){
	### 		if (isset($_SERVER[$header]) && !empty($_SERVER[$header])) {
	### 			test("1-Please disable your proxy connection",$header);
	### 		}
	### 	}
	### 


	$proxy_ports = array(80,81,8080,443,1080,6588,3128);
	foreach($proxy_ports as $test_port) {
		if(@fsockopen($REMOTE_ADDR, $test_port, $errno, $errstr, 5)) {
			//test("2-Please disable your proxy connection",$test_port);
			return $test_port;
		}
	}
}





function get_intelitruth_whitelabel_account_details($intelitruth_whitelabel_account_hash="") {
	
	if($intelitruth_whitelabel_account_hash) {
		
		$tmp_sql = "SELECT * 
					FROM accounts 
					WHERE hash = '". $intelitruth_whitelabel_account_hash ."'
					AND template_company_hash = '" . $_SESSION['template']['company']['hash'] . "'
					LIMIT 1;
					";
	} else {
		
		$third_level_hostname = explode(".", $_SERVER['HTTP_HOST']);
		$tmp_sql = "SELECT * 
					FROM accounts 
					WHERE whitelabel_web = '". $third_level_hostname[0] ."'
					AND template_company_hash = '" . $_SESSION['template']['company']['hash'] . "'
					LIMIT 1;
					";
		
	}
	
	
	//test("third_level_hostname",$third_level_hostname);
	return object_to_array_v2(readTHECASHIER($tmp_sql));
}




function contextual_web_search($key_words,$pageNumber="",$pageSize="",$fromPublishedDate="",$toPublishedDate="",$safeSearch="",$autoCorrect="") {
	

/*
	
	10,000 / month  (i.e., 333 / day)
	then $0.0005 each
	https://rapidapi.com/contextualwebsearch/api/web-search

*/
	
	if(!$key_words) $key_words = "";
	if(!$pageNumber) $pageNumber = "1";
	if(!$pageSize) $pageSize = "50";
	if(!$fromPublishedDate) $fromPublishedDate = ""; // 2019-01-30
	if(!$toPublishedDate) $toPublishedDate = "";
	if(!$safeSearch) $safeSearch = "false";
	if(!$autoCorrect) $autoCorrect = "false";
	
	
	
	
	
	
	

	$curl = curl_init();
	
	
	
	$url = "https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI";
	$url .= "?";
	$url .= "autoCorrect=". $autoCorrect;
	$url .= "&";
	$url .= "pageNumber=". $pageNumber;
	$url .= "&";
	$url .= "pageSize=" . $pageSize;
	$url .= "&";
	$url .= "q=" . urlencode($key_words);
	$url .= "&";
	$url .= "safeSearch=" . $safeSearch;
	$url .= "&";
	$url .= "fromPublishedDate=". $fromPublishedDate;
	$url .= "&";
	$url .= "toPublishedDate=" . $toPublishedDate;
	$url .= "";
	
	//test("url",$url);
	
	curl_setopt_array($curl, array(
		CURLOPT_URL => $url,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_ENCODING => "",
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 30,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => "GET",
		CURLOPT_HTTPHEADER => array(
			"x-rapidapi-host: contextualwebsearch-websearch-v1.p.rapidapi.com",
			"x-rapidapi-key: 0c851c3b03mshcf0272c8da96690p123b58jsna096e7784092"
		),
	));
	
	$response = curl_exec($curl);
	$err = curl_error($curl);
	
	curl_close($curl);
	
	if ($err) {
		return "cURL Error #:" . $err;
	} else {
		return $response;
	}
}	






function system_emailer_v1($to,$subject,$message,$activate_unsubscribe="",$mail_exchange="") {



	if(!$activate_unsubscribe) $activate_unsubscribe = false;
	
	
	////////////////////////
	/// FROM NAME
	$insert_email_from_name = $_SESSION['template']['company']['name'];

	////////////////////////
	/// FROM EMAIL
	$insert_email_from_email = $_SESSION['template']['company']['emailaddress_support'];

	////////////////////////
	/// UPPER LEFT LOGO
	/// $GLOBAL_SET_ENTERPRISE_LOGO_MAILER
	
	
	

	$headers = "";
	$headers .= "From: " . $insert_email_from_name . " <" . $insert_email_from_email . ">\r\n";
	$headers .= "Reply-To: " . $insert_email_from_name . " <" . $insert_email_from_email . ">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	
	/////////////////////////////
	/// START: ADD UNSUBSCRIBE
	
	if($activate_unsubscribe != false) {
		
		$unsubscribe_domain = $_SESSION['template']['company']['domain'];
		if(!$unsubscribe_domain) $unsubscribe_domain = "payyap.network";
		
		$message .= "
		
		<hr><span style='font-size:14px;'><a href='https://UNSUBSCRIBE.". $unsubscribe_domain ."/?emailaddress=". $to ."' target='_UNSUBSCRIBE' >Click here to UNSUBSCRIBE<a/> from these ". $insert_email_from_name ." hints & reminders.</span>
		
		";
		$unsubscribe_domain = "";
	}

	/// END: ADD UNSUBSCRIBE
	/////////////////////////////
	
	
	
		
	$message = emailpage($message,$email_insert_style=NULL);
	
	
	$send_to_emailaddress = $to;
	$message_html = $message;
	$mail = new PHPMailer;
	$mail->isSMTP();                                      // Set mailer to use SMTP
	
	////////////////////////
	$smtp_server = 2;
	////////////////////////


	////////////////////////
	/// NSDB
	if($smtp_server == 1) { 
		$mail->Host = 'mx.nsdb.com';
		$mail->Username = 'shea.writer@corp.nsdb.com';		// SMTP username
		$mail->Password = 'P455w0rd!';						// SMTP password
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	////////////////////////
	/// GMAIL
	if($smtp_server == 2) {  	
		
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	////////////////////////
	/// SENDGRID
	if($smtp_server == 3) {

		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;                                    										// TCP port to connect to
		# 
		# 
		# //// INTELITRUTH
		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;   
		
		#####################################
		### INTELITRUTH
		#####################################
		//$mail = new PHPMailer;
		//$mail->isSMTP();
		$mail->CharSet = 'UTF-8';
		$mail->Host = 'smtp.gmail.com';
		$mail->Username = 'kycid.network@gmail.com';
		$mail->Password = 'Bangk0k!';
		
		$mail->SMTPSecure = 'tls';
		$mail->SMTPAuth = true;
		$mail->Port = 587;
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);
		
		                                 										// TCP port to connect to
	}	
	
	
	
	////////////////////////////
	/// TCP port to connect to
	
	$mail->setFrom($insert_email_from_email, $insert_email_from_name);
	
	$mail->addAddress($send_to_emailaddress, $send_to_name);     // Add a recipient
	
	//$mail->addAddress('ellen@example.com');               // Name is optional
	
	$mail->addReplyTo($insert_email_from_email,$insert_email_from_name);
	
	//$mail->addCC('cc@example.com');
	
	$mail->addBCC('payyap.cc@gmail.com');
	
	$mail->addAttachment($path_to_attachment_file_1,$attachment_file_name_1);         // Add attachments
	$mail->addAttachment($path_to_attachment_file_2, $attachment_file_name_2);    // Optional name
	$mail->addAttachment($path_to_attachment_file_3, $attachment_file_name_3);    // Optional name
	$mail->isHTML(true);                                  // Set email format to HTML
	
	$mail->Subject = $subject;
	$mail->Body    = $message_html;
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}

	
}





function AIE_emailer_v1($to,$subject,$message,$activate_unsubscribe="",$mail_exchange="") {



	if(!$activate_unsubscribe) $activate_unsubscribe = false;
	
	
	////////////////////////
	/// FROM NAME
	$insert_email_from_name = $_SESSION['template']['company']['name'];

	////////////////////////
	/// FROM EMAIL
	$insert_email_from_email = $_SESSION['template']['company']['emailaddress_support'];

	////////////////////////
	/// UPPER LEFT LOGO
	/// $GLOBAL_SET_ENTERPRISE_LOGO_MAILER
	
	
	

	$headers = "";
	$headers .= "From: " . $insert_email_from_name . " <" . $insert_email_from_email . ">\r\n";
	$headers .= "Reply-To: " . $insert_email_from_name . " <" . $insert_email_from_email . ">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	
	/////////////////////////////
	/// START: ADD UNSUBSCRIBE
	
	if($activate_unsubscribe != false) {
		
		$unsubscribe_domain = $_SESSION['template']['company']['domain'];
		if(!$unsubscribe_domain) $unsubscribe_domain = "payyap.network";
		
		$message .= "
		
		<hr><span style='font-size:14px;'><a href='https://UNSUBSCRIBE.". $unsubscribe_domain ."/?emailaddress=". $to ."' target='_UNSUBSCRIBE' >Click here to UNSUBSCRIBE<a/> from these ". $insert_email_from_name ." hints & reminders.</span>
		
		";
		$unsubscribe_domain = "";
	}

	/// END: ADD UNSUBSCRIBE
	/////////////////////////////
	
	
	
		
	$message = emailpage($message,$email_insert_style=NULL);
	
	
	$send_to_emailaddress = $to;
	$message_html = $message;
	$mail = new PHPMailer;
	$mail->isSMTP();                                      // Set mailer to use SMTP
	
	////////////////////////
	$smtp_server = 2;
	////////////////////////


	////////////////////////
	/// NSDB
	if($smtp_server == 1) { 
		$mail->Host = 'mx.nsdb.com';
		$mail->Username = 'shea.writer@corp.nsdb.com';		// SMTP username
		$mail->Password = 'P455w0rd!';						// SMTP password
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	////////////////////////
	/// GMAIL
	if($smtp_server == 2) {  	
		
		// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
		// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
		// $mail->Password = 'Bangk0k!';						// SMTP password
		
		$mail->Host = 'smtp.gmail.com'; 
		$mail->Username = 'mailbox@nsdb.com';
		$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
		
		$mail->SMTPAuth = true;								// Enable SMTP authentication
		$mail->SMTPSecure = 'tls';							// Enable TLS encryption, `ssl` also accepted
		$mail->Port = 587;									// TCP port to connect to   
	}
	
	////////////////////////
	/// SENDGRID
	if($smtp_server == 3) {

		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;                                    										// TCP port to connect to
		# 
		# 
		# //// INTELITRUTH
		# $mail->Host = 'smtp.sendgrid.net';  														// Specify main and backup SMTP servers
		# $mail->Username = 'apikey';                 												// SMTP username
		# $mail->Password = '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';	// SMTP password
		# $mail->SMTPSecure = 'tls';                            										// Enable TLS encryption, `ssl` also accepted
		# $mail->SMTPAuth = true;                               										// Enable SMTP authentication
		# $mail->Port = 587;     
		
		#####################################
		### INTELITRUTH
		#####################################
		//$mail = new PHPMailer;
		//$mail->isSMTP();
		$mail->CharSet = 'UTF-8';
		$mail->Host = 'smtp.gmail.com';
		$mail->Username = 'kycid.network@gmail.com';
		$mail->Password = 'Bangk0k!';
		
		$mail->SMTPSecure = 'tls';
		$mail->SMTPAuth = true;
		$mail->Port = 587;
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);
		
		                               										// TCP port to connect to
	}	
	
	
	
	////////////////////////////
	/// TCP port to connect to
	
	$mail->setFrom($insert_email_from_email, $insert_email_from_name);
	
	$mail->addAddress($send_to_emailaddress, $send_to_name);     // Add a recipient
	
	//$mail->addAddress('ellen@example.com');               // Name is optional
	
	$mail->addReplyTo($insert_email_from_email,$insert_email_from_name);
	
	//$mail->addCC('cc@example.com');
	
	$mail->addBCC('payyap.cc@gmail.com');
	
	$mail->addAttachment($path_to_attachment_file_1,$attachment_file_name_1);         // Add attachments
	$mail->addAttachment($path_to_attachment_file_2, $attachment_file_name_2);    // Optional name
	$mail->addAttachment($path_to_attachment_file_3, $attachment_file_name_3);    // Optional name
	$mail->isHTML(true);                                  // Set email format to HTML
	
	$mail->Subject = $subject;
	$mail->Body    = $message_html;
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
	    logger3('Message has been sent');
	}

	
}



function decode_youtube_url($encoded_youtube_url) {
	
	$tmp_youtube_url = $encoded_youtube_url;
	$tmp_youtube_url = str_ireplace("%u2606", "☆", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%u2605", "★", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%3A", ":", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%20", " ", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%27", "'", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%C9", "É", $tmp_youtube_url);
	
	$tmp_youtube_url = str_ireplace("%28", "(", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%29", ")", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%2F", "/", $tmp_youtube_url);	
	$tmp_youtube_url = str_ireplace("%2D", "-", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%2B", "+", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%26", "&", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%24", "$", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%2C", ",", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%23", "#", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%2E", ".", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%3B", ";", $tmp_youtube_url);
	
	$tmp_youtube_url = str_ireplace("%3C", "<", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%3D", "=", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%3E", ">", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%3F", "?", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%40", "@", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%5B", "[", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%5D", "]", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%5F", "_", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%7C", "|", $tmp_youtube_url);
	$tmp_youtube_url = str_ireplace("%21", "!", $tmp_youtube_url);


	return $tmp_youtube_url;
}

function get_hashtags_array($url_or_text) {
	
	$service_name = "aylien-text";
	
	$current_limit = 900; //1000; // day
	$today_start = date("Y-m-d 00:00:00",time());
	$today_end = date("Y-m-d 23:59:59",time());
	$tmp_sql = "SELECT SUM(search_count)
				FROM `news_search_api_logs`
				WHERE news_source = '". $service_name ."'
				AND datetime_created >= '". $today_start ."'
				AND datetime_created < '". $today_end ."'
				;";
	//test("tmp_sql",$tmp_sql);
	$current_count = getTHECASHIER($tmp_sql,"ibm_to_twitter");
	if(!$current_count) $current_count = 0;
	
	
	### DO IT:
	//test("current_limit",$current_limit);
	//test("current_count",$current_count);
	if($current_count < $current_limit) {
	
	
		$PARAMETERS = "?";
		if(strstr($url_or_text,"http")) {
			$PARAMETERS .= "url=".$url_or_text;
		} else {
			$PARAMETERS .= "text=". urlencode($url_or_text);
		}
		$curl = curl_init();
		
		curl_setopt_array($curl, array(
			CURLOPT_URL => "https://aylien-text.p.rapidapi.com/hashtags".$PARAMETERS,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => "",
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 30,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => "GET",
			CURLOPT_HTTPHEADER => array(
				"x-rapidapi-host: aylien-text.p.rapidapi.com",
				"x-rapidapi-key: f9168ddf49msh45a061f266ad5cep11bc18jsnca5797209e8d"
			),
		));
		
		$response = curl_exec($curl);
		$err = curl_error($curl);
		
		curl_close($curl);
		
		
		
		### ADD TO COUNTER:
		$_XXXXX_news_search_api_logs_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXXX_news_source = $service_name;
		$_XXXXX_search_count = "1";
		$_XXXXX_datetime_created = datetime_v2();
		$tmp_sql = "INSERT INTO `news_search_api_logs`
					(
						`news_search_api_logs_id`
						, `hash`
						, `news_source`
						, `search_count`
						, `datetime_created`
					) VALUES (
						'". $_XXXXX_news_search_api_logs_id . "'
						, '". $_XXXXX_hash . "'
						, '". $_XXXXX_news_source . "'
						, '". $_XXXXX_search_count . "'
						, '". $_XXXXX_datetime_created . "'
					);";
		//test("tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql,"ibm_to_twitter");
		
		
		if ($err) {
			//echo "cURL Error #:" . $err;
			return FALSE;
		} else {
			
			
			$response = object_to_array_v2(json_decode($response));
			return $response['hashtags'];
			//echo $response;
		}
	} else {
		return FALSE;
	}
}




function AIE_get_client_preference($business_account_hash,$parameter_name) {
	
	if(
		(!business_account_hash)
		|| (!parameter_name)
	) {
		return false;	
	}
	
	//test("business_account_hash",$business_account_hash);
	//test("parameter_name",$parameter_name);
	
	$tmp_sql = "SELECT preference_value
			FROM client_preferences
			WHERE business_account_hash = '". addslashes($business_account_hash) ."'
			AND preference_name = '". addslashes($parameter_name) ."'
			ORDER BY datetime_created DESC
			LIMIT 1
			;";
	//test("tmp_sql",$tmp_sql);
	$existing_record = getTHECASHIER($tmp_sql,"ibm_to_twitter");
	//test("existing_record",$existing_record);
	if($existing_record) {
		return $existing_record;
	} else {
		return false;
	}
	
}

function AIE_update_client_preference($business_account_hash,$parameter_name,$parameter_value) {
	$tmp_sql = "SELECT *
				FROM client_preferences
				WHERE business_account_hash = '". addslashes($business_account_hash) ."'
				AND preference_name = '". addslashes($parameter_name) ."'
				ORDER BY datetime_created DESC
				LIMIT 1
				;";
	logger3("tmp_sql",$tmp_sql);
	$existing_record = object_to_array_v2(readTHECASHIER($tmp_sql,"ibm_to_twitter"));
	logger3("existing_record",$existing_record);
	
	if($existing_record) {
		
		
		$tmp_sql = "UPDATE client_preferences
					SET preference_value = '". addslashes($parameter_value) ."'
					WHERE hash = '". addslashes($existing_record['hash']) ."'
					;";
		logger3("tmp_sql",$tmp_sql);
		$update_results = updateTHECASHIER($tmp_sql,"ibm_to_twitter");
		logger3("update_results",$update_results);
		
	
	} else {
		
		$_XXXXX_client_preferences_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXXX_subscriber_hash = "";
		$_XXXXX_business_account_hash = addslashes($business_account_hash);
		$_XXXXX_preference_name = addslashes($parameter_name);
		$_XXXXX_preference_value = addslashes($parameter_value);
		$_XXXXX_client_industry_name = "";
		$_XXXXX_datetime_created = datetime_v2();
		$_XXXXX_datetime_updated = $_XXXXX_datetime_created;
						
		$tmp_sql = "INSERT INTO `client_preferences`
					(
						`client_preferences_id`
						, `hash`
						, `subscriber_hash`
						, `business_account_hash`
						, `preference_name`
						, `preference_value`
						, `client_industry_name`
						, `datetime_created`
						, `datetime_updated`
					) VALUES (
						
						'". $_XXXXX_client_preferences_id ."'
						, '". $_XXXXX_hash ."'
						, '". $_XXXXX_subscriber_hash ."'
						, '". $_XXXXX_business_account_hash ."'
						, '". $_XXXXX_preference_name ."'
						, '". $_XXXXX_preference_value ."'
						, '". $_XXXXX_client_industry_name ."'
						, '". $_XXXXX_datetime_created ."'
						, '". $_XXXXX_datetime_updated ."'
						
					);";
		logger3("tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql,"ibm_to_twitter");
		logger3("insert_results",$insert_results);	
		
	}
}



function BLINGK_GET_AVAILABLE_COUPONS($blogger_account_hash,$customer_memberid) {
	
	//test("blogger_account_hash",$blogger_account_hash);
	//test("customer_memberid",$customer_memberid);
	
	if(!$_SESSION['BLINGK']['BLOGGER']['hash']) {
		
		$tmp_sql = "SELECT *
					FROM accounts
					WHERE hash = '". $blogger_account_hash ."'
					;";
		//test("tmp_sql",$tmp_sql);
		
		$_SESSION['BLINGK']['BLOGGER'] = object_to_array_v2(readTHECASHIER($tmp_sql));
		//test("_SESSION['BLINGK']['BLOGGER']",$_SESSION['BLINGK']['BLOGGER']);
		
	}
	
	
	### GET BLOGGER COUPON OFFER
	$COUPONS_AVAILABLE = $_SESSION['BLINGK']['BLOGGER']['blingk_free_coupons_amount'];
	//test("COUPONS_AVAILABLE",$COUPONS_AVAILABLE);
	
	$COUPONS_PER_TIME = $_SESSION['BLINGK']['BLOGGER']['blingk_free_coupons_time_value'] . " " . $_SESSION['BLINGK']['BLOGGER']['blingk_free_coupons_time_type'];
	//test("COUPONS_PER_TIME",$COUPONS_PER_TIME);
	
	### GET CUSTOMER COUPON HISTORY:
	$COUPON_TIMEFRAME = date("Y-m-d H:i:s",strtotime("-". $COUPONS_PER_TIME ));
	//test("COUPON_TIMEFRAME",$COUPON_TIMEFRAME);
	
	$COUPON_STATUS = 'REFUNDED';
	
	$tmp_sql = "SELECT COUNT(hash)
				FROM blingk_free_coupons
				WHERE blogger_account_hash = '". trim($blogger_account_hash) ."'
				AND customer_memberid = '". trim($customer_memberid) ."'
				AND datetime_created >= '". $COUPON_TIMEFRAME ."'
				AND status != '". $COUPON_STATUS ."'
				;";
	//test("tmp_sql",$tmp_sql);
	$COUPONS_USED = getTHECASHIER($tmp_sql);
	//test("COUPONS_USED",$COUPONS_USED);
	
	$FINAL_COUPONS_AVAILABLE = $COUPONS_AVAILABLE - $COUPONS_USED;
	//test("FINAL_COUPONS_AVAILABLE",$FINAL_COUPONS_AVAILABLE);
	
	return $FINAL_COUPONS_AVAILABLE;
}












function update_member($field_name,$field_value,$member_hash) {
	

	/// member
	$tmp_sql = "UPDATE members 
	SET $field_name = '". addslashes(trim($field_value)) ."' 
	WHERE hash = '". trim($member_hash) ."'
	;";
	logger3("tmp_sql",$tmp_sql);
	$update_results = updateTHECASHIER($tmp_sql);
	logger3("10. update_results",$update_results); $update_results = "";
	
}


function update_account($field_name,$field_value,$account_hash) {

	
	$tmp_sql = "UPDATE accounts 
	SET $field_name = '". addslashes(trim($field_value)) ."' 
	WHERE hash = '". trim($account_hash) ."'
	;";
	logger3("tmp_sql",$tmp_sql);
	$update_results = updateTHECASHIER($tmp_sql);
	logger3("16. update_results",$update_results); $update_results = "";
	
}



function get_kyc_certificate_id($account_hash) {
	
	$tmp_sql = "SELECT kyc_certificate_id
				FROM accounts
				WHERE hash = '". $account_hash ."'
				;";
	$kyc_certificate_id = getTHECASHIER($tmp_sql);
	
	while(empty($kyc_certificate_id)) {
			
			$new_kyc_certificate_id = random_string("4","123456789") ."-". random_string("4","123456789") ."-". random_string("4","123456789") ."-". random_string("4","123456789");
			
			$tmp_sql = "SELECT hash
						FROM accounts
						WHERE kyc_certificate_id = '". $new_kyc_certificate_id ."'
						;";
			$kyc_certificate_id_exists = getTHECASHIER($tmp_sql);
			if(empty($kyc_certificate_id_exists)) {
			
				$kyc_certificate_id = $new_kyc_certificate_id;
			
				$tmp_sql = "UPDATE accounts
							SET kyc_certificate_id = '". $kyc_certificate_id ."'
							WHERE hash = '". $account_hash ."'
							;";
				$update_results = updateTHECASHIER($tmp_sql);
			}
		}
	
	return $kyc_certificate_id;
}




function IEW_get_account_flags($account_hash) {
	
	
	
	
	#######################################################################
	#######################################################################
	### START: FLAGS
	
	
	
		#################################################### PERSONAL FLAGS: 
		
		
		##############
		$tmp_list_name = "OFAC_SDN_XML";
		$tmp_sql = "SELECT SUM(risk_score)
					FROM AML_flags
					WHERE account_hash = '". $account_hash ."'
					AND flag_status != 'OFF'
					AND list_name = '". $tmp_list_name ."'
					;";
		$risk_score[$tmp_list_name] = getTHECASHIER($tmp_sql);
		if(empty($risk_score[$tmp_list_name])) $risk_score[$tmp_list_name] = "0";
		$_SESSION['intelitruth']['admin']['profile_manager']['flags'][$account_hash][$tmp_list_name] += $risk_score[$tmp_list_name];
		$_SESSION['intelitruth']['admin']['profile_manager']['flags'][$account_hash]['AML'] += $risk_score[$tmp_list_name];
		
		
		##############
		$tmp_list_name = "OFAC_CONSOLIDATED_XML";
		$tmp_sql = "SELECT SUM(risk_score)
					FROM AML_flags
					WHERE account_hash = '". $account_hash ."'
					AND flag_status != 'OFF'
					AND list_name = '". $tmp_list_name ."'
					;";
		$risk_score[$tmp_list_name] = getTHECASHIER($tmp_sql);
		if(empty($risk_score[$tmp_list_name])) $risk_score[$tmp_list_name] = "0";
		$_SESSION['intelitruth']['admin']['profile_manager']['flags'][$account_hash][$tmp_list_name] += $risk_score[$tmp_list_name];
		$_SESSION['intelitruth']['admin']['profile_manager']['flags'][$account_hash]['AML'] += $risk_score[$tmp_list_name];
		
		
		##############
		$tmp_list_name = "PEPs";
		$tmp_sql = "SELECT SUM(risk_score)
					FROM AML_flags
					WHERE account_hash = '". $account_hash ."'
					AND flag_status != 'OFF'
					AND list_name = '". $tmp_list_name ."'
					;";
		$risk_score[$tmp_list_name] = getTHECASHIER($tmp_sql);
		if(empty($risk_score[$tmp_list_name])) $risk_score[$tmp_list_name] = "0";
		$_SESSION['intelitruth']['admin']['profile_manager']['flags'][$account_hash][$tmp_list_name] += $risk_score[$tmp_list_name];
		$_SESSION['intelitruth']['admin']['profile_manager']['flags'][$account_hash]['AML'] += $risk_score[$tmp_list_name];
		
		
		
		
		
		//    ##############
		//    $tmp_list_name = "FBI";
		//    $tmp_sql = "SELECT SUM(risk_score)
		//    			FROM AML_flags
		//    			WHERE account_hash = '". $account_details['hash'] ."'
		//    			AND flag_status != 'OFF'
		//    			AND list_name = '". $tmp_list_name ."'
		//    			;";
		//    $risk_score[$tmp_list_name] = getTHECASHIER($tmp_sql);
		//    if(empty($risk_score[$tmp_list_name])) $risk_score[$tmp_list_name] = "0";
		//    
		//    
		//    
		//    
		//    ##############
		//    $tmp_list_name = "DEA";
		//    $tmp_sql = "SELECT SUM(risk_score)
		//    			FROM AML_flags
		//    			WHERE account_hash = '". $account_details['hash'] ."'
		//    			AND flag_status != 'OFF'
		//    			AND list_name = '". $tmp_list_name ."'
		//    			;";
		//    $risk_score[$tmp_list_name] = getTHECASHIER($tmp_sql);
		//    if(empty($risk_score[$tmp_list_name])) $risk_score[$tmp_list_name] = "0";
		//    
		//    
		//    ##############
		//    $tmp_list_name = "ICE";
		//    $tmp_sql = "SELECT SUM(risk_score)
		//    			FROM AML_flags
		//    			WHERE account_hash = '". $account_details['hash'] ."'
		//    			AND flag_status != 'OFF'
		//    			AND list_name = '". $tmp_list_name ."'
		//    			;";
		//    $risk_score[$tmp_list_name] = getTHECASHIER($tmp_sql);
		//    if(empty($risk_score[$tmp_list_name])) $risk_score[$tmp_list_name] = "0";
		//    
		//    
		//    
		//    ##############
		//    $tmp_list_name = "INTERPOL";
		//    $tmp_sql = "SELECT SUM(risk_score)
		//    			FROM AML_flags
		//    			WHERE account_hash = '". $account_details['hash'] ."'
		//    			AND flag_status != 'OFF'
		//    			AND list_name = '". $tmp_list_name ."'
		//    			;";
		//    $risk_score[$tmp_list_name] = getTHECASHIER($tmp_sql);
		//    if(empty($risk_score[$tmp_list_name])) $risk_score[$tmp_list_name] = "0";
	
	
		############## KYC
		$tmp_list_name = "KYC";
		$tmp_sql = "SELECT SUM(risk_score)
					FROM KYC_flags
					WHERE account_hash = '". $account_hash ."'
					AND flag_status != 'OFF'
					;";
		$risk_score[$tmp_list_name] = getTHECASHIER($tmp_sql,"intelitruth");
		if(empty($risk_score[$tmp_list_name])) $risk_score[$tmp_list_name] = "0";
		$_SESSION['intelitruth']['admin']['profile_manager']['flags'][$account_hash][$tmp_list_name] = $risk_score[$tmp_list_name];


		############## AML
		$tmp_list_name = "AML";
		$tmp_sql = "SELECT SUM(risk_score)
					FROM AML_flags
					WHERE account_hash = '". $account_hash ."'
					AND flag_status != 'OFF'
					;";
		//logger3("tmp_sql",$tmp_sql);
		$risk_score[$tmp_list_name] = getTHECASHIER($tmp_sql,"intelitruth");
		//logger3("risk_score[$tmp_list_name]",$risk_score[$tmp_list_name]);
		if(empty($risk_score[$tmp_list_name])) $risk_score[$tmp_list_name] = "0";
		$_SESSION['intelitruth']['admin']['profile_manager']['flags'][$account_hash][$tmp_list_name] = $risk_score[$tmp_list_name];
		


		############## NEGATIVENEWS
		$tmp_list_name = "NEGATIVENEWS";
		$tmp_sql = "SELECT COUNT(hash)
		  			FROM NEGATIVENEWS_flags
		  			WHERE account_hash = '". $account_hash ."'
		  			AND flag_status != 'OFF'
		  			;";
		$risk_score[$tmp_list_name] = getTHECASHIER($tmp_sql,"intelitruth");
		if(empty($risk_score[$tmp_list_name])) $risk_score[$tmp_list_name] = "0";
		$_SESSION['intelitruth']['admin']['profile_manager']['flags'][$account_hash][$tmp_list_name] = $risk_score[$tmp_list_name];
		
		
		############## INTELISPIDER
		$tmp_list_name = "INTELISPIDER";
		$tmp_sql = "SELECT COUNT(hash)
		  			FROM INTELISPIDER_flags
		  			WHERE account_hash = '". $account_hash ."'
		  			AND flag_status != 'OFF'
		  			;";
		$risk_score[$tmp_list_name] = getTHECASHIER($tmp_sql,"intelitruth");
		if(empty($risk_score[$tmp_list_name])) $risk_score[$tmp_list_name] = "0";
		$_SESSION['intelitruth']['admin']['profile_manager']['flags'][$account_hash][$tmp_list_name] = $risk_score[$tmp_list_name];
		
		
		
				
		
		#################################################### BUSINES FLAGS: 
	
	
	### END: FLAGS
	#######################################################################
	#######################################################################
	
	
	return $_SESSION['intelitruth']['admin']['profile_manager']['flags'][$account_hash];
	
}



function time_to_scan($time_scan_schedule,$time_last_scan) {
			
	if($time_last_scan >= $time_scan_schedule) {
		return FALSE; //echo "DON'T SCAN";
	} else {
		return TRUE; // echo "SCAN";
	}
}




function get_supporting_document_titles($whitelabel_business_account_hash,$TIER="") {
	
	if(empty($TIER)) $TIER = "DEFAULT";
	
	$tmp_sql = "SELECT * 
				FROM onboarding_preferences 
				WHERE whitelabel_business_account_hash = '". $whitelabel_business_account_hash ."'
				AND form_name = '". addslashes($TIER) ."'
				;";
	$whitelabel_onboarding_preferences = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/// PERSONAL
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	
	$return = "";
	$return['individual'] = "";
	$return['business'] = "";
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/// selfie
	
	$paramater_value = "onboarding_identity_selfie";
	$return['individual']['selfie']['KEY'] = "SELFIE";
	$return['individual']['selfie']['title'] = "Selfie";
	$return['individual']['selfie']['status'] = $whitelabel_onboarding_preferences[$paramater_value];
	if(empty($return['individual']['selfie']['status'])) $return['individual']['selfie']['status'] = "optional";
	
	
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/// onboarding_identity_photo_id
	$paramater_value = "onboarding_identity_photo_id";
	$whitelabel_business_account_hash = $whitelabel_business_account_hash;
	$pulldown_name = $paramater_value;
	$pulldown_version = $TIER;
	unset($options_array);
	$raw_options_array = get_pulldown_options_v2($whitelabel_business_account_hash,$pulldown_name,$pulldown_version);
	$options_array = $raw_options_array['pulldown_data'];
	if(!$options_array['title']) {

		
		unset($options_array);
		$options_array = array();
		$options_array['title'] = "Proof of Personal Identity";
		$options_array['option_description'] = "";
		$options_array['option_alert'] = "";
		$options_array['option_status'] = "optional";
		$options_array['option_name'][] = "Passport (Front + Back)";
		$options_array['option_name'][] = "Driver's License (Front + Back)";
		$options_array['option_name'][] = "State-Issued Photo ID (Front + Back)";
		
		
		$_XXXXX_pulldown_options_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
		$_XXXXX_pulldown_name = $pulldown_name;
		$_XXXXX_version = $pulldown_version;
		$_XXXXX_title = addslashes($options_array['title']);
		$_XXXXX_pulldown_data = addslashes(json_encode($options_array));
		$_XXXXX_datetime_updatad = datetime_v2();
		$tmp_sql = "
		INSERT INTO `pulldown_options`
		(
			`pulldown_options_id`
			, `hash`
			, `whitelabel_business_account_hash`
			, `pulldown_name`
			, `version`
			, `title`
			, `pulldown_data`
			, `datetime_updatad`
		) VALUES (
			'". $_XXXXX_pulldown_options_id ."'
			,'". $_XXXXX_hash ."'
			,'". $_XXXXX_whitelabel_business_account_hash ."'
			,'". $_XXXXX_pulldown_name ."'
			,'". $_XXXXX_version ."'
			,'". $_XXXXX_title ."'
			,'". $_XXXXX_pulldown_data ."'
			,'". $_XXXXX_datetime_updatad ."'
		);
		";
		logger3(" $paramater_value tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
		logger3(" $paramater_value insert_results",$insert_results);
	}
	
	$return['individual']['photo_id'] = $options_array;
	$return['individual']['photo_id']['KEY'] = "PHOTO_ID";
	
	$return['individual']['photo_id']['status'] = $whitelabel_onboarding_preferences[$paramater_value];
	if(empty($return['individual']['photo_id']['status'])) $return['individual']['photo_id']['status'] = "optional";

	
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/// onboarding_identity_residence
	$paramater_value = "onboarding_identity_residence";
	$whitelabel_business_account_hash = $whitelabel_business_account_hash;
	$pulldown_name = $paramater_value;
	$pulldown_version = $TIER;
	unset($options_array);
	$raw_options_array = get_pulldown_options_v2($whitelabel_business_account_hash,$pulldown_name,$pulldown_version);
	$options_array = $raw_options_array['pulldown_data'];
	if(!$options_array['title']) {

		unset($options_array);
		$options_array = array();
		$options_array['title'] = "Proof of Personal Residence";
		$options_array['option_description'] = "";
		$options_array['option_alert'] = "";
		$options_array['option_status'] = "optional";
		$options_array['option_name'][] = "Electricity Bill";
		$options_array['option_name'][] = "Cable / Internet Bill";
		$options_array['option_name'][] = "Apartment / Home Rental Bill";
		
		
		$_XXXXX_pulldown_options_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
		$_XXXXX_pulldown_name = $pulldown_name;
		$_XXXXX_version = $pulldown_version;
		$_XXXXX_title = addslashes($options_array['title']);
		$_XXXXX_pulldown_data = addslashes(json_encode($options_array));
		$_XXXXX_datetime_updatad = datetime_v2();
		$tmp_sql = "
		INSERT INTO `pulldown_options`
		(
			`pulldown_options_id`
			, `hash`
			, `whitelabel_business_account_hash`
			, `pulldown_name`
			, `version`
			, `title`
			, `pulldown_data`
			, `datetime_updatad`
		) VALUES (
			'". $_XXXXX_pulldown_options_id ."'
			,'". $_XXXXX_hash ."'
			,'". $_XXXXX_whitelabel_business_account_hash ."'
			,'". $_XXXXX_pulldown_name ."'
			,'". $_XXXXX_version ."'
			,'". $_XXXXX_title ."'
			,'". $_XXXXX_pulldown_data ."'
			,'". $_XXXXX_datetime_updatad ."'
		);
		";
		logger3(" $paramater_value tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
		logger3(" $paramater_value insert_results",$insert_results);
	}
	
	$return['individual']['proof_of_residence'] = $options_array;
	$return['individual']['proof_of_residence']['KEY'] = "PROOF_OF_RESIDENCE";
	
	$return['individual']['proof_of_residence']['status'] = $whitelabel_onboarding_preferences[$paramater_value];
	if(empty($return['individual']['proof_of_residence']['status'])) $return['individual']['proof_of_residence']['status'] = "optional";
	
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/// more_personal_documents_xxx
	$loop = 1;
	while($loop <= 10) {
		$paramater_value = "more_personal_documents_". $loop;
		$whitelabel_business_account_hash = $whitelabel_business_account_hash;
		$pulldown_name = $paramater_value;
		$pulldown_version = $TIER;
		unset($options_array);
		$raw_options_array = get_pulldown_options_v2($whitelabel_business_account_hash,$pulldown_name,$pulldown_version);
		$options_array = $raw_options_array['pulldown_data'];
		if(!$options_array['title']) {
		
			$options_array['title'] = "Additional Personal Documentation (". $loop .")";
			$options_array['option_description'] = "";
			$options_array['option_alert'] = "";
			$options_array['option_status'] = "do_not_display";
			$options_array['option_name'][] = "Option 1";
			$options_array['option_name'][] = "Option 2";
			$options_array['option_name'][] = "Option 3";
			
			
			$_XXXXX_pulldown_options_id = "";
			$_XXXXX_hash = hash_me();
			$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
			$_XXXXX_pulldown_name = $pulldown_name;
			$_XXXXX_version = $pulldown_version;
			$_XXXXX_title = addslashes($options_array['title']);
			$_XXXXX_pulldown_data = addslashes(json_encode($options_array));
			$_XXXXX_datetime_updatad = datetime_v2();
			$tmp_sql = "
			INSERT INTO `pulldown_options`
			(
				`pulldown_options_id`
				, `hash`
				, `whitelabel_business_account_hash`
				, `pulldown_name`
				, `version`
				, `title`
				, `pulldown_data`
				, `datetime_updatad`
			) VALUES (
				'". $_XXXXX_pulldown_options_id ."'
				,'". $_XXXXX_hash ."'
				,'". $_XXXXX_whitelabel_business_account_hash ."'
				,'". $_XXXXX_pulldown_name ."'
				,'". $_XXXXX_version ."'
				,'". $_XXXXX_title ."'
				,'". $_XXXXX_pulldown_data ."'
				,'". $_XXXXX_datetime_updatad ."'
			);
			";
			logger3(" $paramater_value tmp_sql",$tmp_sql);
			$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
			logger3(" $paramater_value insert_results",$insert_results);
		}
		$return['individual'][$paramater_value] = $options_array;
		$return['individual'][$paramater_value]['KEY'] = "MORE_PERSONAL_DOCUMENTS_".$loop;
		
		$return['individual'][$paramater_value]['status'] = $whitelabel_onboarding_preferences[$paramater_value];
		if(empty($return['individual'][$paramater_value]['status'])) $return['individual'][$paramater_value]['status'] = "do_not_display";
	
	
		$loop = $loop + 1;
	
	}
	
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/// BUSINESS
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////

	
	
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/// onboarding_identity_business
	$paramater_value = "onboarding_identity_business";
	$whitelabel_business_account_hash = $whitelabel_business_account_hash;
	$pulldown_name = $paramater_value;
	$pulldown_version = $TIER;
	unset($options_array);
	$raw_options_array = get_pulldown_options_v2($whitelabel_business_account_hash,$pulldown_name,$pulldown_version);
	$options_array = $raw_options_array['pulldown_data'];
	if(!$options_array['title']) {

		$options_array['title'] = "Proof of Business Credentials";
		$options_array['option_description'] = "";
		$options_array['option_alert'] = "";
		$options_array['option_status'] = "optional";
		$options_array['option_name'][] = "Federal EIN (TAX ID) Registration Receipt";
		$options_array['option_name'][] = "State-Issued Sole Proprietor / DBA Certificate";
		$options_array['option_name'][] = "State-Issued Incorporation Certificate";
		
		
		$_XXXXX_pulldown_options_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
		$_XXXXX_pulldown_name = $pulldown_name;
		$_XXXXX_version = $pulldown_version;
		$_XXXXX_title = addslashes($options_array['title']);
		$_XXXXX_pulldown_data = addslashes(json_encode($options_array));
		$_XXXXX_datetime_updatad = datetime_v2();
		$tmp_sql = "
		INSERT INTO `pulldown_options`
		(
			`pulldown_options_id`
			, `hash`
			, `whitelabel_business_account_hash`
			, `pulldown_name`
			, `version`
			, `title`
			, `pulldown_data`
			, `datetime_updatad`
		) VALUES (
			'". $_XXXXX_pulldown_options_id ."'
			,'". $_XXXXX_hash ."'
			,'". $_XXXXX_whitelabel_business_account_hash ."'
			,'". $_XXXXX_pulldown_name ."'
			,'". $_XXXXX_version ."'
			,'". $_XXXXX_title ."'
			,'". $_XXXXX_pulldown_data ."'
			,'". $_XXXXX_datetime_updatad ."'
		);
		";
		logger3(" $paramater_value tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
		logger3(" $paramater_value insert_results",$insert_results);
	}
	
	$return['business']['proof_of_business'] = $options_array;	
	$return['business']['proof_of_business']['KEY'] = "PROOF_OF_BUSINESS";
	
	$return['business']['proof_of_business']['status'] = $whitelabel_onboarding_preferences[$paramater_value];
	if(empty($return['business']['proof_of_business']['status'])) $return['business']['proof_of_business']['status'] = "optional";
					
	
	
	
	
	
	
	
	
	
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/// onboarding_identity_banking
	$paramater_value = "onboarding_identity_banking";
	$whitelabel_business_account_hash = $whitelabel_business_account_hash;
	$pulldown_name = $paramater_value;
	$pulldown_version = $TIER;
	unset($options_array);
	$raw_options_array = get_pulldown_options_v2($whitelabel_business_account_hash,$pulldown_name,$pulldown_version);
	$options_array = $raw_options_array['pulldown_data'];
	if(!$options_array['title']) {

		$options_array['title'] = "Proof of Banking Credentials";
		$options_array['option_description'] = "";
		$options_array['option_alert'] = "";
		$options_array['option_status'] = "optional";
		$options_array['option_name'][] = "Business Bank Account Invoice / Statement";
		$options_array['option_name'][] = "Business Bank Account Voided Check";
		//$options_array['option_name'][] = "State-Issued Incorporation Certificate";
		
		$_XXXXX_pulldown_options_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
		$_XXXXX_pulldown_name = $pulldown_name;
		$_XXXXX_version = $pulldown_version;
		$_XXXXX_title = addslashes($options_array['title']);
		$_XXXXX_pulldown_data = addslashes(json_encode($options_array));
		$_XXXXX_datetime_updatad = datetime_v2();
		$tmp_sql = "
		INSERT INTO `pulldown_options`
		(
			`pulldown_options_id`
			, `hash`
			, `whitelabel_business_account_hash`
			, `pulldown_name`
			, `version`
			, `title`
			, `pulldown_data`
			, `datetime_updatad`
		) VALUES (
			'". $_XXXXX_pulldown_options_id ."'
			,'". $_XXXXX_hash ."'
			,'". $_XXXXX_whitelabel_business_account_hash ."'
			,'". $_XXXXX_pulldown_name ."'
			,'". $_XXXXX_version ."'
			,'". $_XXXXX_title ."'
			,'". $_XXXXX_pulldown_data ."'
			,'". $_XXXXX_datetime_updatad ."'
		);
		";
		logger3(" $paramater_value tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
		logger3(" $paramater_value insert_results",$insert_results);
	}
	
	$return['business']['proof_of_banking'] = $options_array;
	$return['business']['proof_of_banking']['KEY'] = "BUSINESS_BANKING";
	
	$return['business']['proof_of_banking']['status'] = $whitelabel_onboarding_preferences[$paramater_value];
	if(empty($return['business']['proof_of_banking']['status'])) $return['business']['proof_of_banking']['status'] = "optional";
		
	
	
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/// onboarding_identity_tax_returns
	$paramater_value = "onboarding_identity_tax_returns";
	$whitelabel_business_account_hash = $whitelabel_business_account_hash;
	$pulldown_name = $paramater_value;
	$pulldown_version = $TIER;
	unset($options_array);
	$raw_options_array = get_pulldown_options_v2($whitelabel_business_account_hash,$pulldown_name,$pulldown_version);
	$options_array = $raw_options_array['pulldown_data'];
	if(!$options_array['title']) {

		$options_array['title'] = "Proof of Tax Returns";
		$options_array['option_description'] = "";
		$options_array['option_alert'] = "";
		$options_array['option_status'] = "optional";
		$options_array['option_name'][] = "New Business / No Previous Tax Returns (0 YEARS)";
		$options_array['option_name'][] = "1 YEAR of Tax Returns";
		$options_array['option_name'][] = "2 YEAR of Tax Returns";
		$options_array['option_name'][] = "3 YEAR of Tax Returns";
		
		
		$_XXXXX_pulldown_options_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
		$_XXXXX_pulldown_name = $pulldown_name;
		$_XXXXX_version = $pulldown_version;
		$_XXXXX_title = addslashes($options_array['title']);
		$_XXXXX_pulldown_data = addslashes(json_encode($options_array));
		$_XXXXX_datetime_updatad = datetime_v2();
		$tmp_sql = "
		INSERT INTO `pulldown_options`
		(
			`pulldown_options_id`
			, `hash`
			, `whitelabel_business_account_hash`
			, `pulldown_name`
			, `version`
			, `title`
			, `pulldown_data`
			, `datetime_updatad`
		) VALUES (
			'". $_XXXXX_pulldown_options_id ."'
			,'". $_XXXXX_hash ."'
			,'". $_XXXXX_whitelabel_business_account_hash ."'
			,'". $_XXXXX_pulldown_name ."'
			,'". $_XXXXX_version ."'
			,'". $_XXXXX_title ."'
			,'". $_XXXXX_pulldown_data ."'
			,'". $_XXXXX_datetime_updatad ."'
		);
		";
		logger3(" $paramater_value tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
		logger3(" $paramater_value insert_results",$insert_results);
	}
	
	$return['business']['tax_returns'] = $options_array;
	$return['business']['tax_returns']['KEY'] = "BUSINESS_TAX_RETURNS";
	
	
	$return['business']['tax_returns']['status'] = $whitelabel_onboarding_preferences[$paramater_value];
	if(empty($return['business']['tax_returns']['status'])) $return['business']['tax_returns']['status'] = "optional";
				
	
	
	
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/// onboarding_identity_processing
	$paramater_value = "onboarding_identity_processing";
	$whitelabel_business_account_hash = $whitelabel_business_account_hash;
	$pulldown_name = $paramater_value;
	$pulldown_version = $TIER;
	unset($options_array);
	$raw_options_array = get_pulldown_options_v2($whitelabel_business_account_hash,$pulldown_name,$pulldown_version);
	$options_array = $raw_options_array['pulldown_data'];
	if(!$options_array['title']) {

		$options_array['title'] = "Proof of Previous Processing Statements";
		$options_array['option_description'] = "";
		$options_array['option_alert'] = "";
		$options_array['option_status'] = "optional";
		$options_array['option_name'][] = "No Previous Processing (0 Months)";
		$options_array['option_name'][] = "1 MONTH of Previous Process Statements";
		$options_array['option_name'][] = "2 MONTH of Previous Process Statements";
		$options_array['option_name'][] = "3 MONTH of Previous Process Statements";
		$options_array['option_name'][] = "4 MONTH of Previous Process Statements";
		$options_array['option_name'][] = "5 MONTH of Previous Process Statements";
		$options_array['option_name'][] = "6 MONTH of Previous Process Statements";
		$options_array['option_name'][] = "12 MONTH of Previous Process Statements";
		
		
		$_XXXXX_pulldown_options_id = "";
		$_XXXXX_hash = hash_me();
		$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
		$_XXXXX_pulldown_name = $pulldown_name;
		$_XXXXX_version = $pulldown_version;
		$_XXXXX_title = addslashes($options_array['title']);
		$_XXXXX_pulldown_data = addslashes(json_encode($options_array));
		$_XXXXX_datetime_updatad = datetime_v2();
		$tmp_sql = "
		INSERT INTO `pulldown_options`
		(
			`pulldown_options_id`
			, `hash`
			, `whitelabel_business_account_hash`
			, `pulldown_name`
			, `version`
			, `title`
			, `pulldown_data`
			, `datetime_updatad`
		) VALUES (
			'". $_XXXXX_pulldown_options_id ."'
			,'". $_XXXXX_hash ."'
			,'". $_XXXXX_whitelabel_business_account_hash ."'
			,'". $_XXXXX_pulldown_name ."'
			,'". $_XXXXX_version ."'
			,'". $_XXXXX_title ."'
			,'". $_XXXXX_pulldown_data ."'
			,'". $_XXXXX_datetime_updatad ."'
		);
		";
		logger3(" $paramater_value tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
		logger3(" $paramater_value insert_results",$insert_results);
	}
	
	$return['business']['processing_history'] = $options_array;
	$return['business']['processing_history']['KEY'] = "PROOF_OF_PROCESSING";
	
	$return['business']['processing_history']['status'] = $whitelabel_onboarding_preferences[$paramater_value];
	if(empty($return['business']['processing_history']['status'])) $return['business']['processing_history']['status'] = "optional";	
	
	
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/// more_business_documents_xxxx
	$loop = 1;
	while($loop <= 10) {
		$paramater_value = "more_business_documents_". $loop;
		$whitelabel_business_account_hash = $whitelabel_business_account_hash;
		$pulldown_name = $paramater_value;
		$pulldown_version = $TIER;
		unset($options_array);
		$raw_options_array = get_pulldown_options_v2($whitelabel_business_account_hash,$pulldown_name,$pulldown_version);
		$options_array = $raw_options_array['pulldown_data'];
		if(!$options_array['title']) {
		
			$options_array['title'] = "Additional Business Documentation (". $loop .")";
			$options_array['option_description'] = "";
			$options_array['option_alert'] = "";
			$options_array['option_status'] = "do_not_display";
			$options_array['option_name'][] = "Option 1";
			$options_array['option_name'][] = "Option 2";
			$options_array['option_name'][] = "Option 3";
			
			
			$_XXXXX_pulldown_options_id = "";
			$_XXXXX_hash = hash_me();
			$_XXXXX_whitelabel_business_account_hash = $whitelabel_business_account_hash;
			$_XXXXX_pulldown_name = $pulldown_name;
			$_XXXXX_version = $pulldown_version;
			$_XXXXX_title = addslashes($options_array['title']);
			$_XXXXX_pulldown_data = addslashes(json_encode($options_array));
			$_XXXXX_datetime_updatad = datetime_v2();
			$tmp_sql = "
			INSERT INTO `pulldown_options`
			(
				`pulldown_options_id`
				, `hash`
				, `whitelabel_business_account_hash`
				, `pulldown_name`
				, `version`
				, `title`
				, `pulldown_data`
				, `datetime_updatad`
			) VALUES (
				'". $_XXXXX_pulldown_options_id ."'
				,'". $_XXXXX_hash ."'
				,'". $_XXXXX_whitelabel_business_account_hash ."'
				,'". $_XXXXX_pulldown_name ."'
				,'". $_XXXXX_version ."'
				,'". $_XXXXX_title ."'
				,'". $_XXXXX_pulldown_data ."'
				,'". $_XXXXX_datetime_updatad ."'
			);
			";
			logger3(" $paramater_value tmp_sql",$tmp_sql);
			$insert_results = insertTHECASHIER($tmp_sql,"intelitruth");
			logger3(" $paramater_value insert_results",$insert_results);
		}
		
		$return['business'][$paramater_value] = $options_array;
		$return['business'][$paramater_value]['KEY'] = "MORE_BUSINESS_DOCUMENTS_".$loop;
		
		$return['business'][$paramater_value]['status'] = $whitelabel_onboarding_preferences[$paramater_value];
		if(empty($return['business'][$paramater_value]['status'])) $return['business'][$paramater_value]['status'] = "do_not_display";		
	
		$loop = $loop + 1;
	}	
	
	
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	
	
	
	
	return $return;
	
	
	
	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////		

}



function IEW_get_whitelabel_business_account_preferences($whitelabel_business_account_hash) {
	
	$tmp_sql = "SELECT distinct(preference_name)
				FROM whitelabel_preferences
				WHERE whitelabel_business_account_hash = '". addslashes(trim($whitelabel_business_account_hash)) ."'
				;";
	$distinct_preference_name_array = arrayTHECASHIER($tmp_sql,"intelitruth");
	
	$whitelabel_business_account_preferences_array = "";
	
	foreach($distinct_preference_name_array AS $key => $preference_name) {
		
		$tmp_sql = "SELECT *
					FROM whitelabel_preferences
					WHERE whitelabel_business_account_hash = '". addslashes(trim($whitelabel_business_account_hash)) ."'
					AND preference_name = '". addslashes(trim($preference_name)) ."'
					ORDER BY datetime_created DESC
					LIMIT 1
					;";
		$results = object_to_array_v2(readTHECASHIER($tmp_sql,"intelitruth"));
		$whitelabel_business_account_preferences_array[$results['preference_name']] = $results['preference_value'];

	}

	return object_to_array_v2($whitelabel_business_account_preferences_array);

}





function IEW_add_scan_target($whitelabel_hash,$target_table,$target_account_type,$target_account_hash,$target_member_hash,$target_type,$target_value) {

	$_XXXXX_common_datetime = datetime_v2();
	
	$_XXXXX_AML_targets_id = "";
	$_XXXXX_hash = hash_me();
	$_XXXXX_template_company_hash = $_SESSION['template']['company']['hash'];
	$_XXXXX_whitelabel_business_account_hash = trim($whitelabel_hash);
	$_XXXXX_account_type = trim($target_account_type);
	$_XXXXX_account_hash = trim($target_account_hash);
	$_XXXXX_creator_member_hash = trim($target_member_hash);
	$_XXXXX_target_type = trim($target_type);
	$_XXXXX_target_value = trim($target_value);
	$_XXXXX_target_schedule = "";
	$_XXXXX_datetime_last_scan = "0000-00-00 00:00:00";
	$_XXXXX_datetime_created = $_XXXXX_common_datetime;
	$_XXXXX_datetime_updated = $_XXXXX_common_datetime;
	
	
	$tmp_sql = "
	INSERT INTO `". $target_table ."`
		(
			`AML_targets_id`
			, `hash`
			, `template_company_hash`
			, `whitelabel_business_account_hash`
			, `account_type`
			, `account_hash`
			, `creator_member_hash`
			, `target_type`
			, `target_value`
			, `target_schedule`
			, `datetime_last_scan`
			, `datetime_created`
			, `datetime_updated`
		) VALUES (
			'". $_XXXXX_AML_targets_id . "'
			, '". addslashes($_XXXXX_hash) . "'
			, '". addslashes($_XXXXX_template_company_hash) . "'
			, '". addslashes($_XXXXX_whitelabel_business_account_hash) . "'
			, '". addslashes($_XXXXX_account_type) . "'
			, '". addslashes($_XXXXX_account_hash) . "'
			, '". addslashes($_XXXXX_creator_member_hash) . "'
			, '". addslashes($_XXXXX_target_type) . "'
			, '". addslashes($_XXXXX_target_value) . "'
			, '". $_XXXXX_target_schedule . "'
			, '". $_XXXXX_datetime_last_scan . "'
			, '". $_XXXXX_datetime_created . "'
			, '". $_XXXXX_datetime_updated . "'
	
		);";
	
	
	if(!empty($_XXXXX_target_value)) {
		return insertTHECASHIER($tmp_sql,"intelitruth");
	}
	
}




function clean_HGO_ID($string) {
	
	$string = trim($string);
	$string = numbers_only($string,$display_style=2);
	$string_array = str_split($string);
	
	return $string_array[0] . $string_array[1] . $string_array[2] . "-" . $string_array[3] . $string_array[4] . $string_array[5] . "-" . $string_array[6] . $string_array[7] . $string_array[8]; 
}




function load_bootstrap($version="") {
	
	if(empty($version)) $version = 4;
	
	if($version == 3) {
		echo '<!-- jQuery library -->';
		echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>';


		echo '<!-- Latest compiled JavaScript -->';
		echo '<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>';
	}
	
	if($version == 4) {
		
		echo '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">';
		echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>';
		echo '<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>';
		echo '<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>';
	}

}



function get_filename_details($path_to_filename) {
	
	$path_parts = pathinfo($path_to_filename);
	return object_to_array_v2($path_parts);
}





function is_EURO_ZONE($iso3) {
		
	$iso3 = strtoupper(trim($iso3));
	
	$eu_iso3 = array('AUT', 'BEL', 'BGR', 'HRV', 'CYP', 'CZE', 'DNK', 'EST', 'FIN', 'FRA', 'DEU', 'GRC', 'HUN', 'IRL', 'ITA', 'LVA', 'LTU', 'LUX', 'MLT', 'NLD', 'POL', 'PRT', 'ROU', 'SVK', 'SVN', 'ESP', 'SWE', 'GBR');
	
	return in_array($iso3, $eu_iso3);

}





function BLINGK_currency() {
	
	return BLI_get_currency_code_iso3();
	
}


function BLI_get_currency_code_iso3() {
	
	$_XXXXX_currency_iso3 = $_SESSION['template']['company']['currency1'];
	if($_SESSION['member']['preferred_currency_iso3']) $_XXXXX_currency_iso3 = $_SESSION['member']['preferred_currency_iso3'];
	if($_SESSION['BLINGK']['customer']['member']['preferred_currency_iso3']) $_XXXXX_currency_iso3 = $_SESSION['BLINGK']['customer']['member']['preferred_currency_iso3'];
	if($_SESSION['BLINGK']['customer']['account']['personal']['currency_0_iso3']) $_XXXXX_currency_iso3 = $_SESSION['BLINGK']['customer']['account']['personal']['currency_0_iso3'];
	
	return "EUR";
	//return $_XXXXX_currency_iso3;
	
}



function BLI_get_currency_format($value) {
	
	
	return number_format($value, 2, '.', '');
	
}




function INTELI_get_registration_login_security_process($whitelabel_account_hash) {



	$tmp_sql = "SELECT onboarding_account_registration_process 
				FROM onboarding_preferences
				WHERE whitelabel_business_account_hash = '". $whitelabel_account_hash ."'
				and form_name = 'DEFAULT'
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	$default_onboarding_preferences_array = object_to_array_v2(readarrayTHECASHIER($tmp_sql,"intelitruth"));



}





### LANGUAGE TRANSLATION:



function get_full_langtrans_session($new_user_selected_iso2="") {
	
	
	
	/// set system source default:
	global $master_config_default_platform_language_iso2;
	$source_language_iso2 = $master_config_default_platform_language_iso2; // "en";


	/// set new user selected language
	if(!empty(trim($new_user_selected_iso2))) {
		
		$_SESSION['user_selected_language_iso2'] = $new_user_selected_iso2;
		
	}
	
	/// set default user selected session
	if(!$_SESSION['user_selected_language_iso2']) $_SESSION['user_selected_language_iso2'] = "en";
	
	
	/// set local user selected:
	$user_selected_iso2 = $_SESSION['user_selected_language_iso2'];
	
	//logger3("user_selected_iso2",$user_selected_iso2);
	
	
	
	$_SESSION['language'] = array();
	

	$_SESSION['language']['user_selected_iso2'] = $user_selected_iso2;
	
	logger3("_SESSION['language']['user_selected_iso2']",$_SESSION['language']['user_selected_iso2']);
	
	// if(!$_SESSION['language']['user_selected_iso2']) {
	// 	$_SESSION['language']['user_selected_iso2'] = $user_selected_iso2;
	// 	$user_selected_iso2 = $_SESSION['language']['user_selected_iso2'];
	// }
	
	
	//logger3("user_selected_iso2",$user_selected_iso2);
	
	
	$tmp_sql = "SELECT *
				FROM service_text_language_translations
				WHERE language_iso2 = '". $source_language_iso2 ."'
				OR language_iso2 = '". $user_selected_iso2 ."'
				;";
	logger3("tmp_sql",$tmp_sql);
	$full_langtrans_session_raw = object_to_array_v10(readarrayTHECASHIER($tmp_sql,""));
	//logger3("full_langtrans_session_raw",$full_langtrans_session_raw);
	
	
	$_SESSION['language_raw_session'] = array();
	$_SESSION['language_raw_session'] = object_to_array_v10($full_langtrans_session_raw);

	
	return $full_langtrans_session_raw;
	
}



function convert_full_langtrans_session_to_pretty_language_session($full_langrans_session_array) {
	
	/// set system source default:
	global $master_config_default_platform_language_iso2;
	$source_language_iso2 = $master_config_default_platform_language_iso2; // "en";
	
	
	# if(!$user_selected_iso2) $user_selected_iso2 = "en";
	# //logger3("user_selected_iso2",$user_selected_iso2);
	
	
	
	
	
	/// set user selected from session
	$user_selected_iso2 = trim($_SESSION['user_selected_language_iso2']);
	
	/// set default user if non exist
	if(!$user_selected_iso2) $user_selected_iso2 = "en";
	
	//logger3("user_selected_iso2",$user_selected_iso2);
	
	
	$_SESSION['language'][$source_language_iso2] = array();
	$_SESSION['language'][$user_selected_iso2] = array();
	
	
	//logger3("444 full_langrans_session_array",$full_langrans_session_array);
	
	
	
	foreach($full_langrans_session_array AS $raw_key => $language_file_details) {
		
		
		
		$language_file_details = object_to_array_v10($language_file_details);
		
		//logger3("raw_key",$raw_key);
		//logger3("language_file_details",$language_file_details);
		
		
		$language_file_details_iso2 = $language_file_details['language_iso2'];
		
		//logger3("language_file_details_iso2",$language_file_details_iso2);
		
		//$ORIG_PATH_TRANSLATED = $language_file_details['ORIG_PATH_TRANSLATED'];
		
		//logger3("ORIG_PATH_TRANSLATED",$ORIG_PATH_TRANSLATED);
		
		$file_time_id = $language_file_details['time_id'];
		
		
		//logger3("000_SESSION['language']",$_SESSION['language']);
		
		
		//$_SESSION['language'][$language_file_details_iso2][$ORIG_PATH_TRANSLATED][$file_time_id] = $language_file_details['text'];
		
		$_SESSION['language'][$language_file_details_iso2][$file_time_id] = $language_file_details['text'];
					
		
			
	}
	
	//logger3("888 _SESSION['language']",$_SESSION['language']);

	return $_SESSION['language'];
}



/*
function translang($text,$time_id="",$source_language_iso2="") {
	
	
	/////////////////////////////////////////////////////////////////////
	/// START: don't process  if....
	
	if(stristr($text,"blingk")) return $text;
	
	if(!$_SESSION['template']['company']['name'])  return $text;
	
	if(!trim($text))  return $text;
	
	/// END: don't process  if....
	/////////////////////////////////////////////////////////////////////
	
	
	
	
	//$_SESSION['language'] = "";
	
	if(!$_SESSION['language']) {
		$full_langrans_session_array = get_full_langtrans_session($user_selected_iso2="");
		$_SESSION['language'] = convert_full_langtrans_session_to_pretty_language_session($full_langrans_session_array);
	}
	
	//logger3("_SESSION['language']",$_SESSION['language']);
	
	
	
	if(!$time_id) return false;
	
	
	if(!$source_language_iso2) $source_language_iso2 = "en";
	//logger3("source_language_iso2",$source_language_iso2);
	
	# if(!$user_selected_iso2) $user_selected_iso2 = "en";
	# //logger3("user_selected_iso2",$user_selected_iso2);
	
	
	
	
	
	/// set user selected from session
	$user_selected_iso2 = trim($_SESSION['user_selected_language_iso2']);
	
	/// set default user if non exist
	if(!$user_selected_iso2) $user_selected_iso2 = "en";
	
	//logger3("user_selected_iso2",$user_selected_iso2);
	
	
	$_XXXXX_ORIG_PATH_TRANSLATED = $_SERVER['ORIG_PATH_TRANSLATED'];
	
	//logger3("_XXXXX_ORIG_PATH_TRANSLATED",$_XXXXX_ORIG_PATH_TRANSLATED);


	

	
	##############
	### example:
	### $_SESSION['language']['en']['/home/blingk/public_html/phpinfo.php']['1620383607']
	##############
	
	
	
	/// last note:
	/// switching from line_1 to simple text_id
	
	
	### check if the incoming text matches the existing (known) session data:
	
	logger3("text",$text);
	
	logger3("_SESSION['language']['$source_language_iso2']['$time_id']",$_SESSION['language'][$source_language_iso2][$time_id]);
	
	if($_SESSION['language'][$source_language_iso2][$time_id] == $text) {
		
		// if matches, echo the known - all good - nothing to do.
		//logger3("text MATCHES",1);
		
		# return $_SESSION['language'][$user_selected_iso2][$_XXXXX_ORIG_PATH_TRANSLATED][$time_id];
		# return true;
	
	
	### if not, update the data
	} else {
		
		
		//logger3("text NOT MATCHES",0);
		//logger3("text",$text);
		//logger3("_SESSION['language']['$source_language_iso2']['$time_id']",$_SESSION['language'][$source_language_iso2][$time_id]);
		
		
		# $_SESSION['language'][$source_language_iso2][$_XXXXX_ORIG_PATH_TRANSLATED]['line_'.$language_text_line_number] = $text;
		
		/// update language + filename of existing record:
		//logger3("_SESSION['language'][$source_language_iso2][$_XXXXX_ORIG_PATH_TRANSLATED]",$_SESSION['language'][$source_language_iso2][$_XXXXX_ORIG_PATH_TRANSLATED]);
		
		//logger3("--> _SESSION['language']['$source_language_iso2']['$time_id']", $_SESSION['language'][$source_language_iso2][$time_id]);
		
		//logger3("--> text", $text);
		
		
		//////////////////////////////////////////////////////
		//////////////////////////////////////////////////////
		/// exists, but does not mot match
		
		if(
			($_SESSION['language'][$source_language_iso2][$time_id])
			&& ($_SESSION['language'][$source_language_iso2][$time_id] != $text)
		) {
			
			
			$translang_whatsdifferent = array();
			$translang_whatsdifferent[$time_id]['existing'] = $_SESSION['language'][$source_language_iso2][$time_id];
			$translang_whatsdifferent[$time_id]['new'] = $text;
			
			logger3($log_name="translang_whatsdifferent",$log_value=$translang_whatsdifferent,$action_code="",$log_filename="/BANGK!/logs/translang_whatsdifferent.logger");
			
			## OLD:
			## /// UPDATE SOURCE LANGUAGE ONLY
			## $tmp_sql = 'UPDATE service_text_language_translations
			## 	SET `text` = "'. addslashes($text) .'"
			## 	, datetime_updated = "'. datetime_v2() .'"
			## 	WHERE language_iso2 = "'. addslashes($source_language_iso2) .'"
			## 	AND time_id = "'. $time_id .'"				
			## 	';
			## //logger3("tmp_sql",$tmp_sql);
			## $update_results = updateTHECASHIER($tmp_sql,"");
			## //logger3("update_results",$update_results);
			
			
			### NEW:
			
			/// DESTROY ALL RELATED TIME IDs
			$tmp_sql = "DELETE FROM service_text_language_translations
						WHERE time_id = '". addslashes($time_id) ."'
						;";
			//logger3("tmp_sql",$tmp_sql);
			$update_results = updateTHECASHIER($tmp_sql,"");
			//logger3("update_results",$update_results);
			
			
			/// SET NEW
			
			$tmp_sql = 'INSERT INTO `service_text_language_translations`
							(
								`service_text_language_translations_id`
								, `ORIG_PATH_TRANSLATED`
								, `language_iso2`
								, `text`
								, `time_id`
								, `datetime_updated`
							) VALUES (
								"'. $blank .'"
								, "'. addslashes($_XXXXX_ORIG_PATH_TRANSLATED) .'"
								, "'. addslashes($source_language_iso2) .'"
								, "'. addslashes($text) .'"
								, "'. addslashes($time_id) .'"	
								, "'. datetime_v2() .'"
							);
						';
			//logger3("tmp_sql",$tmp_sql);
			$insert_results = insertTHECASHIER($tmp_sql,"");
			//logger3("insert_results",$insert_results);
			
			
			/// get new session
			# get_full_langtrans_session($_SESSION['user_selected_language_iso2']);
		
		
			
		//////////////////////////////////////////
		//////////////////////////////////////////
		/// or create new record if none exists:
		} else {
			
			$tmp_sql = 'INSERT INTO `service_text_language_translations`
						  (
							  `service_text_language_translations_id`
							  , `ORIG_PATH_TRANSLATED`
							  , `language_iso2`
							  , `text`
							  , `time_id`
							  , `datetime_updated`
						  ) VALUES (
							  "'. $blank .'"
							  , "'. addslashes($_XXXXX_ORIG_PATH_TRANSLATED) .'"
							  , "'. addslashes($source_language_iso2) .'"
							  , "'. addslashes($text) .'"
							  , "'. addslashes($time_id) .'"	
							  , "'. datetime_v2() .'"
						  );
					  ';
			//logger3("tmp_sql",$tmp_sql);
			$insert_results = insertTHECASHIER($tmp_sql,"");
			//logger3("insert_results",$insert_results);
			
			/// get new session
			# get_full_langtrans_session($_SESSION['user_selected_language_iso2']);
				
		}
		
		
		$full_langrans_session_array = get_full_langtrans_session($user_selected_iso2);
		
		
		//$_SESSION['language'][$source_language_iso2][$_XXXXX_ORIG_PATH_TRANSLATED][$time_id] = $text;
		
	
		//logger3("..updating..","");
		# return "..updating..";
	}
	
	
	
	/// !!! lots of overhear !!!! TO DO !!!
	convert_full_langtrans_session_to_pretty_language_session($_SESSION['language_raw_session']);
	
	
	
	//logger3("555 _SESSION['language'][$user_selected_iso2][$time_id]",$_SESSION['language'][$user_selected_iso2][$time_id]);
	
	//logger3("user_selected_iso2",$user_selected_iso2);
	//logger3("_SESSION['language'][$user_selected_iso2][$time_id]",$_SESSION['language'][$user_selected_iso2][$time_id]);
	
	/// attempt to translate:
	$final_translated_text = trim($_SESSION['language'][$user_selected_iso2][$time_id]);
	
	//logger3("_SESSION['language'][$user_selected_iso2][$time_id]",$_SESSION['language'][$user_selected_iso2][$time_id]);
	//logger3("final_translated_text",$final_translated_text);
	
	
	/// default to source:
	if(!$final_translated_text) {
		$final_translated_text = $_SESSION['language'][$source_language_iso2][$time_id];
	}
	
	//logger3("2final_translated_text",$final_translated_text);
	
	/// return final results:
	return $final_translated_text;

}

*/



function translang($text,$time_id="",$source_language_iso2="") {
	
	
	
	### ########################################################################
	### 
	### NOTES:	FOR NOW... translations are stored in a session.
	### 	
	### 		this session could get very big
	### 		
	### 		but it's better for speed on the server, 
	### 		
	### 		see: "translation is already set:"
	### 		
	### 
	### 
	### 
	### #######################################################################


		
	
	/////////////////////////////////////////////////////////////////////
	/// START: don't process  if....
	
	if(stristr($text,"blingk")) return $text;
	
	if(!$_SESSION['template']['company']['name'])  return $text;
	
	if(!trim($text))  return $text;
	
	
	if(!$time_id) return $text;
	if($time_id == null) return $text;
	if($time_id == 0) return $text;
	if($time_id == "0") return $text;
	
	/// END: don't process  if....
	/////////////////////////////////////////////////////////////////////
	
	
	
	
	
	
	
	/// set source language
	if(!$source_language_iso2) $source_language_iso2 = "en";
	
	/// set user selected from session
	$user_selected_iso2 = trim($_SESSION['user_selected_language_iso2']);
	
	/// set default user if non exist
	if(!$user_selected_iso2) $user_selected_iso2 = "en";
	
	
	
	
	/// if the translation is english, just return the text:
	if($source_language_iso2 == $user_selected_iso2)
	{
		return $text;
	
	
	/// translation is already set:
	} else if(isset($_SESSION['translation'][$user_selected_iso2][$time_id])) 
	{
		return $_SESSION['translation'][$user_selected_iso2][$time_id];
	
	
	
	// translation required....
	} else { 
	
		$_XXXXX_ORIG_PATH_TRANSLATED = $_SERVER['ORIG_PATH_TRANSLATED'];
		

		
		/// confirm new text matches existing time_id record:
		$tmp_sql = "SELECT text
					FROM service_text_language_translations
					WHERE language_iso2 = '". $source_language_iso2 ."'
					AND time_id = '". $time_id ."'
					;";
		$source_text_exists = getTHECASHIER($tmp_sql);
		
		if(trim($source_text_exists)) {
		
			if(trim($text) != trim($source_text_exists)) {
				
				
				/// log the difference:
				$translang_whatsdifferent = array();
				$translang_whatsdifferent[$time_id]['existing'] = $source_text_exists;
				$translang_whatsdifferent[$time_id]['new'] = $text;
				logger3($log_name="translang_whatsdifferent",$log_value=$translang_whatsdifferent,$action_code="",$log_filename="/BANGK!/logs/translang_whatsdifferent.logger");
				
				
				/// DESTROY ALL RELATED TIME IDs
				$tmp_sql = "DELETE FROM service_text_language_translations
							WHERE time_id = '". addslashes($time_id) ."'
							;";
				logger3("tmp_sql",$tmp_sql);
				$update_results = updateTHECASHIER($tmp_sql,"");
				logger3("update_results",$update_results);
				
				
				/// SET NEW
				$tmp_sql = 'INSERT INTO `service_text_language_translations`
								(
									`service_text_language_translations_id`
									, `ORIG_PATH_TRANSLATED`
									, `language_iso2`
									, `text`
									, `time_id`
									, `datetime_updated`
								) VALUES (
									"'. $blank .'"
									, "'. addslashes($_XXXXX_ORIG_PATH_TRANSLATED) .'"
									, "'. addslashes($source_language_iso2) .'"
									, "'. addslashes($text) .'"
									, "'. addslashes($time_id) .'"	
									, "'. datetime_v2() .'"
								);
							';
				logger3("tmp_sql",$tmp_sql);
				$insert_results = insertTHECASHIER($tmp_sql,"");
				logger3("insert_results",$insert_results);
				
				
				
				/// SET FINAL RESPONSE TEXT:
				$final_response_text = $text;
	
				
			} else { // new text matches existing source - get the translation:
				
					
				/// find the correct translation
				$tmp_sql = "SELECT text
							FROM service_text_language_translations
							WHERE language_iso2 = '". $user_selected_iso2 ."'
							AND time_id = '". $time_id ."'
							;";
				$translation_text_exists = getTHECASHIER($tmp_sql);
				
				
				/// SET FINAL RESPONSE TEXT:
				if(trim($translation_text_exists)) {
					
					$final_response_text = $translation_text_exists;
				
				} else { /// translation does not exist - return source text
					
					$final_response_text = $text;
				
				}
			}
		
		} else { // record does NOT YET exist - create a new record:
			
			
			$tmp_sql = 'INSERT INTO `service_text_language_translations`
						  (
							  `service_text_language_translations_id`
							  , `ORIG_PATH_TRANSLATED`
							  , `language_iso2`
							  , `text`
							  , `time_id`
							  , `datetime_updated`
						  ) VALUES (
							  "'. $blank .'"
							  , "'. addslashes($_XXXXX_ORIG_PATH_TRANSLATED) .'"
							  , "'. addslashes($source_language_iso2) .'"
							  , "'. addslashes($text) .'"
							  , "'. addslashes($time_id) .'"	
							  , "'. datetime_v2() .'"
						  );
					  ';
			logger3("tmp_sql",$tmp_sql);
			$insert_results = insertTHECASHIER($tmp_sql,"");
			logger3("insert_results",$insert_results);
			
			$final_response_text = $text;
		}
		
		
		if(!isset($_SESSION['translation'])) $_SESSION['translation'] = array();
		if(!isset($_SESSION['translation'][$user_selected_iso2])) $_SESSION['translation'][$user_selected_iso2] = array();
		
		$_SESSION['translation'][$user_selected_iso2][$time_id] = $final_response_text;
		return $final_response_text;
	
	}

}





function get_language_array() {

	return $language_array = array (
		"ab" => "Abkhazian"
		, "aa" => "Afar"
		, "af" => "Afrikaans"
		, "sq" => "Albanian"
		, "am" => "Amharic"
		, "ar" => "Arabic"
		, "an" => "Aragonese"
		, "hy" => "Armenian"
		, "as" => "Assamese"
		, "ae" => "Avestan"
		, "ay" => "Aymara"
		, "az" => "Azerbaijani"
		, "ba" => "Bashkir"
		, "eu" => "Basque"
		, "be" => "Belarusian"
		, "bn" => "Bengali"
		, "bh" => "Bihari"
		, "bi" => "Bislama"
		, "bs" => "Bosnian"
		, "br" => "Breton"
		, "bg" => "Bulgarian"
		, "my" => "Burmese"
		, "ca" => "Catalan"
		, "ch" => "Chamorro"
		, "ce" => "Chechen"
		, "zh" => "Chinese"
		, "cu" => "Church Slavic, Slavonic, Old Bulgarian"
		, "cv" => "Chuvash"
		, "kw" => "Cornish"
		, "co" => "Corsican"
		, "hr" => "Croatian"
		, "cs" => "Czech"
		, "da" => "Danish"
		, "dv" => "Divehi, Dhivehi, Maldivian"
		, "nl" => "Dutch"
		, "dz" => "Dzongkha"
		, "en" => "English"
		, "eo" => "Esperanto"
		, "et" => "Estonian"
		, "fo" => "Faroese"
		, "fj" => "Fijian"
		, "fi" => "Finnish"
		, "fr" => "French"
		, "gd" => "Gaelic, Scottish Gaelic"
		, "gl" => "Galician"
		, "ka" => "Georgian"
		, "de" => "German"
		, "el" => "Greek, Modern"
		, "gn" => "Guarani"
		, "gu" => "Gujarati"
		, "ht" => "Haitian, Haitian Creole"
		, "ha" => "Hausa"
		, "he" => "Hebrew"
		, "hz" => "Herero"
		, "hi" => "Hindi"
		, "ho" => "Hiri Motu"
		, "hu" => "Hungarian"
		, "is" => "Icelandic"
		, "io" => "Ido"
		, "id" => "Indonesian"
		, "ia" => "Interlingua"
		, "ie" => "Interlingue"
		, "iu" => "Inuktitut"
		, "ik" => "Inupiaq"
		, "ga" => "Irish"
		, "it" => "Italian"
		, "ja" => "Japanese"
		, "jv" => "Javanese"
		, "kl" => "Kalaallisut"
		, "kn" => "Kannada"
		, "ks" => "Kashmiri"
		, "kk" => "Kazakh"
		, "km" => "Khmer"
		, "ki" => "Kikuyu, Gikuyu"
		, "rw" => "Kinyarwanda"
		, "ky" => "Kirghiz"
		, "kv" => "Komi"
		, "ko" => "Korean"
		, "kj" => "Kuanyama, Kwanyama"
		, "ku" => "Kurdish"
		, "lo" => "Lao"
		, "la" => "Latin"
		, "lv" => "Latvian"
		, "li" => "Limburgan, Limburger, Limburgish"
		, "ln" => "Lingala"
		, "lt" => "Lithuanian"
		, "lb" => "Luxembourgish, Letzeburgesch"
		, "mk" => "Macedonian"
		, "mg" => "Malagasy"
		, "ms" => "Malay"
		, "ml" => "Malayalam"
		, "mt" => "Maltese"
		, "gv" => "Manx"
		, "mi" => "Maori"
		, "mr" => "Marathi"
		, "mh" => "Marshallese"
		, "mo" => "Moldavian"
		, "mn" => "Mongolian"
		, "na" => "Nauru"
		, "nv" => "Navaho, Navajo"
		, "nd" => "Ndebele, North"
		, "nr" => "Ndebele, South"
		, "ng" => "Ndonga"
		, "ne" => "Nepali"
		, "se" => "Northern Sami"
		, "no" => "Norwegian"
		, "nb" => "Norwegian Bokmal"
		, "nn" => "Norwegian Nynorsk"
		, "ny" => "Nyanja, Chichewa, Chewa"
		, "oc" => "Occitan, Provencal"
		, "or" => "Oriya"
		, "om" => "Oromo"
		, "os" => "Ossetian, Ossetic"
		, "pi" => "Pali"
		, "pa" => "Panjabi"
		, "fa" => "Persian"
		, "pl" => "Polish"
		, "pt" => "Portuguese"
		, "ps" => "Pushto"
		, "qu" => "Quechua"
		, "rm" => "Raeto-Romance"
		, "ro" => "Romanian"
		, "rn" => "Rundi"
		, "ru" => "Russian"
		, "sm" => "Samoan"
		, "sg" => "Sango"
		, "sa" => "Sanskrit"
		, "sc" => "Sardinian"
		, "sr" => "Serbian"
		, "sn" => "Shona"
		, "ii" => "Sichuan Yi"
		, "sd" => "Sindhi"
		, "si" => "Sinhala, Sinhalese"
		, "sk" => "Slovak"
		, "sl" => "Slovenian"
		, "so" => "Somali"
		, "st" => "Sotho, Southern"
		, "es" => "Spanish, Castilian"
		, "su" => "Sundanese"
		, "sw" => "Swahili"
		, "ss" => "Swati"
		, "sv" => "Swedish"
		, "tl" => "Tagalog"
		, "ty" => "Tahitian"
		, "tg" => "Tajik"
		, "ta" => "Tamil"
		, "tt" => "Tatar"
		, "te" => "Telugu"
		, "th" => "Thai"
		, "bo" => "Tibetan"
		, "ti" => "Tigrinya"
		, "to" => "Tonga"
		, "ts" => "Tsonga"
		, "tn" => "Tswana"
		, "tr" => "Turkish"
		, "tk" => "Turkmen"
		, "tw" => "Twi"
		, "ug" => "Uighur"
		, "uk" => "Ukrainian"
		, "ur" => "Urdu"
		, "uz" => "Uzbek"
		, "vi" => "Vietnamese"
		, "vo" => "Volapuk"
		, "wa" => "Walloon"
		, "cy" => "Welsh"
		, "fy" => "Western Frisian"
		, "wo" => "Wolof"
		, "xh" => "Xhosa"
		, "yi" => "Yiddish"
		, "yo" => "Yoruba"
		, "za" => "Zhuang, Chuang"
		, "zu" => "Zulu"
	);
}


function country_to_language($country_iso2) {
	
	$locales = array("af-ZA"
	,"am-ET"
	,"ar-AE"
	,"ar-BH"
	,"ar-DZ"
	,"ar-EG"
	,"ar-IQ"
	,"ar-JO"
	,"ar-KW"
	,"ar-LB"
	,"ar-LY"
	,"ar-MA"
	,"ar-OM"
	,"ar-QA"
	,"ar-SA"
	,"ar-SY"
	,"ar-TN"
	,"ar-YE"
	,"az-Cyrl-AZ"
	,"az-Latn-AZ"
	,"be-BY"
	,"bg-BG"
	,"bn-BD"
	,"bs-Cyrl-BA"
	,"bs-Latn-BA"
	,"cs-CZ"
	,"da-DK"
	,"de-AT"
	,"de-CH"
	,"de-DE"
	,"de-LI"
	,"de-LU"
	,"dv-MV"
	,"el-GR"
	,"en-AU"
	,"en-BZ"
	,"en-CA"
	,"en-GB"
	,"en-IE"
	,"en-JM"
	,"en-MY"
	,"en-NZ"
	,"en-SG"
	,"en-TT"
	,"en-US"
	,"en-ZA"
	,"en-ZW"
	,"es-AR"
	,"es-BO"
	,"es-CL"
	,"es-CO"
	,"es-CR"
	,"es-DO"
	,"es-EC"
	,"es-ES"
	,"es-GT"
	,"es-HN"
	,"es-MX"
	,"es-NI"
	,"es-PA"
	,"es-PE"
	,"es-PR"
	,"es-PY"
	,"es-SV"
	,"es-US"
	,"es-UY"
	,"es-VE"
	,"et-EE"
	,"fa-IR"
	,"fi-FI"
	,"fil-PH"
	,"fo-FO"
	,"fr-BE"
	,"fr-CA"
	,"fr-CH"
	,"fr-FR"
	,"fr-LU"
	,"fr-MC"
	,"he-IL"
	,"hi-IN"
	,"hr-BA"
	,"hr-HR"
	,"hu-HU"
	,"hy-AM"
	,"id-ID"
	,"ig-NG"
	,"is-IS"
	,"it-CH"
	,"it-IT"
	,"ja-JP"
	,"ka-GE"
	,"kk-KZ"
	,"kl-GL"
	,"km-KH"
	,"ko-KR"
	,"ky-KG"
	,"lb-LU"
	,"lo-LA"
	,"lt-LT"
	,"lv-LV"
	,"mi-NZ"
	,"mk-MK"
	,"mn-MN"
	,"ms-BN"
	,"ms-MY"
	,"mt-MT"
	,"nb-NO"
	,"ne-NP"
	,"nl-BE"
	,"nl-NL"
	,"pl-PL"
	,"prs-AF"
	,"ps-AF"
	,"pt-BR"
	,"pt-PT"
	,"ro-RO"
	,"ru-RU"
	,"rw-RW"
	,"sv-SE"
	,"si-LK"
	,"sk-SK"
	,"sl-SI"
	,"sq-AL"
	,"sr-Cyrl-BA"
	,"sr-Cyrl-CS"
	,"sr-Cyrl-ME"
	,"sr-Cyrl-RS"
	,"sr-Latn-BA"
	,"sr-Latn-CS"
	,"sr-Latn-ME"
	,"sr-Latn-RS"
	,"sw-KE"
	,"tg-Cyrl-TJ"
	,"th-TH"
	,"tk-TM"
	,"tr-TR"
	,"uk-UA"
	,"ur-PK"
	,"uz-Cyrl-UZ"
	,"uz-Latn-UZ"
	,"vi-VN"
	,"wo-SN"
	,"yo-NG"
	,"zh-CN"
	,"zh-HK"
	,"zh-MO"
	,"zh-SG"
	,"zh-TW");
				
				
	foreach ($locales as $key => $locale) {
		
		//test("locale",$locale);
		
		$test_country_iso2 = "-".strtoupper($country_iso2);
		
		//test("test_country_iso2",$test_country_iso2);
		
		if(strstr($locale,$test_country_iso2)) {
			
			$split = str_split($locale);
			
			//test("split",$split);
			
			return $split[0].$split[1];
		}
				
	}
	
	# default
	return "en";
	
}



function ip2location_v10($ip_address) {
	
	if(!$ip_address) $ip_address = $_SERVER['REMOTE_ADDR'];

	$curl = curl_init();
	
	$ip_to_location_url = "http://geodata.premiuum.net/?ip_address=". $ip_address;
	
	//test("url",$url);

	
	curl_setopt_array($curl, [
		CURLOPT_URL => $ip_to_location_url,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_ENCODING => "",
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 30,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => "GET",
		
	]);
	
	
			
	$response = curl_exec($curl);
	
	curl_close($curl);
	
	$response = json_decode($response);
	
	$response = object2array($response);
	
	//test("1 response",$response);
	
	return $response;
	
	exit;
	
}


function object_to_array_v10($object) {
	return $array = json_decode(json_encode($object), true);
}

function array_to_object_v10($array) {
	return $object = json_decode(json_encode($array), FALSE);
	//$object = json_decode(json_encode($array), FALSE);
	//return $object = (object) $array;
}






function INTELITRUTH_mailer($to_name="",$to_emailaddress="",$subject="",$html_message="",$from_name="",$from_email_address="") {
	


	#####################################
	### INTELITRUTH
	#####################################
	$mail = new PHPMailer;
	$mail->isSMTP();
	
	# $mail->addCustomHeader('MIME-Version', '1.0');
	# $mail->addCustomHeader('Content-type', 'text/html; charset=UTF-8');
	$mail->CharSet = 'UTF-8';
	
	// $mail->Host = 'smtp.gmail.com';  					// Specify main and backup SMTP servers
	// $mail->Username = 'shea.writer@nsdb.com';			// SMTP username
	// $mail->Password = 'Bangk0k!';						// SMTP password
	
	$mail->Host = 'smtp.gmail.com'; 
	$mail->Username = 'mailbox@nsdb.com';
	$mail->Password = 'qD*YBKfnK*zszcuMxpNEUqqc3n%Dz*%A';
	
	
	
	$mail->SMTPSecure = 'tls';
	$mail->SMTPAuth = true;
	$mail->Port = 587;
	
	
	$mail->SMTPOptions = array(
		'ssl' => array(
			'verify_peer' => false,
			'verify_peer_name' => false,
			'allow_self_signed' => true
		)
	);



	#####################################
	### TCP port to connect to
	
	$mail->setFrom($from_email_address, $from_name);
	
	$mail->addAddress($to_emailaddress, $to_name);
		
	$mail->addReplyTo($from_email_address,$from_name);
	
	# $mail->addCC('cc@example.com');
	
	$mail->addBCC("shea.writer@nsdb.com","premiuum cc: me");

	$mail->isHTML(true);
	
	$mail->Subject = $subject;
	
	$mail->Body    = $html_message;
	
	$mail->AltBody = '(NOTE: This email must be viewed with an HTML-compatible email client. Thank you.)';
	
	if(!$mail->send()) {
		logger3('Mailer Error',$mail->ErrorInfo);
	} else {
		logger3('Message has been sent');
	}
}




	
	
?>