Location: PHPKode > projects > Homeless Mangement Information System > hmis/include/client_profile_class.inc
<?php
//*Client Data System, Copyright (C) 2000, 2001, 2002, 2003 Tedd Kelleher.  This is free software, subject to the 
//*GNU GENERAL PUBLIC LICENSE, Version 2, June 1991 (in file named gpl.txt), which should accompany 
//*any distribution of this file.  Tedd Kelleher can be contacted at hide@address.com

class Client_profile
{
    var $report_id;
    
	//This function is used for inserting a NEW client into the system and for editing an EXISTING client
	//which is in fact an insert since we do not overwrite report data...
    function insert_client_profile_answers ( $report_type, $client_info, $questions_attributes, $alt_org_id='', $alt_hoh_designation='' )
    {
		GLOBAL $org_id, $user_id, $unix_date, $unique_seq, $message, $message_type;
		$report_type = addslashes($report_type);
        
		//echo "<br><b>insert_client_profile</b><br>";
		//echo pretty_var_dump($client_info)."<br>";
        
        //If we are specifying a different org id than the global one, use it
        if ($alt_org_id)
        {
            $use_org_id = $alt_org_id;
        }
        else 
        {
            $use_org_id = $org_id;
        }
        transaction_begin ( 'Trans begin for insert client report answers' );
        
        //Loop through the client profiles
        foreach ( $client_info AS $client_info_array )
        {
                //Find if there is an existing client profile report
                $sqlo = "SELECT client_rpt_id FROM client_rpt_profile WHERE client_id = '".$client_info_array["client_id"]."' AND
                         report_org_id = '".$use_org_id."' AND report_type = '".$report_type."' AND succeeded_by IS NULL";
                $existing_report = run_query ($sqlo, "Finding Existing Reports");
                
                //If this is the type of report that does not cover a period of time (i.e., ethnicity and disabilities, put some
                // values into the begin and end date so queries can find the people by date
    		    if( !$client_info_array['report_date_beginc'] ) 
    		    {
                    $client_info_array['report_date_beginc'] = $unix_date;
                }
                if( !$client_info_array['report_date_endc'] )
                {
                    $client_info_array['report_date_endc'] = $unix_date;
                }
                
                //Convert dates into their encrypted date equivalent
                $client_info_array['report_date_beginc'] = date_encrypted_find_index_unix_time ( $client_info_array['report_date_beginc'] );
                $client_info_array['report_date_endc'] =   date_encrypted_find_index_unix_time ( $client_info_array['report_date_endc'] );
                $en = new Encryption ();
                $unix_date_encrypted = addslashes ( $en->encrypt_data ( $unix_date ) );
                
                $sqla = "INSERT INTO client_rpt_profile (client_rpt_id, client_id, report_type, report_org_id, report_user_id, report_timestamp, report_date_beginc, report_date_endc, client_rpt_sharing_permission) VALUES ('0', '".$client_info_array["client_id"]."', '".$report_type."', '".$use_org_id."', '".$user_id."', '".$unix_date_encrypted."', '".$client_info_array["report_date_beginc"]."', '".$client_info_array["report_date_endc"]."', '".$client_info_array["client_rpt_sharing_permission"]."')";
    		    run_query ($sqla, "Insert client profile");
                //echo '<br>Insert client profile:<br>'.$sqla;
                
    		    $sqlb = "SELECT clnt_rpt_rowid FROM client_rpt_profile WHERE report_user_id LIKE '".$user_id."' AND report_timestamp LIKE '".$unix_date_encrypted."' AND client_id = '".$client_info_array["client_id"]."'";
    		    $report_id_result = run_query ($sqlb, "Insert report ProfileB");
                //echo '<br>Insert report ProfileB:<br>'.$sqlb;
                
    		    $this->report_id = fetch_result($report_id_result, "Extract report ID");
                
    		    $sqlc = "UPDATE client_rpt_profile SET client_rpt_id='".$this->report_id."' WHERE clnt_rpt_rowid = '".$this->report_id."'";
    		    run_query ($sqlc, "Insert report ProfileC");
                log_report_activity ( $user_id, 'client', $this->report_id, 'create_clnt_profile' );
                
                //echo '<br>Insert report ProfileC:<br>'.$sqlc;
                
                /////////////////////////////
                // UPDATE EXISTING PROFILE //
                /////////////////////////////
                
                //If there is an existing report, depreciate the old report by putting the new report id into the succeeded_by column
                if( num_rows ($existing_report) > 0 )
                {
                    $existing_report_number = fetch_result ($existing_report, "Fetching Report Number");
                    
                    //Need to get existing profile answers 
                    $sqloa = "SELECT client_rpt_question_id, client_rpt_answer, client_rpt_answer_int FROM client_rpt_answers WHERE client_rpt_id = '".$existing_report_number."'";
                    
                    $existing_report_answers = run_query_return_array ($sqloa, "Finding Existing Report Answers");
                    //echo '<br>Finding Existing Report Answers:<br>'.$sqloa;
                    
                    $existing_report_column_for_answer = array();
                    
                    //Adding old answers from profile form for updating
                    foreach( $existing_report_answers as $old_answer )
                    {
                        if (!$old_answer["client_rpt_answer_int"])
                        {
                            $old_answer["client_rpt_answer_int"] = "NULL";
                            $existing_report_column_for_answer[$old_answer['client_rpt_question_id']] = 'client_rpt_answer';
                        }
                        else
                        {
                            $existing_report_column_for_answer[$old_answer['client_rpt_question_id']] = 'client_rpt_answer_int';
                        }
                        
                        $sql = "INSERT INTO client_rpt_answers (client_rpt_id, client_rpt_question_id, client_rpt_answer, client_rpt_answer_int) VALUES ('".$this->report_id."', '".$old_answer["client_rpt_question_id"]."', '".$old_answer["client_rpt_answer"]."', ".$old_answer["client_rpt_answer_int"].")";
                        run_query ($sql, "Insert array report answer");
                        //echo '<br>Insert array report answer:<br>'.$sql;
                    }
                    //echo '<hr color=red>'.pretty_var_dump($existing_report_column_for_answer);
                    //update old answers with new values
    		        //Loop through the questions set
    		        foreach($client_info_array AS $question_id => $current_answer)
    		        {
           				//echo "<br>$question_id) $current_answer - and was... ".pretty_var_dump($existing_report_column_for_answer);
    				    
                        if (is_int($question_id))
                        {
                             //If the answer is an array (i.e., checkboxes) loop through array
                             if(is_array($current_answer))
                             {
                                    //echo "<ol>Array answers being updated: ".$question_id."<br>";
                                    foreach($current_answer AS $array_answer)
                                    {
                                        //todo: this is kind of a hack.  The problem is that the question_id is 98 which does not match up with the 
                                        //$question_id client_year_born0 for instance in the case of 98,100,101, etc profile answers...
                                        //but since we are updating we can cheat... update int if int was previously set for this id or nonint...
                                        //                                     client_rpt_answer_int/client_rpt_answer
                                        $sql = "UPDATE client_rpt_answers SET ".$existing_report_column_for_answer[$question_id]." = '".$array_answer."' where client_rpt_id = '".$this->report_id."' and client_rpt_question_id = '".$question_id."'";
                                        run_query ($sql, "Update array report answer");
                                        //echo '<li>Update array report answer'.$sql."</li>";
                                    }
                                    //echo "</ol>";
                             }
                             else
                             {
                                //echo "<ul>Non-array answers being updated: ".$question_id."<br>";
                                
                                //Actually insert the report answers
                                $current_answer = addslashes($current_answer);
                                
                                //echo "<hr><table><tr><td>".pretty_var_dump($vetted_value)."</td><td>".pretty_var_dump($questions_attributes)."</td></tr></table><hr>";
                                //even if the type is number, #99# and other codes may need to be entered into the text field and <NULL> entered into the int field
                                $sql = "UPDATE client_rpt_answers SET ".$existing_report_column_for_answer[$question_id]." = '".$current_answer."' where client_rpt_id = '".$this->report_id."' and client_rpt_question_id = '".$question_id."'";
                                
                                //echo "Question #: ".$question_id." Answer: ".$vetted_value[$question_id]."<br>";
                                //echo '<li>'.$sql.'</li></ul>';
                                run_query ($sql, "Update report answer");
                            }
                        }
                    }
                    
                    $sqlp = "UPDATE client_rpt_profile SET succeeded_by = '".$this->report_id."' WHERE client_rpt_id = '".$existing_report_number."'";
                    run_query ($sqlp, "Depreciate existing form");
                    //echo '<br>Depreciate the form:<br>'.$sqlp;
                }
                
                /////////////////////////////
                //   INSERT NEW PROFILE    //
                /////////////////////////////
                
                else
                {
        		     //Loop through the questions set
        		     foreach($client_info_array AS $question_id => $current_answer)
        		     {
                        if (is_int($question_id))
                        {
                             //If the answer is an array (i.e., checkboxes) loop through array
                             if(is_array($current_answer))
                             {
                                    //echo "<ul>Array answers being inserted: ".$question_id."<br>";
                                    foreach($current_answer AS $array_answer)
                                    {
                                         //echo $array_answer."<br>";
                                         $sql = "INSERT INTO client_rpt_answers (client_rpt_id, client_rpt_question_id, client_rpt_answer) VALUES ('".$this->report_id."', '".$question_id."', '".$array_answer."')";
                                          //VALUES ('".$this->report_id."', '".$question_id."', '".$vetted_value[$question_id]."')";
                                         run_query ($sql, "Insert array report answer");
                                         //echo '<li>Insert array report answer'.$sql."<br/>";
                                    }
                                    //echo "</ul>";
                             }
                             else
                             {
                                //echo "<ul>Non-array answers being inserted: ".$question_id."<br>";
                                
                                //Actually insert the report answers
                                $current_answer = addslashes($current_answer);
                                
                                //even if the type is number, #99# and other codes may need to be entered into the text field and <NULL> entered into the int field
                                if ( $questions_attributes[$question_id]["question_type"]=="number" && strstr($current_answer,'#') )
                                {   //client_rpt_answer_int
                                    $sql = "INSERT INTO client_rpt_answers (client_rpt_id, client_rpt_question_id, client_rpt_answer, client_rpt_answer_int) VALUES
                                    ('".$this->report_id."', '".$question_id."', '".$current_answer."', null)";
                                }
                                elseif ($questions_attributes[$question_id]["question_type"] == "number")
                                {
                                    $sql = "INSERT INTO client_rpt_answers (client_rpt_id, client_rpt_question_id, client_rpt_answer_int) VALUES
                                    ('".$this->report_id."', '".$question_id."', '".$current_answer."')";
                                }
                                else
                                {
                                    $sql = "INSERT INTO client_rpt_answers (client_rpt_id, client_rpt_question_id, client_rpt_answer) VALUES
                                    ('".$this->report_id."', '".$question_id."', '".$current_answer."')";
                                }
                                
                                //echo "Question #: ".$question_id." Answer: ".$vetted_value[$question_id]."<br>";
                                //echo '<li>'.$sql.'</li></ul>';
                                run_query ($sql, "Insert report answer");
                            }
                        }
                    }
                    
                    //ONLY UPDATE HOUSEHOLD RELATIONSHIPS WHEN CLIENTS ARE ADDED NOT WHEN PROFILE IS EDITED.
                    $insert_hh_rpt = new Insert_household_report();
                    settype ( $questions_atts, 'array' );
                    $inserted_hh_rpt_id = $insert_hh_rpt->insert_report_answers ( 'INTAKE', $client_info, $questions_atts, $vetted_value, $org_id, 'yes' );
    			}
        
        $message = "Client Identifiers/Profile successfully entered. ";
        transaction_commit ( 'Trans commit for insert_client_profile_answers' );
        }
        
        $message_type = "ok";
	}



    function pull_client_reports_result ($client_id)
	{
        GLOBAL $org_id;
        $sql = "SELECT DISTINCT(client_rpt_id), report_type, client_rpt_sharing_permission 
			FROM client_rpt_profile 
         		WHERE 
					client_rpt_profile.client_id = '".$client_id."'
         			AND client_rpt_profile.succeeded_by IS NULL"; 
                    
                    //AND client_rpt_profile.report_type = 'client_profile'";
         $profile_reports = run_query($sql, "Pulling Client Profile report numbers");
         //echo $sql."<p>";
         
         //$z = run_query_return_array ($sql, "gfgf");
         //var_dump($z);
         
         return $profile_reports;
    }



    function pull_client_identifier_reports ( $client_id )
    {
        GLOBAL $org_id, $user_id;
        $sql = "
        SELECT 
            DISTINCT(client_rpt_id), report_type, report_org_id
        FROM 
            client_rpt_profile, report_type_profile
         		WHERE report_type_profile.report_type_id LIKE client_rpt_profile.report_type
                    AND report_type_profile.report_on_unit LIKE 'client_identifier'
                    
					AND client_rpt_profile.client_id = '".$client_id."'
         			AND client_rpt_profile.succeeded_by IS NULL"; 
                    
                    
                    //AND client_rpt_profile.report_type = 'client_profile'";
         $profile_reports = run_query_return_array ( $sql, 'Pulling Client Profile report numbers' );
         //echo $sql."<p>";
         
         $z = 0;
         foreach ( $profile_reports AS $cur_rpt )   
         {                        
            $perms = report_permissions_client ( $cur_rpt['client_rpt_id'], $org_id, $user_id );
            if ( $perms['read_rpt'] == 1 )  
            {
                $return_rpts[$z] = $cur_rpt;
                $z++;    
            
            }
         
         }
         
         //var_dump ( $return_rpts );
         return $return_rpts;
    }



	function pull_client_profile_array ( $client_id )	
	{
		GLOBAL $org_id, $access_level, $org_id, $group_id;
        
        //$profile_reports = $this->pull_client_reports_result ($client_id);  
        //This option only pulls clieft identifier reports, instead of data from every client report that exists
        $profile_reports = $this->pull_client_identifier_reports ( $client_id ); 
        
        //Loop through the shared client profile reports....
        //$report_count = count ( $profile_reports );
        //echo "<p>Count is: ".$report_count."<p>";
		$cl_lkup = new Client_lookup();
        
        foreach ( $profile_reports AS $cur_rpt )
		{
            $report_number = $cur_rpt;
            //echo 'On rpt: '.$report_number['client_rpt_id'].'<p>';
            
            //Pull out the org-gen_cli_ids assoicated with this origanization's report 
            //echo 'Org id is: '.$cur_rpt['report_org_id'].'<p/>';
            $cl_ids = $cl_lkup->pull_related_org_identifiers ( $client_id, $cur_rpt['report_org_id'] );
            //var_dump ( $cl_ids );
            
            //If not Anon
            if ( $cl_ids )
			{
                //Loop through the ids and put them into the array we are returning
                foreach ( $cl_ids AS $id_type => $id_val )
				{
                    $org_gen_ids[$id_type][$cur_rpt['report_org_id']] = $id_val;
                    //If we have not seen this id for this client, add to result
                }
            }
            //$client_info_array['client_rpt_sharing_permission'] = $report_number['client_rpt_sharing_permission'];
            
            //IGNORE,fixed to only pull client identifier reports//For each report pull out the attributes of the questions in that report ******FIX THIS TO ALLOW DIFFERENT REPORTS
            //$report_questions = new Questions_into_array ("client_profile", $access_level, $org_id, $group_id, "display");
            $report_questions = new Questions_into_array ( $report_number['report_type'], $access_level, $org_id, $group_id, 'display' );
            
            //echo $report_number["report_type"]."<p>";
            $sqlb = "SELECT * FROM client_rpt_answers WHERE client_rpt_id = '".$report_number['client_rpt_id']."'";
            //echo $sqlb."<p>";
            $profile_answers = run_query ( $sqlb, 'Pulling Client Profile report answers' );
            
            $number_of_answers = num_rows ( $profile_answers );
            for ( $z = 0; $z < $number_of_answers; $z++ ) {
            
            $report_answer = fetch_array ( $profile_answers, 'Pulling the actual answer', $z );
            
            $question_number =  $report_answer['client_rpt_question_id'];   
            $question_type = $report_questions->questions[$question_number]['question_type'];
            //echo "Question type is: ".$question_type."<br/>";
            
            //Need to pull out the report type, then pull out the question types for use with checkboxes.
                if ( $question_type == 'checkboxes' )
				{
				    foreach ( $report_questions->question_elements[$question_number] AS $element_key => $element )
					{
						//echo "Element key: ".$element_key." element: ".$element["question_element_value"]." <br/>";
						if ( $report_answer['client_rpt_answer'] == $element['question_element_value'] )
						{
							//echo "This is it CHECKED: ".$element_key;
							$client_info_array[$question_number][$element_key] = $element['question_element_value'];
                            $report_answer[$question_number][$element_key] = $element['question_element_value'];
							break 1;
						}
					}
				}
                elseif  ( $question_type == 'number' )
				{
                    $client_info_array[$report_answer['client_rpt_question_id']] = $report_answer['client_rpt_answer_int'];
                }
                else
				{
                    $client_info_array[$report_answer['client_rpt_question_id']] = $report_answer['client_rpt_answer'];
                }
            }
        }
        
        //May be anon
        if ($org_gen_ids) {
            //Make a string containing a list of all the used id, by type (i.e., Richard, Dick, Dicky)
            foreach ( $org_gen_ids AS $id_type => $duplicated_id_vals )
			{
                //echo "In org_gen_is loop<p>";
                $id_array_holder = array_unique ( $duplicated_id_vals );
                
                $seperator = '';
                foreach ( $id_array_holder AS $unique_id_val )
				{
                    $client_info_array[$id_type] .= $seperator.$unique_id_val;
                    $seperator = ', ';
                }
            }
        }
		
        
        /*	
		//Find any org_generated client ids		
		$org_generated_client_id_raw = $this->client_org_generated_id_find ( $client_id );
        
		if ( $org_generated_client_id_raw != '0' )	{
			$client_info_array['org_generated_client_id'] = $org_generated_client_id_raw;
		}
        */

		//Pull the client identifier
		////$sql_c = "SELECT * FROM clients WHERE client_id = '".$client_id."'";
        //echo "<br/>CLIENT identifier sql = ".$sql_c."<br/>";
		////$result_c = run_query ( $sql_c, 'Pulling Client IdentifierZ' );
		////$clients_c = fetch_array ( $result_c, 'Client identifier', '0' );
		////$client_info_array['client_identifier'] = $clients_c["client_identifier"];
        
        //foreach ($client_info_array AS $keey => $current_value)  {echo "Key ".$keey ." => ".$current_value."<br/>";}
        $client_info_array['client_id'] = $client_id;
        
        //var_dump ($client_info_array);
             
        return $client_info_array;
	}


/********************************************************************************************
 * Name: display_client_profile_table: 
 * Description: Display client profile table (The View), building and displaying links and
 * hoh relationship ui if required.
 * 
 * Details and Notes: 
 * 
 * @param: $my_client_info - array of clients' data
 * @param: $table_title - Title of table
 * @param: $table_type
 * @param: $edit_form_id, $rep_type_id, and $form_status are simply values needed to be passed along in posts...  Hack!  Fixme!  Todo!
 * @param: $rep_type_id
 * @param: $form_status
 * @return: html of The View
 * 
 * History: Updated 1/17/03 by Jeff.
 ********************************************************************************************/
	function display_client_profile_table ( $my_client_info, $table_title = '', $table_type='', $edit_form_id='', $rep_type_id='', $form_status='', $show_sysid='' )
	{
		GLOBAL $client_info, $unix_date, $head_dynamic_style, $this_page;
		GLOBAL $rel_changed;
        
        //I think that sys id's should be displayed to super users only as this provides an important bit of info for narrowing down issues much faster.  ~jeff
        if ($_SESSION["super_user_idB"])
        {
           $show_sysid = 'yes';
        }
        
		//Convert array to scaler first, only going to pull up clients based on one form id
		//todo: hack, need to once and for all figure out how or if we are going to 
		//display multiple forms at once, this is another case were things are considerably complicated...
		if (is_array($edit_form_id))
		{
			$edit_form_id = array_values($edit_form_id);
			$edit_form_id = $edit_form_id[0];
		}
		if (is_array($rep_type_id))
		{
			$rep_type_id = array_values($rep_type_id);
			$rep_type_id = $rep_type_id[0];
		}
		
		//echo "<br>display_client_profile_table (".count($my_client_info).", $table_title, $table_type, $edit_form_id, $rep_type_id, $form_status) ";
		//this is only true if client_income_form
		$table_config['show_total_hh_income']=false;
		//define profile table based on $table_type and $form_type
		switch ($table_type)
		{
			case 'client_profile_edit':
			   $table_config['view_unit'] = 'client'; $table_config['show_addtoview_links']=false; $table_config['show_removefromview_links']=true; $table_config['show_hoh']=false; $table_config['show_edit_hoh']=false;
			   break;
			case 'client_forms':  //fall through to next
			   $table_config['view_unit'] = 'client'; $table_config['show_addtoview_links']=false; $table_config['show_removefromview_links']=false; $table_config['show_hoh']=false; $table_config['show_edit_hoh']=false;
			   break;
			case 'clients':
			   $table_config['view_unit'] = 'client'; $table_config['show_addtoview_links']=false; $table_config['show_removefromview_links']=true; $table_config['show_hoh']=false; $table_config['show_edit_hoh']=false;
			   break;
			case 'client_income_forms':
			   $table_config['view_unit'] = 'client'; $table_config['show_addtoview_links']=false; $table_config['show_removefromview_links']=true; $table_config['show_hoh']=false; $table_config['show_edit_hoh']=false;
			   $table_config['show_total_hh_income']=true;
			   break;
			case 'clients_related':
			   $table_config['view_unit'] = 'client'; $table_config['show_addtoview_links']=true; $table_config['show_removefromview_links']=false; $table_config['show_hoh']=true; $table_config['show_edit_hoh']=false;
			   break;
			case 'client_overview':
			   $table_config['view_unit'] = 'client'; $table_config['show_addtoview_links']=false; $table_config['show_removefromview_links']=true; $table_config['show_hoh']=true; $table_config['show_edit_hoh']=false;
			   break;
			case 'client_add':
			   $table_config['view_unit'] = 'client'; $table_config['show_addtoview_links']=false; $table_config['show_removefromview_links']=false; $table_config['show_hoh']=true; $table_config['show_edit_hoh']=false;
			   break;
			case 'households':
			   $table_config['view_unit'] = 'household'; $table_config['show_addtoview_links']=false; $table_config['show_removefromview_links']=true; $table_config['show_hoh']=true;
			   if ($edit_form_id)
			   		$table_config['show_edit_hoh']=false;
			   else
			   		$table_config['show_edit_hoh']=true;
			   break;
			case 'household_forms':
			   $table_config['view_unit'] = 'household'; $table_config['show_addtoview_links']=false; $table_config['show_removefromview_links']=false; $table_config['show_hoh']=true;
			   if ($edit_form_id)
			   		$table_config['show_edit_hoh']=true;
			   else
			   		$table_config['show_edit_hoh']=false;
			   break;
			case 'queried_clients': //fall through to next
			default:
			   $table_config['view_unit'] = 'client'; $table_config['show_addtoview_links']=false; $table_config['show_removefromview_links']=false; $table_config['show_hoh']=true; $table_config['show_edit_hoh']=false;
			   break;
		}
		
        $final_html .= "<table class=\"generictable\"><tr><td class=\"generictabletop\">".$table_title."</td></tr></table>";
        
        //Check if a client is associated first, otherwise we get ForEach errors
        if ( $my_client_info )
		{
            $final_html .= "<table class=\"generictable\">";
			
            //Start the form used to edit relationships
            if ( $table_config['show_edit_hoh'] ) //$table_type == 'client_profile_edit' )
			{
                $final_html .=  "\n<form id=\"rel\" method=\"post\" ";
		        $final_html .=  "action=\"".$this_page."\">";
	            $final_html .=  "<input type=\"hidden\" name=\"form_submitted\" value=\"relationship_change\">\n";
            }
			
			$final_html .= $this->display_client_profile_table_column_headers($table_config, $show_sysid);
            
            foreach ( $my_client_info AS $key => $current_client )
			{
                //echo "Profile is: ".$key. "=> ".$current_client."<br/>";
				$final_html .= $this->display_client_profile( $key, $current_client, $table_config, $rep_type_id, $edit_form_id, $my_client_info, $show_sysid);
            }
			
            //Close out the form used to edit relationships
            if ( $table_config['show_edit_hoh'] ) //$table_type == 'client_profile_edit' )
			{
                $final_html .= '</form>'; 
            }
			
			$final_html .= '</table>';
		    
			//display Change Household Relationship button if editable and $form_status not set, i.e. viewing existing form
		    if ($table_config['show_edit_hoh'] && !$form_status)
		    {
			    $final_html .=  "\n<table width=100%><tr><td align=right>";
				$final_html .=  '<form id="finalizerel" method="post" ';
		        $final_html .=  'action="'.$this_page.'">';
	            $final_html .=  '<input type="hidden" name="form_submitted" value="finalize_relationship_change">';
				$final_html .=  '<input type="hidden" name="report_type_id" value="'.$rep_type_id.'">';
				$final_html .=  '<input type="hidden" name="edit_report_id" value="'.$edit_form_id.'">';
				$final_html .=  '<input type="hidden" name="report_unit" value="household">';
				$final_html .=  '<input '.build_tabindex_html(102).' type="submit" value="Submit Household Change">';
				$final_html .=  '</form></td></tr></table>';
		    }
        
        }
        else //No clients to display
		{
            $final_html .= "<table class=\"generictable\"><tr><td class=\"smalltd\">None</td></tr></table>";
        }
		
		return $final_html;
	}




	function display_client_profile_table_column_headers( $table_config, $show_sysid)
	{
        $final_html = '<tr>';
		//$final_html .= '<td></td>';
		if ($show_sysid)
        	$final_html .= "<td class=\"genericsubtop\">Sys. ID#</td>";
        $final_html .= "<td class=\"genericsubtop\">Name</td>";
        $final_html .= "<td class=\"genericsubtop\">Gender</td>";
        $final_html .= "<td class=\"genericsubtop\">Birthday</td>";
        $final_html .= "<td class=\"genericsubtop\">Race</td>";
        $final_html .= "<td class=\"genericsubtop\">Status</td>";
        $final_html .= "<td class=\"genericsubtop\">Org.Specific ID</td>";
        $final_html .= "<td class=\"genericsubtop\">Social Sec. #</td>";
		if ( $table_config['show_total_hh_income'] )
		{
			$final_html .= "<td class=\"genericsubtop\">Total HH Income</td>";
		}
        //Only show if there is an relationship
        if ( $table_config['show_hoh'] || $table_config['show_edit_hoh'] )
		{
            $final_html .= "<td class=\"genericsubtop\">Relationship to HOH</td>";
        }
        //$final_html .= "<td class=\"genericsubtop\">Link to Profile</td>";
        if ( $table_config['show_removefromview_links'] )
		{
            $final_html .= "<td class=\"genericsubtop\">Remove from View</td>";
        }
        if ( $table_config['show_addtoview_links'] )
		{
            $final_html .= "<td class=\"genericsubtop\">Add client to View</td>";
        }
        $final_html .= '</tr>';	
		return $final_html;
	}



	function display_client_profile( $key, $current_client, $table_config, $rep_type_id, $edit_form_id, $my_client_info, $show_sysid)
	{
	   GLOBAL $this_page;
       
       
	 // echo  var_dump( $current_client );
        $profile_client_id = $current_client['client_id'];
        $profile_name_last = stripslashes( get_friendly_text( $current_client['name_last'] ) );
        $profile_name_first = stripslashes( get_friendly_text( $current_client['name_first'] ) );
        $profile_gender = ucwords( str_replace( '_', ' ', stripslashes( get_friendly_text( $current_client['client_gender'] ) ) ) );
        
        if ($current_client['ss_number'])
        {
            $profile_ss_number = stripslashes(get_friendly_text($current_client['ss_number']));
        }
        else
        {
            $profile_ss_number = '???-??-????';
        }
        
        if ($current_client['birth_month'])
        {
            $profile_birthday = stripslashes(get_friendly_text($current_client['birth_month']));
        }
        else
        {
            $profile_birthday = '??';
        }
        if ($current_client['birth_day'])
        {
            $profile_birthday .= '/'.stripslashes(get_friendly_text($current_client['birth_day']));
        }
        else
        {
            $profile_birthday .= '/??';
        }
        if ($current_client['client_year_born'])
        {
            $profile_birthday .= '/'.stripslashes(get_friendly_text($current_client['client_year_born']));
        }
        else
        {
            $profile_birthday .= '/????';
        }
        
        if ( is_array($current_client['102']) )
        {
            $ww = 0;
            foreach ( $current_client['102'] AS $one_ethnicity )
            {
                 if ( $ww > 0 ) { $ethnicity_output .= '-'; }
                      $ww++;
                      $minus_underscore = str_replace ( '_', ' ', $one_ethnicity );
                      $minus_underscore = ucwords ( $minus_underscore );
                      $profile_ethnicity .= str_replace ( ' ', '-', $minus_underscore );
            }
        }
        $profile_ethnicity = stripslashes( get_friendly_text( $profile_ethnicity ) );
        $profile_status = get_friendly_client_status( $current_client['98'] );
        $profile_org_id = $current_client['org_generated_client_id'];
        
        $final_html = '<tr>';
        
		if ($show_sysid)
        {
	        $final_html .= '<td class="smalltd">'.$profile_client_id.'</td>';
        }
        $final_html .= '<td class="smalltd">
		                <a class="smaller" href="'. $system_directory.'client_overview.php?display_client_overview='.$profile_client_id.'">
						<b>'.$profile_name_last.', '.$profile_name_first.'</b></a>
						</td>';
        $final_html .= "<td class=\"smalltd\">".$profile_gender.'</td>';
        $final_html .= "<td class=\"smalltd\">".$profile_birthday.'</td>';
        $final_html .= "<td class=\"smalltd\">".$profile_ethnicity.'</td>';
        $final_html .= "<td class=\"smalltd\">".$profile_status.'</td>';
        $final_html .= "<td class=\"smalltd\">".$profile_org_id.'</td>';
        $final_html .= "<td class=\"smalltd\">".$profile_ss_number.'</td>';
        
		if ( $table_config['show_total_hh_income'] )
		{
			include_once($include_root."household_income_class.inc");
			$hi = new Household_income ( $profile_client_id );
			if ($hi->total_household_income)
				$hi_to_display = "$$hi->total_household_income";
			else
				$hi_to_display = "unreported";
			$final_html .= "<td class=\"smalltd\">".$hi_to_display.'</td>';
		}
	    
        if ( $table_config['show_edit_hoh'] ) 
        {
                 //$final_html .= "<td class=\"smalltd\">".ucfirst ( $current_client['client_relationship_to_lead'] ).'</td>';
			     $final_html .= "<td class=\"smalltd\">";
				 //The lead client in view's relationship cannot be edited unless is a household of one.  
				 //Rule does not apply if editing an existing form however todo, add rule that one person has to be hoh, can't change all to child...
				 //actually, this might be a rule to apply in general?????
				 if ($key==0 && count($my_client_info)>1 && !$edit_form_id)
				 	$final_html .= ucfirst ( $current_client['client_relationship_to_lead'] );
				 else
                 	$final_html .= $this->build_relationship_edit_question ( $current_client );
			     $final_html .= '</td>';
		         //this latest hack is to simply allow hoh edits on form edit page... Todo: need to fix all this spagehti code
		         $final_html .=  "<input type=\"hidden\" name=\"report_type_id\" value=\"".$rep_type_id."\">\n";
		         $final_html .=  "<input type=\"hidden\" name=\"edit_report_id\" value=\"".$edit_form_id."\">\n";
		         $final_html .=  "<input type=\"hidden\" name=\"report_unit\" value=\"household\">\n";
       }
       elseif ( $table_config['show_hoh'] )
	   {
		         $final_html .= "<td class=\"smalltd\">";
                 $final_html .= ucfirst ( $current_client['client_relationship_to_lead'] );
			     $final_html .= "</td>";
       }
       
	   if (strstr( '?', $this_page))
		   $page_url_for_extend = $this_page.'&';
	   else
		   $page_url_for_extend = $this_page.'?';
	   
	   if ($table_config['show_removefromview_links'])
	   {
		    if ($table_config['view_unit'] == 'household' && $my_client_info[0]['client_id']==$current_client['client_id'])
		      $remove_link = 'REMOVE household from View';
		    else
		      $remove_link = 'REMOVE client from View';
		    
		    //if show_view_unit is not client (i.e. household) and its not the lead client in view or is an unknown relation than enabled remove from view, otherwise no link!
            if ( $table_config['view_unit']=='client' || $my_client_info[0]['client_id']==$current_client['client_id'] || ($current_client['client_relationship_to_lead']==null || $current_client['client_relationship_to_lead']=='unknown') )
		    {
                $final_html .= "<td class=\"smalltd\"><a class=\"smaller\"
                    href=\"".$system_directory.$page_url_for_extend.'remove_client_from_household_session='.$current_client['client_id']."\">".$remove_link."</a></td>";
            }
		    else
		    {
			    $final_html .= "<td class=\"smalltd\">&nbsp;</td>";
		    }
	   }
       
       if ( $table_config['show_addtoview_links'] )
	   {
            $final_html .= "<td class=\"smalltd\"><a class=\"smaller\"
                 href=\"".$system_directory.$page_url_for_extend."add_client_to_household_session=".$current_client['client_id']."\">ADD client
                        to View</a></td>";
       }
       
       $final_html .= '</tr>';
       log_report_activity ( $_SESSION['user_idB'], 'clnt_prof', $current_client['client_id'], 'display_clnt_profile' );
	   return $final_html;
	}




    function enforce_h_view_rules($edit_form_id='')
	{
		GLOBAL $client_info;
		//echo "<br>enforce_h_view_rules($edit_form_id)<br>";
		
		if (is_array($edit_form_id))
		{
			$edit_form_id = array_values($edit_form_id);
			$edit_form_id = $edit_form_id[0];
		}
		
        //add related clients to the view
        $rel = new Relationships ( $client_info[0]['client_id'], $edit_form_id, 'yes_get_latest_rel' );
        
        $new_client_info = array();
        $ids_in_view = array();
        //array_push($ids_in_view, $client_info[0]['client_id']);
        //first push on all clients currently in view
        if (!is_array($client_info))
        return null;
        
        foreach( $client_info AS $key => $current_client)
        {
            //should we double check this or leave unknowns?
            //if ($current_client['client_relationship_to_lead'] != 'unknown' && $current_client['client_relationship_to_lead'] != null)
            array_push($new_client_info, $current_client);
            array_push($ids_in_view, $current_client['client_id']);
        }
            	
        //$tag_values['{RELATIONSHIPS}'] = $rel->display_other_related_clients_table();
        //echo '<hr color=red>'.pretty_var_dump($ids_in_view);
        if (is_array($rel->related_clients_profile_array))
        {
            foreach( $rel->related_clients_profile_array AS $key => $related_client)
            {
                //if related client isn't already in new view add...'
                //echo '<br> Is '.$related_client['client_id'].' in there? '.( !in_array ($current_client['client_id'],$ids_in_view) ).' ';
                if ( !in_array($related_client['client_id'],$ids_in_view) )
                {
                    array_push($new_client_info, $related_client);
                }
        /*else //In array so update relationship based on form pulled
        {    //Note: should only update with the first row containting id!
        	foreach($new_client_info as $k => $cli)
        	{
        		if (!$new_client_info[$k]['already_updated_hh'] || $cli['client_id']==$related_client['client_id'])
        		{
        			echo '<br> update rel to '.$related_client['client_relationship_to_lead'];
        			$new_client_info[$k]['client_relationship_to_lead'] = $related_client['client_relationship_to_lead'];
        			//$new_client_info[$k]['already_updated_hh'] = true;
        			break;
        		}
        	}
        }*/
            }
        }
        
        //echo '<br> leaving with '.pretty_var_dump($new_client_info[0]['client_relationship_to_lead']);
		return $new_client_info;
    }



	function put_client_profiles_associated_with_household_report_into_client_info_session_variable ($report_id)
	{
		GLOBAL $client_info;
		
		//Pull out the client ids associated with the report
		$sql = "SELECT report_relationship.client_id, client_relationship_to_lead FROM report_relationship WHERE
         hh_report_id = '".$report_id."' ORDER BY report_relationship.client_id";
		//$clients_result = run_query ($sql, "Finding clients related to form");
        //$client_count = num_rows($clients_result);
        
        $related_client_id_array = run_query_return_array ( $sql, 'Finding clients related to report' );
        $client_count = count ( $related_client_id_array );
        
        foreach ( $related_client_id_array AS $key => $cur_client )
		{
            //Note the lead id
            if ( $cur_client['client_relationship_to_lead'] == 'head of household' ) 
			{
                 $lead_client_key = $key;
                 //echo "Lead is: ".$cur_client["client_id"]."<p/>";
                 break;
            } 
        }
		//Switch the  lead intothe first position
        $temp_switch_holder = $related_client_id_array[0];
        $related_client_id_array[0] = $related_client_id_array[$lead_client_key];
        $related_client_id_array[$lead_client_key] = $temp_switch_holder;
                
        //array_search (4,$map,true);
        //array_splice ( array input, int offset [, int length [, array replacement]])
		
        //Erase the existing session info
		$client_info = "";
        $_SESSION['client_infoB'] = $client_info;
        
		//Assign the clients to the session variable
		for($x = 0; $x < $client_count; $x++)
		{
			//$related_client_id_array = fetch_array($clients_result, "Clients tied to form", $x);
			//$related_client_id = $related_client_id_array["report_relationship_client_id"];
            $related_client_id = $related_client_id_array[$x]['client_id'];
			$client_info[$x] = $this->pull_client_profile_array ($related_client_id);
			$client_info[$x]['client_relationship_to_lead'] = $related_client_id_array[$x]['client_relationship_to_lead'];
			$_SESSION['client_infoB'][$x] = $client_info[$x]; 
		}
		
	}



    function put_client_profile_associated_with_client_report_into_client_info_session_variable ($client_id)
	{
		GLOBAL $client_info;
        
        $client_info = '';
        $_SESSION['client_infoB'] = '';
		
		$client_info[0] = $this->pull_client_profile_array ($client_id);
		
        //Need to stop assuming/overwriting client_relationship_to_lead.  If child is the lead relationship should be 'child' even if no other clients are in the view.
	    if ( $client_info[0]['client_id'] > 0 )
        {
		      $rel = new Relationships ( $client_info[0]['client_id'] );
              $relationship = $rel->find_relationship_to_lead ( $client_info[0]['client_id'], $client_info[0]['client_id'] );
              $client_info[0]['client_relationship_to_lead'] = $relationship;
        }
        else //No one in repomdent role, so make the new person the head of household.  This case should never happen since relating client to themselves to get true relationship to hoh designation.
        {
              $client_info[$i]['client_relationship_to_lead'] = 'head of household';
        }
		
		$_SESSION['client_infoB'][0] = $client_info[0];
	}



    function add_client_to_household_session ( $client_id ) 
    {
        GLOBAL $client_info, $message, $message_type;
        
        // Search through the existing clients to make sure not already added
		if (is_array($client_info)){
          foreach ( $client_info AS $cur_cli )
          {
            if ( $cur_cli['client_id'] == $client_id )  
            {
                $client_already_loaded_in_session = 1;
                $message .= 'Client already in view. ';
                $message_type = 'error';
                break;
            }
          }
		}
        
        if ( $client_already_loaded_in_session != 1 )
        {
            $cli_array = $this->pull_client_profile_array ( $client_id );
			
			// Note: the first index [0] is always reserved for the lead_client and 
			// if this client is removed, the next in the list is moved to this position.
            if ( $client_info[0]['client_id'] > 0 )
            {
				$rel = new Relationships ( $client_id );
				
                $relationship = $rel->find_relationship_to_lead ( $client_info[0]['client_id'], $client_id, 'yes_get_latest_relationship' );
				
                $cli_array['client_relationship_to_lead'] = $relationship;
            }
            // No one in respondent role, so make the new person the head of household
            else
			{
				//echo ' No one in respondent role, so make the new person the head of household ';
				// this may seem like a hack but it works and is better then making a 'child' into a 'head of household'
				$rel = new Relationships ( $client_id );
                $relationship = $rel->find_relationship_to_lead ( $client_id, $client_id );
				if ($relationship)
				{
                	$cli_array['client_relationship_to_lead'] = $relationship;
				}
				else
				{
					// no report filed relating this client to others so assume hoh.
					$cli_array['client_relationship_to_lead'] = 'head of household';
				}
            }
			
		//echo '<hr color=blue>relationship to lead:'.$relationship;echo "rel->find_relationship_to_lead (".$client_info[0]['client_id'].", $client_id) = ";
		//echo pretty_var_dump ($rel->related_clients_profile_array);
			
            //echo "<hr color=green>Add Client ".$client_id." to household session...";
            //echo "<br>BEFORE lead_client_in_view is ".$lead_client_in_view." client_info:".pretty_var_dump($client_info);
			
			if (!is_array($client_info))
			{
			        // If first client to be added to view then the $client_info var is not set, set it.
                    settype ( $client_info, 'array' );
					$client_info[0] = $cli_array;
			}
			else
			{
			        array_push ( $client_info, $cli_array );
			}
            $_SESSION['client_infoB'] = $client_info;
        }
		//echo "<br>AFTER client_info:".pretty_var_dump($client_info).'<hr color=blue>';
		//echo "<hr color=green>";
    }




	//Todo: the below code I added could be made more efficient and logical... ~jeff
	function remove_client_from_household_session ( $client_id, $remove_all_in_household='' )
	{
	    GLOBAL $client_info;
		$reset_lead = false;
		$client_info_updated = false;
	    
		if ($remove_all_in_household)
		{
			//echo '<br>Remove all in HH';
			for ($i=0;$i<count($client_info);$i++)
		    {
			    if ($client_info[$i]['client_id']==$client_id && ($client_info[$i]['client_relationship_to_lead'] == null || $client_info[$i]['client_relationship_to_lead'] == 'unknown') )
				{
					$remove_all_in_household = FALSE; //only removing the one so unset flag...
					//echo '<br>nevermind that... ';
				}
		    }
		}
		
		if (is_array($client_info))
		{
	      foreach ( $client_info AS $key => $cli_array )
		  {
	        if ( $cli_array['client_id'] ==  $client_id || 
			     ($remove_all_in_household && $cli_array['client_relationship_to_lead']!=null && $cli_array['client_relationship_to_lead']!='unknown')  )
			{
	            unset ( $client_info[$key] );
	            $client_info_updated = true;
				
				//if 'lead' client in view is removed need to reset lead
				if ($key==0)
				{
					$reset_lead=true;
				}
				if (!$remove_all_in_household)
					break;
			}
		  }
		}
		//echo '<hr color=blue>before reset lead:<br>';
		/*for ($i=0;$i<count($client_info);$i++)
		{
			echo $i.')'.$client_info[$i]['client_relationship_to_lead'].'<br>';
		}*/
		
		/*if ($reset_lead)
		{
			//refresh-restack client_info so index is in order 0-X for remaining clients in view,
			//...then refresh relationship for client with index 0 and any relations
			echo '<br>Reset Lead';
			$i=0;
			$new_client_info = null;
		    foreach ( $client_info AS $key => $cli_array )
			{
				$new_client_info[$i] = $cli_array;
				$i++;
			}
			$client_info = $new_client_info;
			
			// Now update alllll of the client relationships to this new lead along with the lead relationship, if needed.
			if (is_array($client_info))
			{
			  foreach ( $client_info AS $key => $cli_array )
			  {
				// Need to re-establish new relationships to new lead for all clients in view
				// Note: if key==0 then query returns back correct relation to the hoh who is not listed in view.
				$rel = new Relationships ( $client_info[$key]['client_id'] );
               	$relationship = $rel->find_relationship_to_lead ( $client_info[0]['client_id'],
																   $client_info[$key]['client_id'] );
               	$client_info[$key]['client_relationship_to_lead'] = $relationship;
				// Now if relationship is not null set lead relationship
				if ($client_info[$key]['client_relationship_to_lead']==null && $relationship)
				{
					$relationship = $rel->find_relationship_to_lead ( $client_info[$key]['client_id'],
																       $client_info[0]['client_id']   );
               	    $client_info[0]['client_relationship_to_lead'] = $relationship;
				}
			  }
			}
		}*/
		
		//echo '<hr color=blue>after reset lead:<br>';
		/*for ($i=0;$i<count($client_info);$i++)
		{
			echo $i.')'.$client_info[$i]['client_relationship_to_lead'].'<br>';
		}*/
		
		if ($client_info_updated)
		{
			$_SESSION['client_infoB'] = $client_info;
	    }
		
		//echo "<br>AFTER--client_in_lead is key 0 id ".$client_info[0]['client_id']." & client_info:".pretty_var_dump($client_info)."<hr color=red>";
	}



    function edit_client_relationship_session ( $form_answer_rel )
	{
        GLOBAL $client_info, $message, $message_type;
        //echo " edit_client_relationship_session() ";
        //Loop through the relationship changes submitted
        foreach ( $form_answer_rel AS $cli_id => $new_relationship ) 
		{
            //echo '<br>new relationship is: '.$new_relationship.'<p>';
            //Validate the relationship type
            switch ( $new_relationship )
			{
                case 'unknown':
                    $ok = 1;
                    break;
                case 'head of household':
                    $ok = 1;
                    break;
                case 'spouse':
                    $ok = 1;
                    break;
				case 'partner':
					$ok = 1;
					break;
                case 'child':
                    $ok = 1;
                    break;
                case 'friend':
                    $ok = 1;
                    break;
                case 'sibling':
                    $ok = 1;
                    break;
                case 'family, not immediate':
                    $ok = 1;
                    break;
                default:
                    $ok = -1;
            }
            
            if ( $ok == 1 )
			{
                $vetted_new_relationship = $new_relationship;
            }
            else
			{
				//echo '<br>Invalid relationship, IP logged.  ';
                $message .= 'Invalid relationship, IP logged. ';
                $message_type = 'error';
                $vetted_new_relationship = 'zz';
            }
            
            //Loop through client_info clients
            foreach ( $client_info AS $key => $cur_cli )
			{
                if ( $cur_cli['client_id'] == $cli_id )  
				{
                    //echo "a match<p>";
                    $client_info[$key]['client_relationship_to_lead'] = $vetted_new_relationship;
                    
                    //If the new person is a 'head of household', the '0' index person is not, put them at '0'
					//jeffgu: actually, the way things work now, a non hoh can and must be allowed in view so that hh relationship changes can take effect
                    /*if ( $key != 0 
                        && $vetted_new_relationship == 'head of household' 
                        && $client_info[0]['client_relationship_to_lead'] != 'head of household' )
					{
                        //Save the contents of the old index client
                        $holder = $client_info[0];
                        //Copy the contents of the new respomndent to 0
                        $client_info[0] = $client_info[$key];
                        //Put the old head of household in the new respondents place
                        $client_info[$key] = $holder;
                    }*/
                    break;
                }
            }
        }
        $_SESSION['client_infoB'] = $client_info;
    }




    function build_relationship_edit_question ( $cur_client_info )
	{
        $options = array ( 'unknown' => 'Unknown', 'head of household' => 'Head of Household', 'spouse' => 'Spouse', 'partner' => 'Partner', 'child' => 'Child', 
		                   'friend'  => 'Friend', 'sibling' => 'Sibling', 'family, not immediate' => 'Family, not immediate' );
        
        //$final_html .= "<td class=\"smalltd\">";
        $final_html .= "<select ".build_tabindex_html(101)." class=\"tinytd\" name=\"form_answer[rel][".$cur_client_info['client_id']."]\" ";
        $final_html .= " OnChange=\"document.getElementById('rel').submit()\">"; //relationship change is reflected on page but does not post to db until 'finalize' button click...
        foreach ( $options AS $val => $title )
		{
            $final_html .= "<option value=\"".$val."\"";
            if ( $cur_client_info['client_relationship_to_lead'] == $val )
			{
                $final_html .= " selected=\"selected\"";
            }
            $final_html .= ">".$title."</option>";
        }
        $final_html .= "</select>";
        //$final_html .= "</td>";
        
        return $final_html;
    
    }


/*    
    function client_org_generated_id_find ( $client_id )	{
		GLOBAL $org_id;

		$sql = "SELECT org_generated_client_id FROM org_generated_client_ids WHERE client_id = '".$client_id."' AND org_id = '".$org_id."'";
		$matching_client_result = run_query ( $sql, 'client_org_generated_id_find' );

        $count = num_rows ( $matching_client_result );

        //Loop through all the client ids available
        for ( $i=0; $i < $count; $i++ )   {
			if ( $i > 0 ) { $org_generated_client_id .= ';  '; }      
            $answer_array = fetch_array ( $matching_client_result, 'Pulling existing org generated client id', $i );
			$org_generated_client_id .= $answer_array['org_generated_client_id'];			
			//echo "Org generated client is: ".$org_generated_client_id."<br/>";
		}
		return $org_generated_client_id;			
	}
*/
}

/*
function assemble_client_id_string ($clnt_num, $clnt_info)  {
    GLOBAL $unix_date;
    //echo "client info is:<br>";
    //display_value($clnt_info);
    //echo $clnt_info[$clnt_num]["100"];

	if($clnt_info[$clnt_num]['client_id'])	{
		$final_html .= "<td class=\"tinytd\">Name: ".stripslashes(get_friendly_text($clnt_info[$clnt_num]['name_first'])).' '.stripslashes(get_friendly_text($clnt_info[$clnt_num]['name_last'])).'</td>';
	}

	if($clnt_info[$clnt_num]['initial_first'])	{
		$initials = $clnt_info[$clnt_num]['initial_first'].".".$clnt_info[$clnt_num]['initial_last'];
		$initials = str_replace('#', '?', $initials);
		$final_html .= "<td class=\"tinytd\">Initials: ".$initials."</td>";
	}

	$final_html .= "<td class=\"tinytd\">Gender: ". stripslashes(get_friendly_text(ucwords(str_replace( '_', ' ', $clnt_info[$clnt_num]['101']))))."</td>";
	if ( $clnt_info[$clnt_num]['client_relationship_to_lead'] )	{
		$final_html .= "<td class=\"tinytd\">Relationship to HOH: ".
        ucfirst ($clnt_info[$clnt_num]['client_relationship_to_lead'])."</td>";
	}
	$age = safe_date( 'Y', $unix_date) - $clnt_info[$clnt_num]['100'];
	$begin_age = $age -1;
    $final_html .= "<td class=\"tinytd\">Age: ".$begin_age.'-'.$age.'</td>';

    if  (is_array ( $clnt_info[$clnt_num]['102'] ) )	{
		foreach ( $clnt_info[$clnt_num]['102'] AS $one_ethnicity )   {
        	if($ww > 0) {$ethnicity_output .= '-';}
        	$ww++;
        	$minus_underscore = str_replace ( '_', ' ', $one_ethnicity );
        	$minus_underscore = ucwords ( $minus_underscore );
        	$ethnicity_output .= str_replace ( ' ', '-', $minus_underscore );
    	}
	}

	$final_html .= "<td class=\"tinytd\">Race: ".stripslashes(get_friendly_text($ethnicity_output)).'</td>';

	if ( $clnt_info[$clnt_num]['client_id'] != 0 )	{
		$final_html .= "<td class=\"tinytd\"><a class=\"smaller75\"
         href=\"".$system_directory."client_overview.php?display_client_overview=".$clnt_info[$clnt_num]["client_id"]."\">Link to Client
          Overview</a></td>";
    }

    return $final_html;
    

}
*/

//todo: consolidate.  combine this code with display profile code
function assemble_client_id_string ( $clnt_num, $client_info, $unit = 'client' )
{
		GLOBAL $unix_date;

        //Check if a client is associated first, otherwise we get ForEach errors
        if ( $client_info[$clnt_num] )
		{
            $final_html .= "<table class=\"generictable\">";
            $final_html .= '<tr>';
            $final_html .= "<td class=\"genericsubtop\">Last name</td>";
            $final_html .= "<td class=\"genericsubtop\">First name</td>";
            $final_html .= "<td class=\"genericsubtop\">Gender</td>";
            $final_html .= "<td class=\"genericsubtop\">Age</td>";
            //$final_html .= "<td class=\"genericsubtop\">Race</td>";
			$final_html .= "<td class=\"genericsubtop\">Status</td>";
            $final_html .= "<td class=\"genericsubtop\">Org.Specific ID</td>";
			if ($unit=='household')
	            $final_html .= "<td class=\"genericsubtop\">Relationship to HOH</td>";
            //$final_html .= "<td class=\"genericsubtop\">Link to Profile</td>";
            $final_html .= '</tr>';        
            
            //foreach ( $client_info AS $key => $current_client )	{
                //echo "Profile is: ".$key. "=> ".$current_client."<br/>";
                $final_html .= '<tr>';
                //$final_html .= "<td class=\"smalltd\">".stripslashes(get_friendly_text($client_info[$clnt_num]['name_last'])).'</td>';
				$final_html .= "<td class=\"smalltd\"><a class=\"smaller\" href=\"".$system_directory."client_overview.php?display_client_overview=".$client_info[$clnt_num]['client_id']."\">";
				$final_html .= stripslashes(get_friendly_text($client_info[$clnt_num]['name_last']))."</a></td>";
                $final_html .= "<td class=\"smalltd\">".stripslashes(get_friendly_text($client_info[$clnt_num]['name_first'])).'</td>';
                
                $final_html .= "<td class=\"smalltd\">".ucwords(str_replace( '_', ' ', stripslashes(get_friendly_text($client_info[$clnt_num]['client_gender'])) )).'</td>';
                
                $age = calculate_age_from_birthday( $client_info[$clnt_num]['birth_month'], $client_info[$clnt_num]['birth_day'], $client_info[$clnt_num]['client_year_born'] );
                $final_html .= "<td class=\"smalltd\">".$age.'</td>';
                
                if ( is_array($client_info[$clnt_num]['102']) )
				{
                    $ww = 0;
                    foreach ( $client_info[$clnt_num]['102'] AS $one_ethnicity )
					{
                        if ( $ww > 0 ) { $ethnicity_output .= '-'; }
                        $ww++;
                        $minus_underscore = str_replace ( '_', ' ', $one_ethnicity );
                        $minus_underscore = ucwords ( $minus_underscore );
                        $ethnicity_output .= str_replace ( ' ', '-', $minus_underscore );
                    }
                
                }
        //Race broken
                //$final_html .= "<td class=\"smalltd\">".stripslashes(get_friendly_text($ethnicity_output)).'</td>';
                unset($ethnicity_output);
				$final_html .= "<td class=\"smalltd\">".get_friendly_client_status($client_info[$clnt_num]['98']).'</td>'; //status
                $final_html .= "<td class=\"smalltd\">".$client_info[$clnt_num]['org_generated_client_id'].'</td>';
               
				if ($unit=='household')
				{
				    $final_html .= "<td class=\"smalltd\">";
                	$final_html .= ucfirst ( $client_info[$clnt_num]['client_relationship_to_lead'] );
                    $final_html .= '</td>';
				}
                //$final_html .= "<td class=\"smalltd\"><a class=\"smaller\" href=\"".$system_directory."client_overview.php?display_client_overview=".$client_info[$clnt_num]['client_id']."\">Link to Client Overview</a></td>";
                $final_html .= '</tr>';
            //}
            
            $final_html .= '</table>';
		
        }
        else {
            $final_html .= "<table class=\"generictable\"><tr><td class=\"smalltd\">None</td></tr></table>";
        }
		
		return $final_html;
	}


function calculate_age_from_birthday ( $birth_month, $birth_day, $birth_year )
{
    GLOBAL $unix_date;
    
    if (strstr($birth_year,'#'))
		return get_friendly_text($birth_year);
		
    $cur_month = safe_date( 'n', $unix_date );
    $cur_day = safe_date( 'j', $unix_date );
    $cur_year = safe_date( 'Y', $unix_date );
    $age = $cur_year - $birth_year; 
    
    if ( $cur_month <= $birth_month && $cur_day < $cur_day )
	{
        $age = $age - 1;
    }
    
    return $age;
}



/*function remove_client_from_household_session ( $client_id )  
{
    GLOBAL $client_info;
        //$_SESSION['client_infoB'] = null;
        //$client_info = null;
    foreach ( $client_info AS $key => $cli_array )  
    {
		//echo "key:".$key." ";
        if ( $cli_array['client_id'] ==  $client_id )   
        {
            unset ( $client_info[$key] );
            $_SESSION['client_infoB'] = $client_info;
            break;        
        }       
    }  
    echo "<hr>COUNT LEFT IN VIEW = ".count($client_info);

}*/

//replaces #99#, #98#, and #88# with user friendly text
function get_friendly_text ( $text )
{
	switch ($text) {
	case '#99#':
		return '&lt;Refused&gt;';
	case '#98#':
		return '&lt;Not Applicable&gt;';
	case '#88#':
		return '&lt;Don\'t Know&gt;';
	case '#77#':
		return '&lt;Don\'t Have&gt;';
	default:
		return $text;
	}
}

function get_friendly_client_status ( $org_client_status_id )
{
        switch ( $org_client_status_id )
        {
            case '1':
                $status = 'Status Not Set';
                break;
            case '2':
                $status = 'Active';
                break;
            case '3':
                $status = 'Inactive/Dormant';
                break;
            case '4':
                $status = 'Exited';
                break;
            case '5':
                $status = 'Followup Required';
                break;
            case '6':
                $status = 'Followup Required - 3 month';
                break;
            case '7':
                $status = 'Followup Required - 6 month';
                break;
            case '8':
                $status = 'Followup Required - 9 month';
                break;
            case '9':
                $status = 'Followup Required - 12 month';
                break;
            case '10':
                $status = 'Deceased';
                break;
            default:
                $status = 'Err: Status Unknown';
                break;
        }
		return $status;
}

?>
Return current item: Homeless Mangement Information System