<?php
/**
 **	common_functions.inc
 **		function definition file
 **
 **	Original Author:	Robby Anderson
 **	Original Date:		March 2001
 **
 **	Modified By:
 **	Modified On:
 **	Modifications:
 **
 **	This file contains the most commonly used functions throughout the site.
 **
 **	Contains the following functions:
 **		mkcurl
 **		mklink
 **		checkOverlib
 **		echon
 **		brAdd
 **		brStrip
 **		redirect
 **		getSponsorHomeFeature
 **		getSponsorCalloutImage
 **		getSponsorPhoneNumber
 **		debug
 **		showDebug
 **		dumpArray
 **		boolText
 **		statusStr
 **		lenderStatusStr
 **		lenderEnteredBy
 **		formatDocument
 **		formatParagraph
 **/


function mkcurl ( $path ) {

    $path = WEBHOME.$path;
	// Get the global doonce var
	//
	global $mkcurl_doOnce;
	// Set link variables
	$tid = false;
	$qvarList = array();
	$qvalList = array();
	$linktext = false;
	$linkextras = false;
	$doOnce = true;

	$qstr = '';
	$protocol = 'http';
	$hostname = getenv('HTTP_HOST');

	// If there are any query variables in the given path,
	// break them out and stick them in the QVLIST
	if (preg_match('/\?/', $path)) {
		list($url, $query) = preg_split('/\?/', $path);
		$path = $url;
		
		$vars = preg_split('/&/', $query);
		
		foreach ($vars as $var) {
			list($key, $val) = preg_split('/=/', $var);
			$qvarList[] = $key;
			$qvalList[] = $val;
		}
	}
	
	$_GET['archive'] = $_GET['archive'] ? $_GET['archive'] : 'no';
	
	if($_GET['archive'] == 'yes') {
		$qvarList[] = 'archive';
		$qvalList[] = 'yes';
	}	
	
	// Check to see if we got any args. If so, we have to process them.
	if ( $numArgs = func_num_args() ) {

		// Set the current arg to 0 and create the argList array
		$curArg = 0;
    		$argList = func_get_args();

		// Loop through the arg list
		while ( $curArg < $numArgs ) {
			// Switch the current arg
			switch ( $argList[$curArg] ) {
				case 'ID':
					// The ID is a throwback to the vignette code, which included an ID as part of the
					// actual URL. To make the port easier, we leave the syntax as is (you can set ID
					// as a parameter), but when we create the query string, we create a query var
					// named 'tID' and we pass the value supplied for ID with that query var
					$tid = $argList[++$curArg];
					break;

				case 'DOONCEOFF':
					// Turn off do once
					//
					$doOnce = false;
					break;

				case 'UNSECURE':
					$protocol = 'http';
					break;

				case 'SECURE':
					// Identify global variable - this is the secure server list
					global $GSEC_sserver;
					// Check to see whether the current server is on the secure server list. If
					// so, then change the protocol to 'https' instead of 'http'
					if ( in_array(strtolower(getenv('HTTP_HOST')),$GSEC_sserver) ) { 
						$protocol = 'https'; 
					}
					break;

				case 'QVLIST':
					// QVLIST stands for query var list. This is how we pass the query variables
					// to be used. Note that we have to both pass a space-delimited list of query
					// variables and a string-delimited space of corresponding values (i.e.,
					// ... QVLIST 'var1 var2 varN' 'value1 value2 valueN'
					
					if (!is_array($argList[++$curArg]))
						$qvarList = array_merge($qvarList, preg_split('/ /', $argList[$curArg]));
					else
						$qvarList = array_merge($qvarList, $argList[$curArg]);

					if (!is_array($argList[++$curArg]))
						$qvalList = array_merge($qvalList, preg_split('/ /', $argList[$curArg]));
					else
						$qvalList = array_merge($qvalList, $argList[$curArg]);
						
					break;

				case 'FORCEHOST':
					// Get the new hostname for this link
					$hostname = $argList[++$curArg];
					if ( in_array('SECURE',$argList) ) { $protocol = 'https'; }
					break;
				case 'LINKTEXT':
					// Get the text to go with the link
					$linktext = $argList[++$curArg];
					break;
				case 'LINKEXTRAS':
					// Get any extra attributes to go with the link. Note the space that is added
					// before the actual test. This is to prettify the link below.
					$linkextras .= ' '.$argList[++$curArg];
					break;
				case 'OVERLIB':
					// OVERLIB sets the overlib caption and text
					$olibArray = $argList[++$curArg];
					$linkextras .= ' '.checkOverlib($olibArray);
					break;
				case 'NOBOLD':
					// Add the 'class="nobold" to the linkextras
					$linkextras .= ' class="nobold"';
					break;
				case 'NOSESSION':
					// This means that we don't want to include the session query var
					$noSession = true;
					break;
				case 'TARGET':
					// Add a target=XXXX to the linkextras
					$target = $argList[++$curArg];
					$linkextras .= ' target="'.$target.'"';
					break;
			}

			// Increment the argument
			$curArg++;
		}
	}


	// Check to see if we're a google bot. If so, set the noSession variable
	//$userAgent = strtolower(getenv('HTTP_USER_AGENT'));

	if ( 0 and $doOnce ) {
		// This autosets javascript to only click on this link once. We need to check the
		// global mkcurl_doOnce variable and see if we need to set it or increment it
		if ( !$mkcurl_doOnce ) { $mkcurl_doOnce = 1; }
		$mkcurl_doOnce++;

		$linkextras .= ' onClick="return doOnce(\''.$mkcurl_doOnce.'\');"';
	}

	// If the path doesn't start with a slash, add the slash
	if ( $path[0] != '/' ) { $path = '/'.$path; }

	// Create the basic link
	$thisLink = "{$protocol}://{$hostname}{$path}";

	// If the session query string exists (and the noSession var doesn't exists),
	// add the session query string to the qstr
	//if ( globalVar('GSEC_sessionQueryString') and !isset($noSession) ) { $qstr .= globalVar('GSEC_sessionQueryString').'&'; }

	// If there is a tid, then add it to the query string
	if ( $tid ) { $qstr .= 'tID='.urlencode($tid).'&'; }

	// If there are qvars, add them to the query string.
	// NOTE: This doesn't account for values that have spaces in them... they should probably
	// be encoded (using + or something) before they get sent to this. Bummer, eh.
	if ( count($qvarList) > 0 ) {
		// split the qvars and qvals into an array (if necessary)
		//if ( !is_array($qvarList) ) { $qvarList = preg_split('/ /',$qvarList); }
		//if ( !is_array($qvalList) ) { $qvalList = preg_split('/ /',$qvalList); }
		//$qvalList = preg_split('/ /',$qvals);

		// Add each variable
		for ( $i = 0 ; $i < count($qvarList) ; $i++ ) {
			$qstr .= $qvarList[$i].'='.urlencode($qvalList[$i]).'&';
		}
	}

	// If there is a tid or any query vars, then we need to add them
	if ( $qstr ) {
		// Add the query seperator and the query string (minus the trailing '&' to
		// the actual link. The link is now created.
		$thisLink .= '?'.substr($qstr,0,-1);
	}

	// If there is link text, make this a hyperlink
	if ( $linktext ) { $thisLink = '<a href="'.$thisLink.'"'.$linkextras.'>'.$linktext.'</a>'; }

	// return the CURL
	return $thisLink;
}


function mklink ( $path ) {

	// Set link variables
	$qvars = false;
	$qvals = false;
	$qvarList = false;
	$qvalList = false;
	$linktext = false;
	$linkextras = false;

	$qstr = '';
	$protocol = 'http://';

	// Check to see if we got any args. If so, we have to process them.
	if ( $numArgs = func_num_args() ) {

		// Set the current arg to 0 and create the argList array
		$curArg = 0;
    		$argList = func_get_args();

		// Loop through the arg list
		while ( $curArg < $numArgs ) {
			// Switch the current arg
			switch ( $argList[$curArg] ) {
				case 'FTP':
					$protocol = 'ftp://';
					break;
				case 'MAILTO':
					$protocol = 'mailto:';
					break;
				case 'SECURE':
					$protocol = 'https://';
					break;
				case 'JAVASCRIPT':
					$protocol = 'javascript:';
					break;
				case 'EMPTY':
					$protocol = '';
					break;
				case 'QVLIST':
					// QVLIST stands for query var list. This is how we pass the query variables
					// to be used. Note that we have to both pass a space-delimited list of query
					// variables and a string-delimited space of corresponding values (i.e.,
					// ... QVLIST 'var1 var2 varN' 'value1 value2 valueN'
					$qvarList = $argList[++$curArg];
					$qvalList = $argList[++$curArg];
					break;
				case 'LINKTEXT':
					// Get the text to go with the link
					$linktext = $argList[++$curArg];
					break;
				case 'LINKEXTRAS':
					// Get any extra attributes to go with the link. Note the space that is added
					// before the actual test. This is to prettify the link below.
					$linkextras .= ' '.$argList[++$curArg];
					break;
				case 'OVERLIB':
					// OVERLIB sets the overlib caption and text and such
					$olibArray = $argList[++$curArg];
					$linkextras .= ' '.checkOverlib($olibArray);
					break;
				case 'NOBOLD':
					// Add the 'class="nobold" to the linkextras
					$linkextras .= ' class="nobold"';
					break;
				case 'MOVER':
					// Get the mouseover javascript
					$linkextras .= ' onMouseOver="'.$argList[++$curArg].'"';
					break;
				case 'MOUT':
					// Get the mouseout javascript
					$linkextras .= ' onMouseOut="'.$argList[++$curArg].'"';
					break;
				case 'TARGET':
					// Add a target=XXXX to the linkextras
					$target = $argList[++$curArg];
					$linkextras .= ' target="'.$target.'"';
					break;
			}

			// Increment the argument
			$curArg++;
		}
	}

	// Start creating the link
	$thisLink = $protocol.$path;

	// If there are qvars, add them to the query string.
	// NOTE: This doesn't account for values that have spaces in them... they should probably
	// be encoded (using +s or something) before they get sent to this. Bummer, eh.
	if ( $qvarList ) {
		// split the qvars and qvals into an array
		if ( !is_array($qvarList) ) { $qvarList = preg_split('/ /',$qvarList); }
		if ( !is_array($qvalList) ) { $qvalList = preg_split('/ /',$qvalList); }

		// Add each variable
		for ( $i = 0 ; $i < count($qvarList) ; $i++ ) {
			$qstr .= $qvarList[$i].'='.urlencode($qvalList[$i]).'&';
		}

		// Add the query seperator and the query string (minus the trailing '&' to
		// the actual link. The link is now created.
		$thisLink .= '?'.substr($qstr,0,-1);
	}
	// If there is link text, make this a hyperlink
	if ( $linktext ) { $thisLink = '<a href="'.$thisLink.'"'.$linkextras.'>'.$linktext.'</a>'; }

	// return the CURL
	return $thisLink;
}



function echon ( $str ) {
	echo $str."\n";
}

function echox ( $str ) {
	echo "\n".$str."\n";
    exit;
}

function brAdd ( $str ) {
	$str = preg_replace("/\n/", '<BR/>', $str);
	return $str;
}


function brStrip ( $str ) {
	$str = preg_replace('/<p>/i', "\n", $str);
	$str = preg_replace('/<\p>/i', "\n", $str);
	$str = preg_replace('/<BR/>/i', "\n", $str);
	return $str;
}


function redirect ( $loc ) {
	// We can use this to redirect to a specific page url, or we can use this to a redirect
	// to a status code
	switch ( $loc ) {
		case 'NOT_FOUND':
			//header('Location: '.mkcurl('/NotFound.html'));
			header('Location: '.mkcurl('','SECURE'));
			exit;
			break;
		case 'CLOSE_WIN':
			// Don't actually pass a header, but instead write javascript that will close
			// this window, and then exit
			echo('<script language="javascript">window.close();</script>');
			exit;
			break;
		default:
			// We assume that the location passed is a valid URL. Pass the location header,
			// but also include the redirect page, just in case (for some odd reason) that
			// they cannot support the location header
			//_DBG($_SERVER["REQUEST_URI"]." => $loc",'redirect','/tmp/redirect');
			header('Location: '.$loc);
			exit;
			break;
	}

	// Flush all the variables in the GLOBAL array, except for $redir (and $GLOBAL)
	foreach ( $GLOBALS as $thisVar ) {
		if ( $thisVar != 'GLOBALS' and $thisVar != 'redir' ) { unset($$thisVar); }
	}

}




function boolText ( $bval ) {
	return $bval ? 'Yes' : 'No';
}


function statusMessage ( $statusMsg ) {

		// Switch the query var to find the appropriate output
		switch ( $statusMsg ) {
			case 'MERIDIAN_SENT':
				$thisMsg = 'Application sent through MeridianLink, please check back for decision.';
				break;
			case 'MERIDIAN_SEND_ERROR':
				$thisMsg = 'Meridian Link Send Error: Check Decision Notes';
				break;
			case 'AUTORESPONDER_UPDATED':
				$thisMsg = 'Auto responder updated successfully.';
				break;
			case 'ACCT_UPDATE':
				$thisMsg = 'Your Account Information has been updated successfully.';
				break;
			case 'APP_CANCELLED':
				$thisMsg = 'Application cancelled successfully.';
				break;
			case 'APP_CHECKIN':
				$thisMsg = 'Application checked in.';
				break;
			case 'APP_CHECKOUT':
				$thisMsg = 'Application checked out.';
				break;
			case 'APP_MARKED':
				$thisMsg = 'Application marked as entered.';
				break;
			case 'APP_UNMARKED':
				$thisMsg = 'Application un-marked as entered.';
				break;
			case 'APP_NOCANCEL':
				$thisMsg = 'Application could not be cancelled.';
				break;
			case 'APP_SUBMITTED':
				$thisMsg = 'Application successfully submitted.';
				break;
			case 'BAD_DATE':
				$thisMsg = '<b>Error: Invalid date value</b><BR/>Please check all date values to make sure they are valid.';
				break;
			case 'BOOKOUT_DECREASE':
				$thisMsg = 'Data updated successfully.<BR/>Bookout value has decreased.';
				break;
			case 'BOOKOUT_DECREASE_DECISIONED':
				$thisMsg = 'Data updated successfully.<BR/>NOTICE: Bookout value has decreased, contact lender immediately regarding this change.';
				break;
			case 'BOOKOUT_INCREASE':
				$thisMsg = 'Data updated successfully.<BR/>Bookout value has increased.';
				break;
			case 'BOOKOUT_INCREASE_DECISIONED':
				$thisMsg = 'Data updated successfully.<BR/>NOTICE: Bookout value has increased, contact lender immediately regarding this change.';
				break;
			case 'BUREAU_ERROR_ENCOUNTERED':
				$thisMsg = '<b>There were one or more errors pulling the Credit File.</b>';
				break;
			case 'BUREAU_PULLED':
				$thisMsg = 'Credit File pulled and saved successfully.';
				break;
			case 'CHECKLIST_UPDATED':
				$thisMsg = 'Checklist updated successfully.';
				break;
			case 'CREDIT_PARSED':
				$thisMsg = 'Credit File parsed successfully.';
				break;
			case 'CREDIT_SAVED':
				$thisMsg = 'Credit File saved successfully.';
				break;
			case 'DATA_UPDATE':
			case 'DATA_UPDATED':
				$thisMsg = 'Data updated successfully.';
				break;
			case 'DUPLICATE_LOGIN':
                $thisMsg = 'You are already logged in.';
				break;
			case 'EMAIL_SENT':
				$thisMsg = 'All quotes E-mailed to customer.';
				break;
			case 'EMAIL_1_SENT':
				$thisMsg = 'quote 1 E-mailed to customer.';
				break;
			case 'EMAIL_2_SENT':
				$thisMsg = 'quote 2 E-mailed to customer.';
				break;
			case 'EMAIL_3_SENT':
				$thisMsg = 'quote 3 E-mailed to customer.';
				break;
			case 'FP_MISSING_USER':
				$thisMsg = '<b>ERROR:</b> No username was entered. Please enter your username, then click <b>Submit</b>.';
				break;
			case 'PWD_STANDARDS':
				$thisMsg = '<b>ERROR:</b> Passwords must contain: <br/>
						- at least one number, <br/>
						- one lower and  <br/>
                        - one upper case letter, and <br/>
                        - one special character: @#$%^&+=()*! <br/>
						- 8 or more characters';
				break;
			case 'HOLD_NOTE':
				$thisMsg = '<b>Hold Note Exists</b><BR/>Please resolve the Hold Note before advancing the application.';
				break;
			case 'IDENTITY_ASSUMED':
				$thisMsg = 'User identity successfully assumed.';
				break;
			case 'IDENTITY_DROPPED':
				$thisMsg = 'User identity successfully dropped.';
				break;
			case 'INVALID_IP_MATCH':
			case 'SESSION_EXPIRED':
				$thisMsg = 'Your previous session has expired, timed out or was terminated for some other reason. Please login again.';
				break;
			case 'IMPORT_ERROR':
				$thisMsg = '<b>Warning:</b> Errors encountered during Import.';
				break;
			case 'IMPORT_SUCCESS':
				$thisMsg = 'Import completed successfully.';
				break;
			case 'INCOMPLETE_BOOKOUT':
				$thisMsg = '<b>Error: Bookout incomplete</b><BR/>Please make sure the vehicle has been properly valued before continuing.';
				break;
			case 'INCOMPLETE_BUREAU':
				$thisMsg = '<b>Error: Credit bureau incomplete</b><BR/>Please pull the appropriate credit bureau before continuing.';
				break;
			case 'INCOMPLETE_CHECKLIST':
				$thisMsg = '<b>Error: Checklist incomplete</b><BR/>Please make sure the appropriate checklist has been completed, then try again.';
				break;
			case 'INCOMPLETE_MAILER':
				$thisMsg = '<b>Error: Mailer linking incomplete</b><BR/>Please link the mailer data before continuing.';
				break;
			case 'INCOMPLETE_TASKS':
				$thisMsg = '<b>Error: Tasks incomplete</b><BR/>Please complete all tasks before continuing.';
				break;
			case 'INCOMPLETE_TITLE':
				$thisMsg = '<b>Error: Title data incomplete</b><BR/>Please pull the title before continuing.';
				break;
            case 'INVALID_CAPTCHA':
                $thisMsg = "<b>Error: Captcha did not validate</b><BR/>Please re-enter and try again.";
                break;
			case 'INVALID_FORGOTPWD':
				$thisMsg = "<b>Error: User not found</b><BR/>Couldn't find a user with this Username and Email. Please re-enter and try again.";
				break;
			case 'INVALID_LOGIN':
			case 'INVALID_LOGIN_LOCKOUT':
				$thisMsg = '<b>Login Failed:</b> Username/Password combination not found or account is locked. Please try again.';
				break;
			case 'INVALID_PASSWORD':
				$thisMsg = '<b>Error: Current Password Incorrect</b><BR/>Please check the Current Password field, then try again.';
				break;
			case 'INVALID_PERMISSIONS':
				$thisMsg = 'The page you requested requires that you are logged in. Please login.';
				break;
			case 'INVALID_PERMLEVEL':
				$thisMsg = '<b>Error: Invalid permissions</b><BR/>You do not have the permission level to perform the task you are attempting.';
				break;
			case 'INVALID_PROMO_CODE':
				$thisMsg = '<b>Error: Invalid Promo Code</b><BR/>Promo code not found in database. Please start application from the beginning.';
				break;
			case 'INVALID_SEARCH':
				$thisMsg = 'Invalid Search. Please make sure you filled out the minimum length for the field(s) you selected.';
				break;
			case 'INVALID_USER':
				$thisMsg = '<b>Error: Invalid User</b><BR/>Please check to make sure the username you entered is correct.';
				break;
			case 'LOGOUT_FORCED':
				$thisMsg = '<b>You have been logged out</b>';
				break;
			case 'LENDER_MARKED':
				$thisMsg = 'Lender successfully marked.<BR/><b>Note:</b> Make sure to send the application to the Lender.</b>';
				break;
			case 'LENDER_UNMARKED':
				$thisMsg = 'Lender successfully unmarked.';
				break;
			case 'LSTATUS_APPROVED':
				$thisMsg = 'Application successfully approved';
				break;
			case 'LSTATUS_DECLINED':
				$thisMsg = 'Application successfully declined';
				break;
			case 'LSTATUS_CHANGED':
				$thisMsg = 'Application status successfully changed';
				break;
			case 'MD_UPDATED':
				$thisMsg = 'Thank you for updating your application. We will review and process it, and your dedicated Loan Agent should contact you and explain the next steps in the process within a few business days.';
				break;
			case 'MISSING_APP_TYPE':
				$thisMsg = 'Please select the type of loan you are applying for.';
				break;
			case 'MISSING_DECISION':
				$thisMsg = '<b>Error: No Decision Entered</b>';
				break;
            case 'MISSING_CAPTCHA':
                $thisMsg = '<b>Error: Missing Captcha</b><BR/>Please check to make sure all required fields are entered, then try again.';
                break;
			case 'MISSING_FIELDS':
				$thisMsg = '<b>Error: Missing required fields</b><BR/>Please check to make sure all required fields are entered, then try again.';
				break;
			case 'MISSING_PARAMETERS':
				$thisMsg = 'Login Failed: Please enter both Username and Password and try again.';
				break;
			case 'MISSING_GAP_DATA':
				$thisMsg = '<b>WARNING: DATA NOT SAVED - Missing Gap Sale data</b><BR/>Please make sure all Gap Sale data has been entered.';
				break;
			case 'MISSING_WARRANTY_DATA':
				$thisMsg = '<b>WARNING: DATA NOT SAVED - Missing Warranty Sale data</b><BR/>Please make sure all Warranty Sale data has been entered.';
				break;
			case 'MISSING_SEARCH_PARAMETERS':
				$thisMsg = '<b>Error:</b> Missing Search Parameters.';
				break;
			case 'NADA_CALCULATED':
				$thisMsg = 'NADA values successfully calculated.';
				break;
			case 'NADA_INVALID_VIN':
				$thisMsg = '<b>Error: Cannot calculate NADA values</b><BR/>Please check the VIN to make sure that it is valid.';
				break;
			case 'NADA_MISSING_VALUES':
				$thisMsg = '<b>Error: Cannot calculate NADA values</b><BR/>Please check to make sure this application has values values for VIN, State and Mileage.';
				break;
			case 'NEED_CONFIRM':
				$thisMsg = 'You <b>must</b> confirm each statement before submitting this loan application.';
				break;
			case 'NEWCUST_ADDED':
				$thisMsg = 'New Customer and Application successfully added.';
				break;
			case 'NO_QUOTES':
				$thisMsg = 'No Quick Quotes found to E-mail.';
				break;
			case 'NOTE_ADDED':
				$thisMsg = 'Note successfully added.';
				break;
			case 'NOTE_UPDATED':
				$thisMsg = 'Note successfully updated.';
				break;
			case 'PASSWORD_NOMATCH':
				$thisMsg = '<b>Error: Passwords do not match</b><BR/>Please check the Password and Password (confirm) fields, then try again.';
				break;
			case 'PREAPP_ERROR':
				$thisMsg = '<b>Technical Error during Registration</b><BR/>There was an unspecified technical error while you were registering. Please try again in a moment.';
				break;
			case 'PREAPP_EXISTS':
				$thisMsg = '<b>Error: User already exists.</b><BR/>This Approval # has already registered. Please return to the home page and login with your Username and Password.	';
				break;
			case 'PWD_CHANGE':
				$thisMsg = 'Password successfully changed.';
				break;
			case 'SEND_SUCCESSFUL':
				$thisMsg = 'Application was sent successfully.';
				break;
			case 'SHIP_LABEL_CREATED':
				$thisMsg = 'Shipping label successfully created. Now click the link to print the shipping label.';
				break;
			case 'SHIP_LABEL_ERROR':
				$thisMsg = 'Error creating shipping label. Please try again. If the error persists, please contact Customer Service.';
				break;
			case 'STATUS_CHANGED':
				$thisMsg = 'Application Status successfully changed.';
				break;
			case 'SUBMIT_ERROR':
				$thisMsg = 'There was an unknown error submitting your application. Please check to make sure that all fields are filled out properly, and then submit your application again.';
				break;
			case 'USER_DISABLED':
				$thisMsg = 'User successfully disabled.';
				break;
			case 'USER_EXISTS':
				$thisMsg = '<b>Error: User already exists</b><BR/>Please enter a different Username and try again.';
				break;
			// http://www.docusign.com/p/APIGuide/Content/Administrative%20Group/Embedded%20Callback%20Event%20Codes.htm
			case 'OnAccessCodeFailed':
				$thisMsg = 'The Access Code is incorrect';
				break;
			case 'OnCancel':
				$thisMsg = 'The document has been canceled';
				break;
			case 'OnDecline':
				$thisMsg = 'The envelope has been declined';
				break;
			case 'OnException':
				$thisMsg = 'An exception has been thrown';
				break;
			case 'OnFaxPending':
				$thisMsg = 'A faxed in document is pending';
				break;
			case 'OnIdCheckFailed':
				$thisMsg = 'You have failed to pass the ID Check authentication questions';
				break;
			case 'OnSessionTimeout':
				$thisMsg = 'The session has timed out';
				break;
			case 'OnSigningComplete':
				break;
			case 'OnTTLExpired':
				$thisMsg = 'The Token URL being invoked has expired';
				break;
			case 'OnViewingComplete':
				$thisMsg = 'The document has successfully been viewed';
				break;
			default:
				$thisMsg = 'Status Message: <b>'.preg_replace('/<script.+?<\/script>/im', "", $statusMsg).'</b>';
				break;
		}

	return $thisMsg;
}



function formatDocument ($body, $margin, $indent = '', $trailnl = false, $hindent = '') {

	$body = preg_replace("/(\r|\n){2}?/", '-=P=-', $body);

	$bodyA = preg_split('/-=P=-/', $body);

	// A bit crude, but the $trailnl should only effect the newline at the end
	// of the document, not each paragraph.  So we have to look through
	// everything but the last paragraph to create most of the document, and
	// then add the last one with the correct $trailnl...

	$newBody = '';

	for( $counter = 0 ; $counter < ( sizeof($bodyA) - 1 ); $counter++ )
	{
		$newBody .= formatParagraph(array($bodyA[$counter]), $margin, $indent, true, $hindent);
	}

	$newBody .= formatParagraph(array($bodyA[$counter]), $margin, $indent, $trailnl, $hindent);

	return( $newBody );
}


function formatParagraph ($body , $margin, $indent = '', $trailnl = true, $hindent = '') {

	$nParagraph = '';

	foreach( $body as $paragraph) {
		$line = $indent;
		$llength = strlen($indent);

		$paragraph = str_replace("\r", ' ', $paragraph);
		$paragraph = str_replace("\n", ' ', $paragraph);
		$paragraph = str_replace("\t", ' ', $paragraph);

		$words = preg_split("/ /", $paragraph);
		$wcount = sizeof($words);

		for( $wpos = 0; $wpos < $wcount; $wpos++ )
		{
			$word = $words[$wpos];
			$wlength = strlen($word) + 1;

			if( ($llength + $wlength > $margin) && $wlength > 1 )
			{
				$nParagraph .= $line . "\r\n";
				$line = $hindent . $indent;
				$llength = strlen($hindent) + strlen($indent);
			}

			$line .= $word . ' ';
			$llength += $wlength;
		}

		$nParagraph .= $line;

		$nParagraph .= "\r\n";

		if( $trailnl )
		{
			$nParagraph .= "\r\n";
		}
	}

	return( $nParagraph );
}


?>
