Merge branch 'owenleonard/ht_sandbox' of git@github.com:apippin/tc into ht_sandbox
[eq/.git] / inc / class.tc.inc.php
1 <?php
2   /**************************************************************************\
3   * Application: phpGroupWare - 3rd Counselor                                *
4   * Framework: http://www.phpgroupware.org                                   *
5   * Author: Alan J. Pippin (apippin@pippins.net)                             *
6   * -----------------------------------------------                          *
7   *  This program is free software; you can redistribute it and/or modify it *
8   *  under the terms of the GNU General Public License as published by the   *
9   *  Free Software Foundation; either version 2 of the License, or (at your  *
10   *  option) any later version.                                              *
11   \**************************************************************************/
12       /* $Id: class.tc.inc.php,v 1.1.1.1 2005/07/20 07:40:32 ajp Exp $ */
13
14 class tc 
15 {
16         var $db;
17         var $db2;
18         var $db3;
19         var $t;
20         var $nextmatchs;
21         var $grants;
22         var $jscal;
23         var $cal_options;  
24         var $default_ht_num_months;
25         var $default_ppi_num_months;
26         var $default_ppi_num_years;
27         var $default_int_num_quarters;
28         var $default_int_num_years;
29         var $default_vis_num_years;
30         var $default_att_num_quarters;
31         var $max_num_districts;
32         var $current_year;
33         var $current_month;
34         var $upload_target_path;
35         var $script_path;
36         var $max_appointments;
37         var $max_presidency_members;
38         var $ppi_frequency_label;
39
40         var $public_functions = array
41         (
42                 'ht_view'    => True,
43                 'ht_update'  => True,
44                 'act_list'        => True,
45                 'act_view'   => True,
46                 'act_update' => True,
47                 'par_view'   => True,
48                 'ppi_view'   => True,
49                 'ppi_update' => True,
50                 'ppi_sched'  => True,
51                 'int_view'   => True,
52                 'int_update' => True,
53                 'int_sched'  => True,
54                 'vis_sched'  => True,
55                 'vis_view'   => True,
56                 'vis_update' => True,
57                 'att_view'   => True,
58                 'att_update' => True,
59                 'dir_view'   => True,
60                 'org_view'   => True,
61                 'schedule'   => True,
62                 'admin'      => True,
63                 'email'      => True,
64                 'email_appt' => True,
65                 'willing_view'   => True,
66                 'willing_update' => True,
67                 'send_ical_appt' => True,
68                 'assign_view'    => True,
69                 'assign_update'  => True,
70                 'get_time_selection_form' => True,
71                 'ht_sandbox' => True,
72         );
73  
74         function tc()
75         {
76                 if(file_exists("setup/tc_config.local")) {
77                         include("setup/tc_config.local");
78                 } else {
79                         include("setup/tc_config");
80                 }
81
82                 $this->script_path = "$this->application_path"."/bin";
83                 $this->max_presidency_members = 99;
84                 $this->max_appointments = 32768;
85
86                 $this->db               = $GLOBALS['phpgw']->db;
87                 $this->db2      = $this->db;
88                 $this->db3      = $this->db;
89                 $this->nextmatchs = CreateObject('phpgwapi.nextmatchs');
90                 $this->t          = $GLOBALS['phpgw']->template;
91                 $this->account    = $GLOBALS['phpgw_info']['user']['account_id'];
92                 $this->grants     = $GLOBALS['phpgw']->acl->get_grants('tc');
93                 $this->grants[$this->account] = PHPGW_ACL_READ + PHPGW_ACL_ADD + PHPGW_ACL_EDIT + PHPGW_ACL_DELETE;
94
95                 $this->jscal = CreateObject('tc.jscalendar');   // before phpgw_header() !!!
96                 $this->cal_options = 'daFormat    : "%Y-%m-%d",
97                                       ifFormat    : "%Y-%m-%d",
98                                       mondayFirst : false,
99                                       weekNumbers : false';
100
101                 $GLOBALS['phpgw_info']['flags']['app_header'] = 'The 3rd Counselor';
102                 $GLOBALS['phpgw']->common->phpgw_header();
103
104                 $this->current_day = `date '+%d'`;
105                 $this->current_day = $this->current_day-0; // Make it numeric
106                 $this->current_month = `date '+%m'`;
107                 $this->current_month = $this->current_month-0; // Make it numeric
108                 $this->current_year = `date '+%Y'`;
109                 $this->current_year = $this->current_year-0; // Make it numeric
110                 
111                 if ($this->ppi_frequency == 12) {
112                         $this->ppi_frequency_label = "Annual";
113                 } else if ($this->ppi_frequency == 6) {
114                         $this->ppi_frequency_label = "Semi-Annual";
115                 } else if ($this->ppi_frequency == 3) {
116                         $this->ppi_frequency_label = "Quarterly";
117                 } else if ($this->ppi_frequency == 1) {
118                         $this->ppi_frequency_label = "Monthly";
119                 } else {
120                         $this->ppi_frequency_label = "Periodic";
121                 }
122
123                 echo parse_navbar();
124                 $this->display_app_header();    
125         }
126         
127         function logToFile($func, $msg)
128         {
129                 // open file
130                 $fd = fopen($this->upload_target_path . "/tc_trace.log", "a");
131                 // append date/time to message
132                 $str = "[" . date("Y/m/d h:i:s", mktime()) . "] [" . $func . "] " . $msg;
133                 // write string
134                 fwrite($fd, $str . "\n");
135                 // close file
136                 fclose($fd);
137         }
138   
139         function save_sessiondata()
140         {
141         }
142
143         function display_app_header()
144         {
145                 $this->t->set_file(array('tc_header' => 'header.tpl'));
146
147                 if (isset($phpgw_info['user']['preferences']['tc']['tc_font']))
148                 {
149                         $font = $phpgw_info['user']['preferences']['tc']['tc_font'];
150                 }
151                 else
152                 {
153                         $font = 'Arial';
154                 }
155
156                 $this->t->set_var('bg_color',$phpgw_info['theme']['th_bg']);
157                 $this->t->set_var('font',$font);
158                 $link_data['menuaction'] = 'tc.tc.ht_view';
159                 $this->t->set_var('link_hometeaching',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
160                 $this->t->set_var('lang_hometeaching','HomeTeaching');
161                 $link_data['menuaction'] = 'tc.tc.act_list';
162                 $this->t->set_var('link_activity',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
163                 $this->t->set_var('lang_activity','Activities');
164                 $link_data['menuaction'] = 'tc.tc.willing_view';
165                 $this->t->set_var('link_willing',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
166                 $this->t->set_var('lang_willing','Willingness');
167                 $link_data['menuaction'] = 'tc.tc.assign_view';
168                 $this->t->set_var('link_assignment',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
169                 $this->t->set_var('lang_assignment','Assignments');
170                 $link_data['menuaction'] = 'tc.tc.par_view';
171                 $this->t->set_var('link_participation',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
172                 $this->t->set_var('lang_participation','Participation');
173                 $link_data['menuaction'] = 'tc.tc.ppi_view';
174                 $this->t->set_var('link_ppi',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
175                 $this->t->set_var('lang_ppi','PPIs');
176                 $link_data['menuaction'] = 'tc.tc.int_view';
177                 $this->t->set_var('link_int',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
178                 $this->t->set_var('lang_int','Interviews');
179                 $link_data['menuaction'] = 'tc.tc.vis_view';
180                 $this->t->set_var('link_visit',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
181                 $this->t->set_var('lang_visit','Visits');
182                 $link_data['menuaction'] = 'tc.tc.att_view';    
183                 $this->t->set_var('link_attendance',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
184                 $this->t->set_var('lang_attendance','Attendance');
185                 $link_data['menuaction'] = 'tc.tc.dir_view';    
186                 $this->t->set_var('link_dir',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
187                 $this->t->set_var('lang_dir','Directory');
188                 $link_data['menuaction'] = 'tc.tc.org_view';    
189                 $this->t->set_var('link_org',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
190                 $this->t->set_var('lang_org','Callings');
191                 $link_data['menuaction'] = 'tc.tc.admin';       
192                 $this->t->set_var('link_admin',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
193                 $this->t->set_var('lang_admin','Admin');
194                 $link_data['menuaction'] = 'tc.tc.schedule';    
195                 $this->t->set_var('link_schedule',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
196                 $this->t->set_var('lang_schedule','Scheduling');
197                 $link_data['menuaction'] = 'tc.tc.email';       
198                 $this->t->set_var('link_email',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
199                 $this->t->set_var('lang_email','Email');
200
201                 $this->t->pparse('out','tc_header');
202         }
203
204         function ht_view()
205         {
206                 $this->t->set_file(array('ht_view_t' => 'ht_view.tpl'));
207                 $this->t->set_block('ht_view_t','district_list','list');
208
209                 $this->t->set_var('linkurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ht_view'));
210                 $num_months = get_var('num_months',array('GET','POST'));
211                 if($num_months == '') { $num_months = $this->default_ht_num_months; }
212                 $this->t->set_var('num_months',$num_months);
213                 $this->t->set_var('lang_filter','Filter');
214                 if($num_months == 1) { $this->t->set_var('lang_num_months','Month of History'); }
215                 else {  $this->t->set_var('lang_num_months','Months of History'); }
216
217                 $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ht_view'));
218                 $this->t->set_var('title','Hometeaching'); 
219
220                 $this->t->set_var('ht_sandbox_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ht_sandbox'));
221                 $this->t->set_var('ht_sandbox_link_title','Hometeaching Sandbox'); 
222
223                 $sql = "SELECT * FROM tc_district AS td JOIN tc_individual AS ti WHERE td.supervisor=ti.individual AND td.valid=1 ORDER BY td.district ASC";
224                 $this->db->query($sql,__LINE__,__FILE__);
225                 $i=0;
226                 while ($this->db->next_record()) {
227                         $districts[$i]['district'] = $this->db->f('district');
228                         $districts[$i]['name'] = $this->db->f('name');
229                         $districts[$i]['supervisor'] = $this->db->f('supervisor');
230                         $i++;
231                 }
232
233                 $sql = "SELECT * FROM tc_individual where valid=1 ORDER BY individual ASC";
234                 $this->db->query($sql,__LINE__,__FILE__);
235                 $i=0;
236                 while ($this->db->next_record()) {
237                         $individual[$i] = $this->db->f('individual');
238                         $indiv_name[$i] = $this->db->f('name');
239                         $indiv_phone[$individual[$i]] = $this->db->f('phone');
240                         $i++;
241                 }
242                 array_multisort($indiv_name, $individual);
243
244                 // Make an array mapping individuals to indiv_names
245                 for($i=0; $i < count($individual); $i++) {
246                         $id = $individual[$i];
247                         $indivs[$id] = $indiv_name[$i];
248                 }      
249
250                 $this->nextmatchs->template_alternate_row_color(&$this->t);
251                 for($m=$num_months; $m >= 0; $m--) { $total_families[$m]=0; }
252                 for ($i=0; $i < count($districts); $i++) {
253                         $this->t->set_var('district_number',$districts[$i]['district']);
254                         $this->t->set_var('district_name',$districts[$i]['name']);      
255                         $supervisor = $districts[$i]['supervisor'];
256
257                         // Select all the unique companionship numbers for this district
258                         $sql = "SELECT distinct companionship FROM tc_companionship where valid=1 and district=". $districts[$i]['district'];
259                         $this->db->query($sql,__LINE__,__FILE__);
260                         $j=0; $unique_companionships = '';
261                         while ($this->db->next_record()) {
262                                 $unique_companionships[$j]['companionship'] = $this->db->f('companionship');
263                                 $j++;
264                         }
265
266                         $comp_width=450; $visit_width=25; $table_width=$comp_width + $num_months*$visit_width;
267                         $table_data=""; $num_companionships = 0;
268                         for($m=$num_months; $m >= 0; $m--) { 
269                                 $visits[$m]=0; 
270                                 $num_families[$m]=0; 
271                         }
272                         for ($j=0; $j < count($unique_companionships); $j++) {
273                                 $companion_table_entry = "";
274                                 // Select all the companions in each companionship
275                                 $sql = "SELECT * FROM tc_companion where valid=1 and ".
276                                 "companionship=". $unique_companionships[$j]['companionship'];
277                                 $this->db->query($sql,__LINE__,__FILE__);
278
279                                 while ($this->db->next_record()) {
280                                         // Get this companions information
281                                         if($companion_table_entry != "") { $companion_table_entry .= "<td>&nbsp;/&nbsp;</td>"; }
282                                         $companionship = $this->db->f('companionship');
283                                         $individual = $this->db->f('individual');
284                                         $name = $indivs[$individual];
285                                         $phone = $indiv_phone[$individual];
286                                         $companion_table_entry .= "<td title=\"$phone\"><b>$name</b></td>";
287                                 }
288                                 $table_data.= "<tr bgcolor=#d3dce3><td colspan=20><table><tr>$companion_table_entry</tr></table><hr></td></tr>";
289
290                                 // Get the names of the families assigned this home teaching companionship
291                                 $sql = "SELECT * FROM tc_family AS tf JOIN tc_individual AS ti WHERE tf.individual=ti.individual AND tf.valid=1 AND tf.companionship=".$unique_companionships[$j]['companionship'];
292                                 $sql = $sql . " ORDER BY name ASC";
293                                 $this->db->query($sql,__LINE__,__FILE__);
294                                 $k=0;
295                                 while ($this->db->next_record()) {
296                                         $family_name = $this->db->f('name');
297                                         $family_id = $this->db->f('family');
298                                         $this->nextmatchs->template_alternate_row_color(&$this->t);
299                                         $table_data.="<tr bgcolor=". $this->t->get_var('tr_color') ."><td>$family_name Family</td>";
300                                         // Find out how many times Visits were performed by this companionship
301                                         // in the past $num_months for this Family
302                                         $header_row="<th width=$comp_width><font size=-2>Families</th>";
303                                         for($m=$num_months; $m >= 0; $m--) {
304                                                 $month = $this->current_month - $m;
305                                                 $year = $this->current_year;
306                                                 if($month <= 0) { $remainder = $month; $month = 12 + $remainder; $year=$year-1; }
307                                                 if($month < 10) { $month = "0"."$month"; }
308                                                 $month_start = "$year"."-"."$month"."-"."01";
309                                                 $month_end = "$year"."-"."$month"."-"."31";
310                                                 $month = "$month"."/"."$year";
311
312                                                 //print "m: $m month: $month year: $year month_start: $month_start month_end: $month_end<br>";
313                                                 // Add this to the query to filter on only visits made by this companionship:
314                                                 // " AND companionship=" . $unique_companionships[$j]['companionship'].
315
316                                                 // First check to see if the currently assigned companionship has visited them
317                                                 $sql = "SELECT * FROM tc_visit WHERE date >= '$month_start' AND date <= '$month_end' ".
318                                                            " AND companionship=".$unique_companionships[$j]['companionship'].
319                                                            " AND family=". $family_id;
320                                                 $query_id = $this->db2->query($sql,__LINE__,__FILE__);
321                                                 if($this->db2->num_rows($query_id) == 0) {
322                                                         // We did not find any visits made by the currently assigned companionship,
323                                                         // look for visits made by any other companionship other than 0. (0 == Presidency Visit)
324                                                         $sql = "SELECT * FROM tc_visit WHERE date >= '$month_start' AND date <= '$month_end' ".
325                                                                    " AND companionship!=0".
326                                                                    " AND family=". $family_id;
327                                                         $query_id = $this->db2->query($sql,__LINE__,__FILE__);
328                                                 }
329                                                 $this->db2->query($sql,__LINE__,__FILE__);
330                                                 $link_data['menuaction'] = 'tc.tc.ht_update';
331                                                 $link_data['date'] = $month_start;
332                                                 $link_data['month_start'] = $month_start;
333                                                 $link_data['month_end'] = $month_end;
334                                                 $link_data['month'] = $month;
335                                                 $link_data['district'] = $districts[$i]['district'];
336                                                 $link_data['district_name'] = $districts[$i]['name'];
337                                                 $link_data['action'] = 'view';
338                                                 $link = $GLOBALS['phpgw']->link('/tc/index.php',$link_data);
339                                                 $header_row .= "<th width=$visit_width><font size=-2><a href=$link>$month</a></th>";
340                                                 if(!$total_visits[$m]) { $total_visits[$m] = 0; }
341                                                 if($this->db2->next_record()) {
342                                                         if($this->db2->f('visited') == 'y') {
343                                                                 $visits[$m]++; $total_visits[$m]++;
344                                                                 $num_families[$m]++; $total_families[$m]++;
345                                                                 $table_data .= '<td align=center><a href="'.$link.'"><img src="images/checkmark.gif"></a></td>';
346                                                         } else if($this->db2->f('visited') == 'n') {
347                                                                 $num_families[$m]++; $total_families[$m]++;
348                                                                 $table_data .= '<td align=center><a href="'.$link.'"><img src="images/x.gif"></a></td>';
349                                                         } else {
350                                                                 //$visits[$m]++; $total_visits[$m]++;
351                                                                 $table_data .= "<td>&nbsp;</td>";
352                                                         }
353                                                 } else {
354                                                         //$visits[$m]++; $total_visits[$m]++;
355                                                         $table_data .= "<td>&nbsp;</td>";
356                                                 }
357                                         }
358                                         $table_data .= "</tr>"; 
359                                         $k++;
360                                 }
361                                 $table_data .= "<tr><td colspan=20></td></tr>";
362                         }
363                         $table_data .= "<tr><td colspan=20><hr></td></tr>";
364                         $stat_data = "<tr><td><b><font size=-2>Families Hometaught:<br>Hometeaching Percentage:</font></b></td>";
365
366                         for($m=$num_months; $m >=0; $m--) {
367                                 if($num_families[$m] > 0) { 
368                                         $percent = ceil(($visits[$m] / $num_families[$m])*100);
369                                 } else {
370                                         $percent = 0;
371                                 }
372                                 $stat_data .= "<td align=center><font size=-2><b>$visits[$m] / $num_families[$m]<br>$percent%</font></b></td>";
373                         }
374                         $stat_data .= "</tr>";
375
376                         $this->t->set_var('table_width',$table_width);
377                         $this->t->set_var('header_row',$header_row);
378                         $this->t->set_var('table_data',$table_data);
379                         $this->t->set_var('stat_data',$stat_data);
380                         $this->t->fp('list','district_list',True);
381                 }
382
383                 $totals = "<tr><td><b><font size=-2>Total Families Hometaught:<br>Total Hometeaching Percentage:</font></b></td>";
384                 for($m=$num_months; $m >=0; $m--) {
385                         if($total_families[$m] > 0) { 
386                                 $percent = ceil(($total_visits[$m] / $total_families[$m])*100);
387                         } else {
388                                 $percent = 0;
389                         }
390                         $totals .= "<td align=center><font size=-2><b>$total_visits[$m] / $total_families[$m]<br>$percent%</font></b></td>";
391                 }
392                 $totals .= "</tr>";
393
394                 $this->t->set_var('totals',$totals);
395
396                 $this->t->pfp('out','ht_view_t');
397                 $this->save_sessiondata();
398         }
399       
400
401         function ht_sandbox()
402         {
403                 $this->t->set_file(array('ht_sandbox_t' => 'ht_sandbox.tpl'));
404             $this->t->set_block('ht_sandbox_t','switch_case_list','sc_list');
405                 $this->t->set_block('ht_sandbox_t','comp_list','c_list');
406                 $this->t->set_block('ht_sandbox_t','district_list','d_list');
407                 $this->t->set_block('ht_sandbox_t','unassigned_ht_list','uht_list');
408                 $this->t->set_block('ht_sandbox_t','assigned_ht_list','aht_list');
409                 $this->t->set_block('ht_sandbox_t','unassigned_family_list','uf_list');
410                 $this->t->set_block('ht_sandbox_t','assigned_family_list','af_list');
411                 $this->t->set_block('ht_sandbox_t','district_table_list','dt_list');
412                 $this->t->set_block('ht_sandbox_t','companionship_table_list','ct_list');
413
414                 $this->t->set_var('submit_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ht_sandbox&action=add'));
415             $this->t->set_var('jquery_url',$GLOBALS['phpgw']->link('inc/jquery.js'));
416                  
417             $action = get_var('action',array('GET','POST'));
418
419                 $this->t->set_var('title','Hometeaching Sandbox'); 
420
421                 if ($_POST['add']) {
422                         #$this->t->set_var('debug_list',$_POST['add']);
423                         $companionship = get_var('companionship',array('POST'));
424                         $district = get_var('district',array('POST'));
425                         $assignedHT_list = get_var('assignedHT',array('POST'));
426                         $unassignedHT_list = get_var('unassignedHT',array('POST'));
427                         $assigned_family_list = get_var('assignedFamiles',array('POST'));
428                         $unassigned_family_list = get_var('unassignedFamilies',array('POST'));
429                         
430                         if ($assignedHT_list || $unassignedHT_list) {
431                                 $sql = "INSERT INTO tc_companionship_sandbox (tc_companionship,district) VALUES (\"NULL\",\"$district\")";
432                                 $this->db2->query($sql,__LINE__,__FILE__);
433                                 $companionship_sandbox = mysql_insert_id();
434                                 
435                                 foreach ($assignedHT_list as $individual) {
436                                         $sql = "INSERT INTO tc_companion_sandbox (individual,companionship) VALUES (\"$individual\",\"$companionship_sandbox\")";
437                                         $this->db->query($sql,__LINE__,__FILE__);
438                                 }
439                                 foreach ($unassignedHT_list as $individual) {
440                                         $sql = "INSERT INTO tc_companion_sandbox (individual,companionship) VALUES (\"$individual\",\"$companionship_sandbox\")";
441                                         $this->db->query($sql,__LINE__,__FILE__);
442                                 }
443                                 foreach ($assigned_family_list as $family) {
444                                         $sql = "UPDATE tc_family_sandbox SET companionship=$companionship_sandbox WHERE family=$family";
445                                         $this->db->query($sql,__LINE__,__FILE__);
446                                 }
447                                 foreach ($unassigned_family_list as $family) {
448                                         $sql = "UPDATE tc_family_sandbox SET companionship=$companionship_sandbox WHERE family=$family";
449                                         $this->db->query($sql,__LINE__,__FILE__);
450                                 }
451                         } else {
452                                 $this->t->set_var('debug_list','You must select at least one companion!');
453                         }
454                 } else if ($_POST['delete']) {
455                         #$this->t->set_var('debug_list',$_POST['delete']);
456                         $companionship = get_var('companionship',array('POST'));
457                         #$this->t->set_var('debug_list',$companionship);
458                         
459                         if ($companionship > 0) {
460                                 # unassign families
461                                 $sql = "UPDATE tc_family_sandbox SET companionship=NULL WHERE companionship=$companionship";
462                                 $this->db->query($sql,__LINE__,__FILE__);
463                                 
464                                 # remove companions
465                                 $sql = "DELETE FROM tc_companion_sandbox WHERE companionship=$companionship";
466                                 $this->db->query($sql,__LINE__,__FILE__);
467                                 
468                                 # remove companionship
469                                 $sql = "DELETE FROM tc_companionship_sandbox WHERE companionship=$companionship";
470                                 $this->db->query($sql,__LINE__,__FILE__);
471                         } else {
472                                 $this->t->set_var('debug_list','You must select a companionship to delete!');
473                         }
474                 } else if ($_POST['update']) {
475                         #$this->t->set_var('debug_list',$_POST['update']);
476                         $companionship = get_var('companionship',array('POST'));
477                         $district = get_var('district',array('POST'));
478                         $assignedHT_list = get_var('assignedHT',array('POST'));
479                         $unassignedHT_list = get_var('unassignedHT',array('POST'));
480                         $assigned_family_list = get_var('assignedFamiles',array('POST'));
481                         $unassigned_family_list = get_var('unassignedFamilies',array('POST'));
482                         #$this->t->set_var('debug_list',$district);
483                         
484                         if ($companionship > 0) {
485                                 if ($assignedHT_list || $unassignedHT_list) {
486                                         # clear out existing info about companionship
487                                         $sql = "UPDATE tc_family_sandbox SET companionship=NULL WHERE companionship=$companionship";
488                                         $this->db->query($sql,__LINE__,__FILE__);
489                                         $sql = "DELETE FROM tc_companion_sandbox WHERE companionship=$companionship";
490                                         $this->db->query($sql,__LINE__,__FILE__);
491                                         
492                                         # set new info about companionship
493                                         $sql = "UPDATE tc_companionship_sandbox SET district=$district WHERE companionship=$companionship";
494                                         $this->db->query($sql,__LINE__,__FILE__);
495                                         foreach ($assignedHT_list as $individual) {
496                                                 $sql = "INSERT INTO tc_companion_sandbox (individual,companionship) VALUES (\"$individual\",\"$companionship\")";
497                                                 $this->db->query($sql,__LINE__,__FILE__);
498                                         }
499                                         foreach ($unassignedHT_list as $individual) {
500                                                 $sql = "INSERT INTO tc_companion_sandbox (individual,companionship) VALUES (\"$individual\",\"$companionship\")";
501                                                 $this->db->query($sql,__LINE__,__FILE__);
502                                         }
503                                         foreach ($assigned_family_list as $family) {
504                                                 $sql = "UPDATE tc_family_sandbox SET companionship=$companionship WHERE family=$family";
505                                                 $this->db->query($sql,__LINE__,__FILE__);
506                                         }
507                                         foreach ($unassigned_family_list as $family) {
508                                                 $sql = "UPDATE tc_family_sandbox SET companionship=$companionship WHERE family=$family";
509                                                 $this->db->query($sql,__LINE__,__FILE__);
510                                         }
511                                 } else {
512                                         $this->t->set_var('debug_list','You must select at least one companion!');
513                                 }
514                         } else {
515                                 $this->t->set_var('debug_list','You must select a companionship to update!');
516                         }
517                 } else if ($_POST['reset']) {
518                         #$this->t->set_var('debug_list',$_POST['reset']);
519                         
520                         $sql = "TRUNCATE TABLE tc_district_sandbox";
521                         $this->db->query($sql,__LINE__,__FILE__);
522                         $sql = "TRUNCATE TABLE tc_family_sandbox";
523                         $this->db->query($sql,__LINE__,__FILE__);
524                         $sql = "TRUNCATE TABLE tc_companion_sandbox";
525                         $this->db->query($sql,__LINE__,__FILE__);
526                         $sql = "TRUNCATE TABLE tc_companionship_sandbox";
527                         $this->db->query($sql,__LINE__,__FILE__);
528                         
529                         # populate tc_district_sandbox
530                         $sql = "SELECT * FROM tc_district WHERE valid=1";
531                         $this->db->query($sql,__LINE__,__FILE__);
532                         while ($this->db->next_record()) {
533                                 $district = $this->db->f('district');
534                                 $supervisor = $this->db->f('supervisor');
535                                 $sql = "INSERT INTO tc_district_sandbox (district,supervisor) VALUES (\"$district\",\"$supervisor\")";
536                                 $this->db2->query($sql,__LINE__,__FILE__);
537                         }
538                         
539                         # populate family, companion, and companionship tables
540                         $sql = "SELECT * FROM tc_companionship WHERE valid=1";
541                         $this->db->query($sql,__LINE__,__FILE__);
542                         while ($this->db->next_record()) {
543                                 $companionship = $this->db->f('companionship');
544                                 $district = $this->db->f('district');
545                                 $sql = "INSERT INTO tc_companionship_sandbox (tc_companionship,district) VALUES (\"$companionship\",\"$district\")";
546                                 $this->db2->query($sql,__LINE__,__FILE__);
547                                 $companionship_sandbox = mysql_insert_id();
548                                 
549                                 $sql = "SELECT * FROM tc_companion AS tc JOIN tc_individual AS ti WHERE tc.individual=ti.individual AND tc.companionship=$companionship AND tc.valid=1 AND ti.valid=1";
550                                 $this->db2->query($sql,__LINE__,__FILE__);
551                                 while ($this->db2->next_record()) {
552                                         $individual = $this->db2->f('individual');
553                                         $sql = "INSERT INTO tc_companion_sandbox (individual,companionship) VALUES (\"$individual\",\"$companionship_sandbox\")";
554                                         $this->db3->query($sql,__LINE__,__FILE__);
555                                 }
556                                 
557                                 $sql = "SELECT * FROM tc_family WHERE companionship=$companionship AND valid=1";
558                                 $this->db2->query($sql,__LINE__,__FILE__);
559                                 while ($this->db2->next_record()) {
560                                         $individual = $this->db2->f('individual');
561                                         $family = $this->db2->f('family');
562                                         $sql = "INSERT INTO tc_family_sandbox (tc_family,individual,companionship) VALUES (\"$family\",\"$individual\",\"$companionship_sandbox\")";
563                                         $this->db3->query($sql,__LINE__,__FILE__);
564                                 }
565                         }
566                 } else if ($_POST['changes']) {
567                         $this->ht_sandbox_changes();
568                 }
569                 
570                 // get list of companionships
571                 $sql = "SELECT DISTINCT companionship FROM tc_companionship_sandbox ORDER BY companionship ASC";
572                 $this->db->query($sql,__LINE__,__FILE__);
573                 $unique_companionships = '';
574                 $unique_companionships[0]['companionship'] = 0;
575                 $this->t->set_var('companionship_list','<option value="0">New Companionship</option>');
576                 $this->t->fp('c_list','comp_list',True);
577                 $j=1;
578                 while ($this->db->next_record()) {
579                         $companionship = $this->db->f('companionship');
580                         $unique_companionships[$j]['companionship'] = $companionship;
581                         $combined_companionship = "";
582                         $sql = "SELECT * FROM tc_companion_sandbox AS tc JOIN tc_individual AS ti WHERE tc.individual=ti.individual AND tc.companionship=$companionship ORDER BY ti.name ASC";
583                         $this->db2->query($sql,__LINE__,__FILE__);
584                         while ($this->db2->next_record()) {
585                                 if ($combined_companionship == "") {
586                                         $combined_companionship .= $this->db2->f('name');
587                                 } else {
588                                         $combined_companionship .= " / " . $this->db2->f('name');
589                                 }
590                         }
591                         $this->t->set_var('companionship_list','<option value="'.$companionship.'">'.$combined_companionship.'</option>');
592                         $this->t->fp('c_list','comp_list',True);
593                         $j++;
594                 }
595
596                 # get list of districts
597                 $sql = "SELECT DISTINCT district FROM tc_district_sandbox ORDER BY district ASC";
598                 $this->db->query($sql,__LINE__,__FILE__);
599                 $districts = '';
600                 $num_districts=0;
601                 while ($this->db->next_record()) {
602                         $districts[$num_districts] = $this->db->f('district');
603                         $this->t->set_var('district','<option value="'.$districts[$num_districts].'">'.$districts[$num_districts].'</option>');
604                         $this->t->fp('d_list','district_list',True);
605                         $num_districts++;
606                 }
607
608                 # get list of individuals who are and are not home teachers
609                 $sql = "SELECT * FROM tc_individual WHERE steward='$this->default_stewardship' AND valid=1 ORDER BY name ASC";
610                 $this->db->query($sql,__LINE__,__FILE__);
611                 while ($this->db->next_record()) {
612                         $individual = $this->db->f('individual');
613                         $name = $this->db->f('name');
614                         $sql = "SELECT DISTINCT * FROM tc_companion_sandbox WHERE individual=$individual";
615                         $this->db2->query($sql,__LINE__,__FILE__);
616                         if ($this->db2->next_record()) {
617                                 $this->t->set_var('assigned_ht','<option value="'.$individual.'">'.$name.'</option>');
618                                 $this->t->fp('aht_list','assigned_ht_list',True);
619                         } else {
620                                 $this->t->set_var('unassigned_ht','<option value="'.$individual.'">'.$name.'</option>');
621                                 $this->t->fp('uht_list','unassigned_ht_list',True);
622                         }
623                 }
624                 
625                 # get list of families who are and are not assigned home teachers
626                 $sql = "SELECT * FROM tc_family_sandbox AS tf JOIN tc_individual AS ti WHERE tf.individual=ti.individual ORDER BY ti.name ASC";
627                 $this->db->query($sql,__LINE__,__FILE__);
628                 while ($this->db->next_record()) {
629                         $individual = $this->db->f('individual');
630                         $family = $this->db->f('family');
631                         $name = $this->db->f('name');
632                         if ($this->db->f('companionship') != 0) {
633                                 $this->t->set_var('assigned_family','<option value="'.$family.'">'.$name.' Family</option>');
634                                 $this->t->fp('af_list','assigned_family_list',True);
635                         } else {
636                                 $this->t->set_var('unassigned_family','<option value="'.$family.'">'.$name.' Family</option>');
637                                 $this->t->fp('uf_list','unassigned_family_list',True);
638                         }
639                 }
640                 
641                 # populate ht districts table
642                 $sandbox_table_data = "<table border=\"0\" cellspacing=\"2\" cellpadding=\"2\">";
643                 
644                 # set up column headers
645                 $sandbox_table_data .= "<tr>";
646                 for ($d = 0; $d < $num_districts; $d++) {
647                         $sandbox_table_data .= "<th align=\"center\" bgcolor=\"#c9c9c9\">District " . $districts[$d] . "</th>";
648                 }
649
650                 # get each companionship in each district
651                 $sandbox_table_data .= "<tr>";
652                 for ($d = 0; $d < $num_districts; $d++) {
653                         $sandbox_table_data .= "<td valign=\"Top\">";
654                         $sandbox_table_data .= "<table>";
655                         $sql = "SELECT DISTINCT companionship FROM tc_companionship_sandbox WHERE district=$districts[$d] ORDER BY companionship ASC";
656                         $this->db->query($sql,__LINE__,__FILE__);
657                         while ($this->db->next_record()) {
658                             $switch_case_list = "";
659                                 $sandbox_table_data .= "<tr><td><table>";
660                                 $companionship = $this->db->f('companionship');
661
662                             $switch_case_list .= "case '". $companionship ."':\n";
663                                 $switch_case_list .= "  $(\"#district option:selected\").removeAttr(\"selected\");\n";
664                                 $switch_case_list .= "  $(\"#assignedHT option:selected\").removeAttr(\"selected\");\n";
665                                 $switch_case_list .= "  $(\"#assignedFamilies option:selected\").removeAttr(\"selected\");\n";
666                                 $switch_case_list .= "  $(\"#district option[value='".$districts[$d]."']\").attr(\"selected\",true);\n";
667
668                                 # get names of companions in this companionship
669                                 $sql = "SELECT * FROM tc_companion_sandbox AS tc JOIN tc_individual AS ti WHERE tc.individual=ti.individual AND companionship=$companionship ORDER BY ti.name ASC";
670                                 $this->db2->query($sql,__LINE__,__FILE__);
671                                 $companion_names = "";
672                                 while ($this->db2->next_record()) {
673                                         if ($companion_names == "") {
674                                                 $companion_names .= $this->db2->f('name');
675                                         } else {
676                                                 $companion_names .= " / " . $this->db2->f('name');
677                                         }
678                                         $individual = $this->db2->f('individual');
679                                         $switch_case_list .= "  $(\"#assignedHT option[value='".$individual."']\").attr(\"selected\",true);\n";
680                                 }
681                                 $this->nextmatchs->template_alternate_row_color(&$this->t);
682                                 $sandbox_table_data .= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
683                                 $sandbox_table_data .= "<th bgcolor=#d3dce3 align=\"Left\">$companion_names</th></tr>";
684                                 $sandbox_table_data .= "<tr bgcolor=". $this->t->get_var('tr_color') ."><td><table>";
685                                 
686                                 # get families they visit
687                                 $sql = "SELECT * FROM tc_companionship_sandbox AS tcp JOIN (tc_family_sandbox AS tf, tc_individual AS ti) WHERE tcp.companionship=$companionship AND tcp.companionship=tf.companionship AND tf.individual=ti.individual";
688                                 $this->db2->query($sql,__LINE__,__FILE__);
689                                 while ($this->db2->next_record()) {
690                                         $family_name = $this->db2->f('name') . " Family";
691                                         $family_id = $this->db2->f('tc_family');
692                                     $family = $this->db2->f('family');
693                                         $tc_companionship = $this->db2->f('tc_companionship');
694                                     $this->nextmatchs->template_alternate_row_color(&$this->t);
695                                     $sandbox_table_data .= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
696                                         $sandbox_table_data .= "<td align=\"Left\" width=\"1000\">$family_name</td>";
697                                     $switch_case_list .= "  $(\"#assignedFamilies option[value='".$family."']\").attr(\"selected\",true);\n";
698                                   
699                                         # get 12 months visit data for given family
700                                         for($m=$this->sandbox_stats_num_months; $m > 0; $m--) {
701                                                 $month = $this->current_month - $m;
702                                                 $year = $this->current_year;
703                                                 if($month <= 0) { $remainder = $month; $month = 12 + $remainder; $year=$year-1; }
704                                                 if($month < 10) { $month = "0"."$month"; }
705                                                 $month_start = "$year"."-"."$month"."-"."01";
706                                                 $month_end = "$year"."-"."$month"."-"."31";
707                                                 $month = "$month"."/"."$year";
708
709                                                 if ($this->sandbox_visits_comp_only == 0) {
710                                                         $sql = "SELECT * FROM tc_visit WHERE date >= '$month_start' AND date <= '$month_end' AND companionship!=0 AND family=". $family_id;
711                                                 } else {
712                                                         $sql = "SELECT * FROM tc_visit WHERE date >= '$month_start' AND date <= '$month_end' AND companionship=$tc_companionship AND family=". $family_id;
713                                                 }
714                                                 $query_id = $this->db3->query($sql,__LINE__,__FILE__);
715
716                                                 if($this->db3->next_record()) {
717                                                         if($this->db3->f('visited') == 'y') {
718                                                                 $sandbox_table_data .= "<td align=\"Right\"><img src=\"images/checkmark.gif\"></td>";
719                                                         } else if($this->db3->f('visited') == 'n') {
720                                                                 $sandbox_table_data .= "<td align=\"Right\"><img src=\"images/x.gif\"></td>";
721                                                         } else {
722                                                                 $sandbox_table_data .= "<td>&nbsp;</td>";
723                                                         }
724                                                 } else {
725                                                         $sandbox_table_data .= "<td>&nbsp;</td>";
726                                                 }
727                                         }
728                                         $sandbox_table_data .= "</tr>";
729                                 }
730                                 $sandbox_table_data .= "</table></td></tr>";
731                                 $sandbox_table_data .= "</table></td></tr>";
732                                 $switch_case_list .= "break;\n";
733                                 $this->t->set_var('switch_case_list',$switch_case_list);
734                                 $this->t->fp('sc_list','switch_case_list',True);
735                         }
736                         $sandbox_table_data .= "</table>";
737                         $sandbox_table_data .= "</td>";
738                 }
739                 $sandbox_table_data .= "</tr>";
740                 
741                 $sandbox_table_data .= "</table>";
742                 $this->t->set_var('district_table',$sandbox_table_data);
743
744                 $this->t->pfp('out','ht_sandbox_t');
745                 $this->save_sessiondata();
746         }
747
748         function ht_sandbox_changes()
749         {
750                 // list all companionships deleted
751                 $email_contents = "Removed Companionships\n\n";
752                 $sql = "SELECT * FROM tc_companionship WHERE companionship NOT IN (SELECT tc_companionship FROM tc_companionship_sandbox) AND valid=1";
753                 $this->db->query($sql,__LINE__,__FILE__);
754                 while ($this->db->next_record()) {
755                         $companionship = $this->db->f('companionship');
756                         $sql = "SELECT * FROM tc_companion AS tc JOIN tc_individual AS ti WHERE tc.individual=ti.individual AND tc.companionship=$companionship";
757                         $this->db2->query($sql,__LINE__,__FILE__);
758                         $companion_names = "";
759                         while ($this->db2->next_record()) {
760                                 if ($companion_names == "") {
761                                         $companion_names .= $this->db2->f('name');
762                                 } else {
763                                         $companion_names .= " / " . $this->db2->f('name');
764                                 }
765                         }
766                         $email_contents .= "\t$companion_names\n";
767                 }
768                 $email_contents .= "\n\n\n";
769                 
770                 // list all companionships added
771                 $email_contents .= "New Companionships\n\n";
772                 $sql = "SELECT * FROM tc_companionship_sandbox WHERE tc_companionship=0";
773                 $this->db->query($sql,__LINE__,__FILE__);
774                 while ($this->db->next_record()) {
775                         $companionship = $this->db->f('companionship');
776                         $sql = "SELECT * FROM tc_companion_sandbox AS tcs JOIN tc_individual AS ti WHERE tcs.individual=ti.individual AND tcs.companionship=$companionship";
777                         $this->db2->query($sql,__LINE__,__FILE__);
778                         $companion_names = "";
779                         while ($this->db2->next_record()) {
780                                 if ($companion_names == "") {
781                                         $companion_names .= $this->db2->f('name');
782                                 } else {
783                                         $companion_names .= " / " . $this->db2->f('name');
784                                 }
785                         }
786                         $email_contents .= "\t$companion_names\n";
787                         $sql = "SELECT * FROM tc_family_sandbox AS tfs JOIN tc_individual AS ti WHERE tfs.individual=ti.individual AND companionship=$companionship";
788                         $this->db2->query($sql,__LINE__,__FILE__);
789                         while ($this->db2->next_record()) {
790                                 $family_name = $this->db2->f('name') . " Family";
791                                 $email_contents .= "\t\t$family_name\n";
792                         }
793                 }
794                 $email_contents .= "\n\n\n";
795                 
796                 // list all companionships with changes
797                 $email_contents .= "Modified Companionships\n\n";
798                 $sql = "SELECT tcps.* FROM tc_companionship AS tc JOIN tc_companionship_sandbox AS tcps WHERE tc.companionship=tcps.tc_companionship";
799                 $this->db->query($sql,__LINE__,__FILE__);
800                 while ($this->db->next_record()) {
801                         $companionship = $this->db->f('companionship');
802                         $tc_companionship = $this->db->f('tc_companionship');
803                         $changed = 0;
804                         // compare companion list
805                         
806                         // list removed families
807                         // list added families
808                 }
809                 $email_contents .= "\n\n\n";
810                 
811                 // email changes to presidency
812                 $to = "owenleonard@gmail.com";
813                 $subject = "HomeTeaching Changes";
814                 $message .= "$email_contents";
815                 $headers = 'From: webmaster@example.com' . "\r\n" .
816                            'Reply-To: webmaster@example.com' . "\r\n" .
817                            'X-Mailer: PHP/' . phpversion();
818
819
820                 mail($to, $subject, $message, $headers);
821         }
822
823         function ht_update()
824         {
825                 $this->t->set_file(array('ht_update_t' => 'ht_update.tpl'));
826                 $this->t->set_block('ht_update_t','district_list','list');
827                 $this->t->set_block('ht_update_t','save','savehandle');
828
829                 $district = get_var('district',array('GET','POST'));
830                 $district_name = get_var('district_name',array('GET','POST'));
831                 $date = get_var('date',array('GET','POST'));
832                 $month = get_var('month',array('GET','POST'));
833                 $month_start = get_var('month_start',array('GET','POST'));
834                 $month_end = get_var('month_end',array('GET','POST'));
835                 $action = get_var('action',array('GET','POST'));
836
837                 $this->t->set_var('done_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ht_view'));
838                 $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ht_update&action=save'));
839                 $this->t->set_var('lang_done','Cancel');
840                 $this->t->set_var('district_name',$district_name);
841                 $this->t->set_var('district_number',$district);
842                 $this->t->set_var('title','Hometeaching Update ' . $month);
843                 $this->t->set_var('date',$date);
844
845                 if($action == 'save') {
846                         // Get a list of all the companionships in this district
847                         $sql = "SELECT distinct companionship FROM tc_companionship where valid=1 and district=". $district;
848                         $this->db->query($sql,__LINE__,__FILE__);
849                         $j=0; $unique_companionships = '';
850                         while ($this->db->next_record()) {
851                                 $unique_companionships[$j]['companionship'] = $this->db->f('companionship');
852                                 $j++;
853                         }
854                         for ($j=0; $j < count($unique_companionships); $j++) {
855                                 //$comp=$unique_companionships[$j]['companionship'];
856                                 //print "deleting from tc_visit where companionship=$comp and date=$date and district=$district<br>";
857                                 // Delete all the visits that have taken place for all families for this companionsthip for this month
858                                 $this->db->query("DELETE from tc_visit where companionship=" . $unique_companionships[$j]['companionship'] .
859                                                  " AND " . "date='" . $date . "'",__LINE__,__FILE__);
860                         }
861
862                         // Now, add the visits that are checked for this month
863                         $new_data = get_var('family_visited',array('POST'));
864                         foreach ($new_data as $family) {
865                                 foreach ($family as $data) {
866                                         //print "family_visited: $data <br>";
867                                         $data_array = explode("/",$data);
868                                         $family_id = $data_array[0];
869                                         $companionship = $data_array[1];
870                                         $date = $data_array[2];
871                                         $visited = $data_array[3];
872                                         if($visited == "") { $visited = $data_array[4]; }
873                                         //print "family_id: $family_id companionship: $companionship date: $date visited: $visited<br>";
874                                         $this->db->query("INSERT INTO tc_visit (family,companionship,date,notes,visited) " . 
875                                                          "VALUES (" . $family_id .",". $companionship .",'". $date ."','','". $visited ."')",__LINE__,__FILE__);
876                                 }
877                         }
878                         $this->ht_view();
879                         return false;
880                 }
881
882                 $sql = "SELECT * FROM tc_individual where valid=1 ORDER BY individual ASC";
883                 $this->db->query($sql,__LINE__,__FILE__);
884                 $i=0;
885                 while ($this->db->next_record()) {
886                         $individual[$i] = $this->db->f('individual');
887                         $indiv_name[$i] = $this->db->f('name');
888                         $indiv_phone[$individual[$i]] = $this->db->f('phone');
889                         $i++;
890                 }
891                 array_multisort($indiv_name, $individual);
892
893                 // Make an array mapping individuals to indiv_names
894                 for($i=0; $i < count($individual); $i++) {
895                         $id = $individual[$i];
896                         $indivs[$id] = $indiv_name[$i];
897                 }      
898
899                 // Select all the unique companionship numbers for this district
900                 $sql = "SELECT distinct companionship FROM tc_companionship where valid=1 and district=". $district;
901                 $this->db->query($sql,__LINE__,__FILE__);
902                 $j=0; $unique_companionships = '';
903                 while ($this->db->next_record()) {
904                         $unique_companionships[$j]['companionship'] = $this->db->f('companionship');
905                         $j++;
906                 }
907
908                 $comp_width=300; $visit_width=25; $table_width=$comp_width + $visit_width;
909                 $table_data=""; $num_companionships = 0; $num_families = 0; $visits=0;
910                 for ($j=0; $j < count($unique_companionships); $j++) {
911                         $companion_table_entry = "";
912                         // Select all the companions in each companionship
913                         $sql = "SELECT * FROM tc_companionship where valid=1 and ".
914                         "companionship=". $unique_companionships[$j]['companionship'];
915                         $this->db->query($sql,__LINE__,__FILE__);
916
917                         while ($this->db->next_record()) {
918                                 // Get this companions information
919                                 if($companion_table_entry != "") { $companion_table_entry .= "<td>&nbsp;/&nbsp;</td>"; }
920                                 $companionship = $this->db->f('companionship');
921                                 $individual = $this->db->f('individual');
922                                 $name = $indivs[$individual];
923                                 $phone = $indiv_phone[$individual];
924                                 $companion_table_entry .= "<td title=\"$phone\"><b>$name</b></td>";
925                         }
926                         $table_data.= "<tr bgcolor=#d3dce3><td colspan=20><table><tr>$companion_table_entry</tr></table><hr></td></tr>";
927
928                         // Get the names of the families assigned this home teaching companionship
929                         $sql = "SELECT * FROM tc_family AS tf JOIN tc_individual AS ti WHERE tf.individual=ti.individual AND tf.valid=1 AND tf.companionship=".$unique_companionships[$j]['companionship'];
930                         $sql = $sql . " ORDER BY ti.name ASC";
931                         $this->db->query($sql,__LINE__,__FILE__);
932                         while ($this->db->next_record()) {
933                                 $family_name = $this->db->f('name');
934                                 $family_id = $this->db->f('family');
935                                 $this->nextmatchs->template_alternate_row_color(&$this->t);
936                                 $table_data.="<tr bgcolor=". $this->t->get_var('tr_color') ."><td>$family_name Family</td>";
937
938                                 $header_row="<th width=$comp_width><font size=-2>Families</th>";
939
940                                 // First check to see if the currently assigned companionship has visited them
941                                 $sql = "SELECT * FROM tc_visit WHERE date >= '$month_start' AND date <= '$month_end' ".
942                                        " AND companionship=".$unique_companionships[$j]['companionship'].
943                                        " AND family=". $family_id;
944                                 $query_id = $this->db2->query($sql,__LINE__,__FILE__);
945                                 if($this->db2->num_rows($query_id) == 0) {
946                                         // We did not find any visits made by the currently assigned companionship,
947                                         // look for visits made by any other companionship other than 0. (0 == Presidency Visit)
948                                         $sql = "SELECT * FROM tc_visit WHERE date >= '$month_start' AND date <= '$month_end' ".
949                                                " AND companionship!=0".
950                                                " AND family=". $family_id;
951                                         $query_id = $this->db2->query($sql,__LINE__,__FILE__);
952                                 }
953
954                                 $value = $family_id . "/" . $unique_companionships[$j]['companionship'] . "/" . $date;
955                                 $header_row .= "<th width=$visit_width><font size=-2><a href=$link>$month</a></th>";
956                                 if(!$total_visits) { $total_visits = 0; }
957                                 if($this->db2->next_record()) {
958                                         if($this->db2->f('visited') == 'y') {
959                                                 $visits++; $total_visits++; $num_families++;
960                                                 $table_data .= '<td width=100 align=center>';
961                                                 $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/y" checked>Y';
962                                                 $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/n">N';
963                                                 $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/"> ';
964                                                 $table_data .= '</td>';
965                                         } else if($this->db2->f('visited') == 'n') {
966                                                 $num_families++;
967                                                 $table_data .= '<td width=100 align=center>';
968                                                 $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/y">Y';
969                                                 $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/n" checked>N';
970                                                 $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/">';
971                                                 $table_data .= '</td>';
972                                         } else {
973                                                 $table_data .= '<td width=100 align=center>';
974                                                 $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/y">Y';
975                                                 $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/n">N';
976                                                 $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/" checked> ';
977                                                 $table_data .= '</td>';
978                                         }
979                                 }
980                                 else {
981                                         $value .= "/";
982                                         $table_data .= '<td width=100 align=center>';
983                                         $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/y">Y';
984                                         $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/n">N';
985                                         $table_data .= '<input type="radio" name="family_visited['.$family_id.'][]" value="'.$value.'/" checked> ';
986                                         $table_data .= '</td>';       
987                                 }
988                         }
989                         $table_data .= "</tr>"; 
990                         $table_data .= "<tr><td colspan=20></td></tr>";
991                 }
992                 $table_data .= "<tr><td colspan=20><hr></td></tr>";
993                 $stat_data = "<tr><td><b><font size=-2>Families Hometaught:<br>Hometeaching Percentage:</font></b></td>";
994
995                 $percent = ceil(($visits / $num_families)*100);
996                 $stat_data .= "<td align=center><font size=-2><b>$visits / $num_families<br>$percent%</font></b></td>";
997                 $stat_data .= "</tr>";
998
999                 $this->t->set_var('table_width',$table_width);
1000                 $this->t->set_var('header_row',$header_row);
1001                 $this->t->set_var('table_data',$table_data);
1002                 $this->t->set_var('stat_data',$stat_data);
1003                 $this->t->fp('list','district_list',True);
1004
1005                 $this->t->set_var('lang_reset','Clear Form');
1006                 $this->t->set_var('lang_save','Save Changes');
1007                 $this->t->set_var('savehandle','');
1008
1009                 $this->t->pfp('out','ht_update_t');
1010                 $this->t->pfp('addhandle','save');
1011
1012                 $this->save_sessiondata();
1013         }
1014
1015         function act_list()
1016         {
1017                 $this->t->set_file(array('act_list_t' => 'act_list.tpl'));
1018                 $this->t->set_block('act_list_t','act_list','list');
1019
1020                 $this->t->set_var('lang_name','Assignment');
1021                 $this->t->set_var('lang_date','Date');
1022                 $this->t->set_var('lang_notes','Description');
1023
1024                 $sql = "SELECT * FROM tc_activity ORDER BY date DESC";
1025                 $this->db->query($sql,__LINE__,__FILE__);
1026                 $total_records = $this->db->num_rows();
1027
1028                 $i = 0;
1029                 while ($this->db->next_record()) {
1030                         $activity_list[$i]['activity']  = $this->db->f('activity');
1031                         $activity_list[$i]['assignment'] = $this->db->f('assignment');
1032                         $activity_list[$i]['date']  = $this->db->f('date');
1033                         $activity_list[$i]['notes']  = $this->db->f('notes');
1034
1035                         $sql = "SELECT * FROM tc_assignment WHERE assignment='" . $activity_list[$i]['assignment'] . "'";
1036                         $this->db2->query($sql,__LINE__,__FILE__);
1037                         if($this->db2->next_record()) {
1038                                 $activity_list[$i]['name'] = $this->db2->f('name');
1039                                 $activity_list[$i]['abbreviation'] = $this->db2->f('abbreviation');
1040                         }
1041                         $i++;
1042                 }
1043
1044                 for ($i=0; $i < count($activity_list); $i++) {
1045                         $this->nextmatchs->template_alternate_row_color(&$this->t);
1046                         $this->t->set_var('name',$activity_list[$i]['name']);
1047                         $this->t->set_var('date',$activity_list[$i]['date']);
1048                         $activity_notes = $activity_list[$i]['notes'];
1049                         if(strlen($activity_notes) > 40) { $activity_notes = substr($activity_notes,0,40) . "..."; }
1050                         $this->t->set_var('notes',$activity_notes);
1051
1052                         $link_data['menuaction'] = 'tc.tc.act_view';
1053                         $link_data['activity'] = $activity_list[$i]['activity'];
1054                         $link_data['action'] = 'view';
1055                         $this->t->set_var('view',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
1056                         $this->t->set_var('lang_view','View');
1057
1058                         $link_data['menuaction'] = 'tc.tc.act_update';
1059                         $link_data['activity'] = $activity_list[$i]['activity'];
1060                         $link_data['action'] = 'edit';
1061                         $this->t->set_var('edit',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
1062                         $this->t->set_var('lang_edit','Edit');
1063
1064                         $this->t->fp('list','act_list',True);
1065                 }
1066
1067                 $link_data['menuaction'] = 'tc.tc.act_update';
1068                 $link_data['activity'] = '0';
1069                 $link_data['action'] = 'add';
1070                 $this->t->set_var('add','<form method="POST" action="' . $GLOBALS['phpgw']->link('/tc/index.php',$link_data) .
1071                                   '"><input type="submit" name="Add" value="' . 'Add Activity' .'"></font></form>');
1072
1073                 $this->t->pfp('out','act_list_t');
1074                 $this->save_sessiondata();
1075         }
1076
1077         function act_view()
1078         {
1079                 $this->t->set_file(array('act_view_t' => 'act_view.tpl'));
1080                 $this->t->set_block('act_view_t','part_list','list');
1081
1082                 $sql = "SELECT * FROM tc_activity WHERE activity=" . intval(get_var('activity',array('GET','POST')));
1083                 $this->db->query($sql,__LINE__,__FILE__);
1084                 $this->db->next_record();
1085                 $this->t->set_var('assignment', $this->db->f('assignment'));
1086                 $this->t->set_var('date', $this->db->f('date'));
1087                 $this->t->set_var('notes', $this->db->f('notes'));
1088
1089                 $sql = "SELECT * FROM tc_assignment WHERE assignment='" . $this->db->f('assignment') . "'";
1090                 $this->db2->query($sql,__LINE__,__FILE__);
1091                 if($this->db2->next_record()) {
1092                         $this->t->set_var('name', $this->db2->f('name'));
1093                         $this->t->set_var('abbreviation', $this->db2->f('abbreviation'));
1094                 }
1095                 $this->t->set_var('lang_name','Assignment');
1096                 $this->t->set_var('lang_date','Date');
1097                 $this->t->set_var('lang_notes','Description');
1098                 $this->t->set_var('lang_done','Done');
1099                 $this->t->set_var('lang_action','View');
1100
1101                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
1102                 $this->t->set_var('tr_color',$tr_color);
1103
1104                 $this->t->set_var('done_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.act_list'));
1105
1106                 $link_data['menuaction'] = 'tc.tc.act_update';
1107                 $link_data['activity'] = get_var('activity',array('GET','POST'));
1108                 $link_data['action'] = 'edit';
1109                 $this->t->set_var('edit',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
1110                 $this->t->set_var('lang_edit','Edit');
1111                 $this->t->set_var('cal_date',$this->db->f('date'));
1112
1113                 // Now find out which indivs participated in this activity
1114                 $sql = "SELECT * FROM tc_participation WHERE activity=" . intval(get_var('activity',array('GET','POST')));
1115                 $this->db->query($sql,__LINE__,__FILE__);
1116                 $total_records = $this->db->num_rows();
1117
1118                 $i = 0;
1119                 while ($this->db->next_record()) {
1120                         $part_list[$i]['individual']  = $this->db->f('individual');
1121                         $i++;
1122                 }
1123
1124                 for ($i=0; $i < count($part_list); $i++) {
1125                         $sql = "SELECT * FROM tc_individual WHERE individual=" . $part_list[$i]['individual'];
1126                         $this->db->query($sql,__LINE__,__FILE__);
1127                         $this->db->next_record();
1128                         $names[$i] = $this->db->f('name');
1129                 }
1130                 sort($names);
1131
1132                 for ($i=0; $i < count($names); $i++) {
1133                         //$this->nextmatchs->template_alternate_row_color(&$this->t);
1134                         $this->t->set_var('individual_name',$names[$i]);
1135                         if(($i+1) % 3 == 0) {
1136                                 $this->t->set_var('table_sep',"</td></tr><tr>"); 
1137                         } else { 
1138                                 $this->t->set_var('table_sep',"</td>"); 
1139                         }
1140                         if(($i) % 3 == 0) { $this->nextmatchs->template_alternate_row_color(&$this->t); }
1141                         $this->t->fp('list','part_list',True);
1142                 }
1143
1144                 $this->t->pfp('out','act_view_t');
1145                 $this->save_sessiondata();
1146         }
1147
1148         function act_update()
1149         {
1150                 $this->t->set_file(array('form' => 'act_update.tpl'));
1151                 $this->t->set_block('form','individual_list','list');
1152                 $this->t->set_block('form','add','addhandle');
1153                 $this->t->set_block('form','edit','edithandle');
1154                 $this->t->set_var('lang_done','Done');
1155
1156                 $action = get_var('action',array('GET','POST'));
1157                 $this->t->set_var('done_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.act_list'));
1158                 $activity['activity'] = intval(get_var('activity',array('GET','POST')));
1159
1160                 if($action == 'save') {
1161                         $activity['assignment'] = get_var('assignment',array('POST'));
1162                         $activity['date'] = get_var('date',array('POST'));
1163                         $activity['notes']= get_var('notes',array('POST'));
1164                         $this->db->query("UPDATE tc_activity set " .
1165                                          "   assignment='" . $activity['assignment'] .
1166                                          "', date='" . $activity['date'] . "'" .
1167                                          ", notes=\"" . $activity['notes'] . "\"" .
1168                                          " WHERE activity=" . $activity['activity'],__LINE__,__FILE__);
1169
1170                         // Delete all the individuals who have particiapted in this activity
1171                         $this->db->query("DELETE from tc_participation where activity=".$activity['activity'],__LINE__,__FILE__);
1172
1173                         // Re-add the individuals who are checked as having participated in this activity
1174                         $indivs = get_var('individual_name',array('POST'));
1175                         if(is_array($indivs)) { // Only do the foreach loop if we have a valid array of indivs to work with
1176                                 foreach ($indivs as $individual) {
1177                                         $this->db->query("INSERT INTO tc_participation (individual,activity) " .
1178                                                          "VALUES (" . $individual . ",". $activity['activity'] . ")",__LINE__,__FILE__);
1179                                 }
1180                         }
1181
1182                         $this->act_list();
1183                         return false;
1184                 }
1185
1186                 if($action == 'insert') {
1187                         $activity['assignment'] = get_var('assignment',array('POST'));
1188                         $activity['date'] = get_var('date',array('POST'));
1189                         $activity['notes']= get_var('notes',array('POST'));
1190                         $this->db->query("INSERT INTO tc_activity (assignment,date,notes) " .
1191                                          "VALUES ('" . $activity['assignment'] . "','" .
1192                                          $activity['date'] . "',\"" . $activity['notes'] . "\")",__LINE__,__FILE__);
1193
1194                         $sql = "SELECT * FROM tc_activity WHERE assignment='".$activity['assignment']."' " .
1195                                " AND date='".$activity['date']."' AND notes=\"".$activity['notes']."\"";
1196                         $this->db->query($sql,__LINE__,__FILE__);
1197                         if($this->db->next_record()) {
1198                                 //print "activity: " . $this->db->f('activity') . "<br>";
1199                                 $activity['activity'] = $this->db->f('activity');
1200                         }
1201
1202                         $indivs = get_var('individual_name',array('POST'));
1203                         foreach ($indivs as $individual)
1204                         {
1205                                 $this->db->query("INSERT INTO tc_participation (individual,activity) " .
1206                                                  "VALUES (" . $individual . ",". $activity['activity'] . ")",__LINE__,__FILE__);
1207                         }
1208
1209                         $this->act_list();
1210                         return false;
1211                 }
1212
1213                 if($action == 'add') {
1214                         $activity['activity'] = 0;
1215                         $this->t->set_var('cal_date',$this->jscal->input('date','','','','','','',$this->cal_options));
1216                         $this->t->set_var('assignment','');
1217                         $this->t->set_var('date','');
1218                         $this->t->set_var('notes','');
1219                         $this->t->set_var('lang_done','Cancel');
1220                         $this->t->set_var('lang_action','Adding New Activity');
1221                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.act_update&activity=' .
1222                                           $activity['activity'] . '&action=' . 'insert'));
1223                 }
1224
1225                 if($action == 'edit') {
1226                         $sql = "SELECT * FROM tc_activity WHERE activity=" . $activity['activity'];
1227                         $this->db->query($sql,__LINE__,__FILE__);
1228                         $this->db->next_record();
1229                         $this->t->set_var('cal_date',$this->jscal->input('date',$this->db->f('date'),'','','','','',$this->cal_options));
1230                         $this->t->set_var('assignment', $this->db->f('assignment'));
1231                         $assignment = $this->db->f('assignment');
1232                         $this->t->set_var('date', $this->db->f('date'));
1233                         $this->t->set_var('notes', $this->db->f('notes'));
1234                         $this->t->set_var('lang_done','Cancel');
1235                         $this->t->set_var('lang_action','Editing Activity');
1236                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.act_update&activity=' .
1237                                           $activity['activity'] . '&action=' . 'save'));
1238                 }
1239
1240                 // Create the assignments drop-down list
1241                 $sql = "SELECT * FROM tc_assignment ORDER BY name ASC";
1242                 $this->db->query($sql,__LINE__,__FILE__);
1243                 $i = 0;
1244                 while ($this->db->next_record()) {
1245                         $assignments[$i]['assignment']  = $this->db->f('assignment');
1246                         $assignments[$i]['name'] = $this->db->f('name');
1247                         $assignments[$i]['abbreviation'] = $this->db->f('abbreviation');
1248                         $i++;
1249                 }
1250
1251                 $assignment_data.= '<select name=assignment>';
1252                 $assignment_data.= '<option value=0></option>';  
1253                 for ($j=0; $j < count($assignments); $j++) {
1254                         $id = $assignments[$j]['assignment'];
1255                         $name = $assignments[$j]['name'];
1256                         if($assignments[$j]['assignment'] == $assignment) { 
1257                                 $selected[$id] = 'selected="selected"'; 
1258                         } else { 
1259                                 $selected[$id] = ''; 
1260                         }
1261                         $assignment_data.= '<option value='.$id.' '.$selected[$id].'>'.$name.'</option>';
1262                 }
1263                 $assignment_data.='</select>';
1264                 $this->t->set_var('assignment_data',$assignment_data);
1265
1266                 // Create individual selection boxes
1267                 $sql = "SELECT * FROM tc_individual";
1268                 $this->db->query($sql,__LINE__,__FILE__);
1269                 $i=0;
1270                 while ($this->db->next_record()) {
1271                         if($this->db->f('valid') == 1 || $action != 'add') {
1272                                 $indiv_name[$i] = $this->db->f('name');
1273                                 $individual[$i] = $this->db->f('individual');
1274                                 $indiv_valid[$i] = $this->db->f('valid');
1275                                 $i++;
1276                         }
1277                 }
1278                 array_multisort($indiv_name, $individual, $indiv_valid);
1279
1280                 $j=0;
1281                 for ($i=0; $i < count($individual); $i++) {
1282                         //$this->nextmatchs->template_alternate_row_color(&$this->t);
1283                         $sql = "SELECT * FROM tc_participation where activity=". $activity['activity'] . " AND individual=" . $individual[$i];
1284                         $this->db->query($sql,__LINE__,__FILE__);
1285                         if($this->db->next_record()) { 
1286                                 $this->t->set_var('checked','checked'); 
1287                                 $checked=1; 
1288                         } else { 
1289                                 $this->t->set_var('checked',''); 
1290                                 $checked=0; 
1291                         }
1292                         if($checked || $indiv_valid[$i] == 1) {
1293                                 $this->t->set_var('individual_name',$indiv_name[$i]);
1294                                 $this->t->set_var('individual',$individual[$i]);
1295                                 if(($j+1) % 3 == 0) {
1296                                         $this->t->set_var('table_sep',"</td></tr><tr>"); 
1297                                 } else { 
1298                                         $this->t->set_var('table_sep',"</td>"); 
1299                                 }
1300                                 if(($j) % 3 == 0) { $this->nextmatchs->template_alternate_row_color(&$this->t); }
1301                                 $this->t->fp('list','individual_list',True);
1302                                 $j++;
1303                         }
1304                 }
1305
1306                 $this->t->set_var('lang_reset','Clear Form');
1307                 $this->t->set_var('lang_add','Add Activity');
1308                 $this->t->set_var('lang_save','Save Changes');
1309                 $this->t->set_var('edithandle','');
1310                 $this->t->set_var('addhandle','');
1311
1312                 $this->t->pfp('out','form');
1313                 if($action == 'edit') { $this->t->pfp('addhandle','edit'); }
1314                 if($action == 'add') { $this->t->pfp('addhandle','add'); }
1315
1316                 $this->save_sessiondata();
1317         }
1318
1319         function assign_view()
1320         {
1321                 $this->t->set_file(array('assign_view_t' => 'assign_view.tpl'));
1322                 $this->t->set_block('assign_view_t','assign_view','list');
1323
1324                 $this->t->set_var('lang_name','Assignment Name');
1325                 $this->t->set_var('lang_code','Abbreviation');
1326
1327                 $sql = "SELECT * FROM tc_assignment ORDER BY name ASC";
1328                 $this->db->query($sql,__LINE__,__FILE__);
1329                 $total_records = $this->db->num_rows();
1330
1331                 $i = 0;
1332                 while ($this->db->next_record()) {
1333                         $assignment_list[$i]['assignment']  = $this->db->f('assignment');
1334                         $assignment_list[$i]['name'] = $this->db->f('name');
1335                         $assignment_list[$i]['abbreviation'] = $this->db->f('abbreviation');
1336                         $i++;
1337                 }
1338
1339                 for ($i=0; $i < count($assignment_list); $i++) {
1340                         $this->nextmatchs->template_alternate_row_color(&$this->t);
1341                         $this->t->set_var('name',$assignment_list[$i]['name']);
1342                         $this->t->set_var('abbreviation',$assignment_list[$i]['abbreviation']);
1343
1344                         $link_data['menuaction'] = 'tc.tc.assign_update';
1345                         $link_data['assignment'] = $assignment_list[$i]['assignment'];
1346                         $link_data['action'] = 'edit';
1347                         $this->t->set_var('edit',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
1348                         $this->t->set_var('lang_edit','Edit');
1349
1350                         $link_data['menuaction'] = 'tc.tc.assign_update';
1351                         $link_data['assignment'] = '0';
1352                         $link_data['action'] = 'add';
1353                         $this->t->set_var('add','<form method="POST" action="' . $GLOBALS['phpgw']->link('/tc/index.php',$link_data) .
1354                                           '"><input type="submit" name="Add" value="' . 'Add Assignment' .'"></font></form>');
1355
1356                         $this->t->fp('list','assign_view',True);
1357                 }
1358
1359                 $this->t->pfp('out','assign_view_t');
1360                 $this->save_sessiondata();
1361         }
1362
1363         function assign_update()
1364         {
1365                 $this->t->set_file(array('form' => 'assign_update.tpl'));
1366                 $this->t->set_block('form','add','addhandle');
1367                 $this->t->set_block('form','edit','edithandle');
1368                 $this->t->set_var('lang_done','Done');
1369
1370                 $action = get_var('action',array('GET','POST'));
1371                 $this->t->set_var('done_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.assign_view'));
1372                 $assignment['assignment'] = intval(get_var('assignment',array('GET','POST')));
1373
1374                 if($action == 'save') {
1375                         $assignment['name'] = get_var('name',array('POST'));
1376                         $assignment['abbreviation'] = get_var('abbreviation',array('POST'));
1377                         $this->db->query("UPDATE tc_assignment set " .
1378                                          "  name='" . $assignment['name'] . "'" .
1379                                          ", abbreviation='" . $assignment['abbreviation'] . "'" .
1380                                          " WHERE assignment=" . $assignment['assignment'],__LINE__,__FILE__);
1381
1382                         $this->assign_view();
1383                         return false;
1384                 }
1385
1386                 if($action == 'insert') {
1387                         $assignment['name'] = get_var('name',array('POST'));
1388                         $assignment['abbreviation'] = get_var('abbreviation',array('POST'));
1389                         $this->db->query("INSERT INTO tc_assignment (name,abbreviation) " .
1390                                          "VALUES ('" . $assignment['name'] . "','" .
1391                                          $assignment['abbreviation'] . "')",__LINE__,__FILE__);
1392                         $this->assign_view();
1393                         return false;
1394                 }
1395
1396                 if($action == 'add') {
1397                         $assignment['assignment'] = 0;
1398                         $this->t->set_var('name','');
1399                         $this->t->set_var('abbreviation','');
1400                         $this->t->set_var('lang_done','Cancel');
1401                         $this->t->set_var('lang_action','Adding New Assignment');
1402                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.assign_update&assignment=' .
1403                                           $assignment['assignment'] . '&action=' . 'insert'));
1404                 }
1405
1406                 if($action == 'edit')
1407                 {
1408                         $sql = "SELECT * FROM tc_assignment WHERE assignment=" . $assignment['assignment'];
1409                         $this->db->query($sql,__LINE__,__FILE__);
1410                         $this->db->next_record();
1411                         $this->t->set_var('name', $this->db->f('name'));
1412                         $this->t->set_var('abbreviation', $this->db->f('abbreviation'));
1413                         $this->t->set_var('lang_done','Cancel');
1414                         $this->t->set_var('lang_action','Editing Assignment');
1415                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.assign_update&assignment=' .
1416                                           $assignment['assignment'] . '&action=' . 'save'));
1417                 }
1418
1419                 $this->t->set_var('lang_reset','Clear Form');
1420                 $this->t->set_var('lang_add','Add Assignment');
1421                 $this->t->set_var('lang_save','Save Changes');
1422                 $this->t->set_var('edithandle','');
1423                 $this->t->set_var('addhandle','');
1424
1425                 $this->t->pfp('out','form');
1426                 if($action == 'edit') { $this->t->pfp('addhandle','edit'); }
1427                 if($action == 'add') { $this->t->pfp('addhandle','add'); }
1428
1429                 $this->save_sessiondata();
1430         }
1431
1432         function par_view()
1433         {
1434                 $this->t->set_file(array('par_view_t' => 'par_view.tpl'));
1435                 $this->t->set_block('par_view_t','header_list','list1');
1436                 $this->t->set_block('par_view_t','individual_list','list2');
1437
1438                 $sql = "SELECT * FROM tc_individual where steward='$this->default_stewardship' and valid=1";
1439                 $this->db->query($sql,__LINE__,__FILE__);
1440                 $i=0;
1441                 while ($this->db->next_record()) {
1442                         $individual_name[$i] = $this->db->f('name');
1443                         $individual[$i] = $this->db->f('individual');
1444                         $i++;
1445                 }
1446                 array_multisort($individual_name, $individual);
1447
1448                 $sql = "SELECT * FROM tc_activity ORDER BY date DESC";
1449                 $this->db->query($sql,__LINE__,__FILE__);
1450                 $total_records = $this->db->num_rows();
1451
1452                 $i = 0;
1453                 while ($this->db->next_record()) {
1454                         $activity_list[$i]['assignment'] = $this->db->f('assignment');
1455                         $activity_list[$i]['date'] = $this->db->f('date');
1456                         $activity_list[$i]['activity']  = $this->db->f('activity');
1457                         $i++;
1458                 }
1459
1460                 $sql = "SELECT * FROM tc_assignment ORDER BY name ASC";
1461                 $this->db->query($sql,__LINE__,__FILE__);
1462                 $i=0;
1463                 while($this->db->next_record()) {
1464                         $assignment_list[$i]['assignment'] = $this->db->f('assignment');
1465                         $assignment_list[$i]['name'] = $this->db->f('name');
1466                         $assignment_list[$i]['abbreviation'] = $this->db->f('abbreviation');
1467                         $i++;
1468                 }
1469
1470                 $individual_width=300; $part_width=25; $assignment_width=50;
1471                 $total_width=$individual_width+$part_width;
1472                 for ($i=0; $i < count($assignment_list); $i++) {
1473                         $this->t->set_var('assignment_name',$assignment_list[$i]['name']);
1474                         $this->t->set_var('assignment_abbreviation',$assignment_list[$i]['abbreviation']);
1475                         $this->t->fp('list1','header_list',True);
1476                         $total_width += $assignment_width;
1477                 }
1478
1479                 for ($i=0; $i < count($individual); $i++) {
1480                         $participated=0; $part_table = ''; 
1481                         $this->nextmatchs->template_alternate_row_color(&$this->t);
1482                         $this->t->set_var('individual_name',$individual_name[$i]);
1483                         for ($j=0; $j < count($assignment_list); $j++) {
1484                                 $date = "0000-00-00"; $checkmark=0; $num_matches=0;
1485                                 for ($k=0; $k < count($activity_list); $k++) {
1486                                         if($assignment_list[$j]['assignment'] == $activity_list[$k]['assignment']) {
1487                                                 $sql = "SELECT * FROM tc_participation where " .
1488                                                        " activity=" . $activity_list[$k]['activity'] .
1489                                                        " AND individual=" . $individual[$i];
1490                                                 $this->db->query($sql,__LINE__,__FILE__);
1491                                                 while($this->db->next_record()) {
1492                                                         if($activity_list[$k]['date'] > $date) { 
1493                                                                 $date = $activity_list[$k]['date'];
1494                                                         }
1495                                                         $checkmark=1;
1496                                                         $num_matches++;
1497                                                         $participated++;
1498                                                 }
1499                                         }
1500                                 }
1501                                 if($checkmark) {
1502                                         $part_table .= '<td align=center><img src="images/checkmark.gif">';
1503                                         $part_table .= '<font size=-2>'.$num_matches.'</font><br>';
1504                                         $part_table .= '<font size=-2>'.$date.'</font></td>';
1505                                 } else {
1506                                         $part_table .= '<td>&nbsp;</td>';
1507                                 }
1508                         }
1509                         if($participated) { 
1510                                 $part_table .= '<td align=center><img src="images/checkmark.gif">'.$participated.'</td>'; 
1511                         } else { 
1512                                 $part_table .= '<td>&nbsp;</td>'; 
1513                         }
1514                         $this->t->set_var('part_table',$part_table);
1515                         $this->t->fp('list2','individual_list',True);
1516                 }
1517                 $this->t->set_var('total_width',$total_width);
1518                 $this->t->set_var('individual_width',$individual_width);
1519                 $this->t->set_var('part_width',$part_width);
1520                 $this->t->set_var('act_width',$act_width);
1521                 $this->t->pfp('out','par_view_t');
1522                 $this->save_sessiondata(); 
1523         }
1524
1525         function willing_view()
1526         {
1527                 $this->t->set_file(array('willing_view_t' => 'willing_view.tpl'));
1528                 $this->t->set_block('willing_view_t','header_list','list1');
1529                 $this->t->set_block('willing_view_t','individual_list','list2');
1530
1531                 $this->t->set_var('lang_filter','Filter');
1532                 $this->t->set_var('lang_filter_unwilling','Filter out unwilling individuals:');
1533
1534                 $filter_unwilling = get_var('filter_unwilling',array('POST'));
1535                 $this->t->set_var('filter_unwilling',$filter_unwilling);
1536
1537                 if($filter_unwilling == 'y' || $filter_unwilling == '') {
1538                         $filter_input = "<input type=\"radio\" name=\"filter_unwilling\" value=\"y\" checked>Y";
1539                         $filter_input.= "<input type=\"radio\" name=\"filter_unwilling\" value=\"n\">N";
1540                         $filter_input.= "&nbsp;&nbsp;";
1541                 } else {
1542                         $filter_input = "<input type=\"radio\" name=\"filter_unwilling\" value=\"y\">Y";
1543                         $filter_input.= "<input type=\"radio\" name=\"filter_unwilling\" value=\"n\" checked>N";
1544                         $filter_input.= "&nbsp;&nbsp;";
1545                 }
1546                 $this->t->set_var('filter_input',$filter_input);
1547
1548                 $sql = "SELECT * FROM tc_individual where steward='$this->default_stewardship' and valid=1";
1549                 $this->db->query($sql,__LINE__,__FILE__);
1550                 $i=0;
1551                 while ($this->db->next_record()) {
1552                         $indiv_name[$i] = $this->db->f('name');
1553                         $individual[$i] = $this->db->f('individual');
1554                         $indiv_phone[$individual[$i]] = $this->db->f('phone');
1555                         $i++;
1556                 }
1557                 array_multisort($indiv_name, $individual);
1558
1559                 $sql = "SELECT * FROM tc_assignment ORDER BY name ASC";
1560                 $this->db->query($sql,__LINE__,__FILE__);
1561                 $i=0;
1562                 while($this->db->next_record()) {
1563                         $assignment_list[$i]['assignment'] = $this->db->f('assignment');
1564                         $assignment_list[$i]['name'] = $this->db->f('name');
1565                         $assignment_list[$i]['abbreviation'] = $this->db->f('abbreviation');
1566                         $i++;
1567                 }
1568
1569                 $sql = "SELECT * FROM tc_activity ORDER BY date DESC";
1570                 $this->db->query($sql,__LINE__,__FILE__);
1571                 $total_records = $this->db->num_rows();
1572
1573                 $i = 0;
1574                 while ($this->db->next_record()) {
1575                         $activity_list[$i]['assignment'] = $this->db->f('assignment');
1576                         $activity_list[$i]['date'] = $this->db->f('date');
1577                         $activity_list[$i]['activity']  = $this->db->f('activity');
1578                         $i++;
1579                 }
1580
1581                 $indiv_width=275; $willing_width=40; $assignment_width=50;
1582                 $total_width=$indiv_width+$willing_width;
1583
1584                 for ($i=0; $i < count($assignment_list); $i++) {
1585                         $this->t->set_var('assignment_name',$assignment_list[$i]['name']);
1586                         $this->t->set_var('assignment_abbreviation',$assignment_list[$i]['abbreviation']);
1587                         $this->t->fp('list1','header_list',True);
1588                         $total_width += $assignment_width;
1589                         $total_willing[$i] = 0;
1590                 }
1591
1592                 for ($i=0; $i < count($individual); $i++) {
1593                         $willing_table = ''; $indiv_willing=0;
1594                         $this->t->set_var('individual_name',$indiv_name[$i]);
1595                         $this->t->set_var('individual_phone',$indiv_phone[$individual[$i]]);
1596                         $this->t->set_var('editurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.willing_update&individual=' .
1597                                           $individual[$i] . '&action=' . 'edit'));
1598                         for ($j=0; $j < count($assignment_list); $j++) {
1599                                 $found_willingness=0; 
1600                                 $sql = "SELECT * FROM tc_willingness where " .
1601                                        " assignment=" . $assignment_list[$j]['assignment'] .
1602                                        " AND individual=" . $individual[$i];
1603                                 $this->db->query($sql,__LINE__,__FILE__);
1604                                 while($this->db->next_record()) {
1605                                         $found_willingness=1;
1606                                         $date_part="";
1607                                         $sql = "SELECT * FROM tc_activity where " .
1608                                                " assignment=". $assignment_list[$j]['assignment'] .
1609                                                " ORDER by date DESC";
1610                                         $this->db2->query($sql,__LINE__,__FILE__);
1611                                         if($this->db2->next_record()) {
1612                                                 $activity = $this->db2->f('activity');
1613                                                 $date = $this->db2->f('date');
1614                                                 $sql = "SELECT * FROM tc_participation where " .
1615                                                        " activity=" . $activity .
1616                                                        " AND individual=". $individual[$i];
1617                                                 $this->db3->query($sql,__LINE__,__FILE__);
1618                                                 if($this->db3->next_record()) {
1619                                                         $date_part = $date;
1620                                                 } 
1621                                         }
1622
1623                                         if($this->db->f('willing') == 'y') {
1624                                                 $total_willing[$j]++;
1625                                                 $indiv_willing=1;
1626                                                 $willing_table .= '<td align=center><img src="images/checkmark.gif"><br><font size=-2>'.$date_part.'</font></td></td>';
1627                                         } else if($this->db->f('willing') == 'n') {
1628                                                 $willing_table .= '<td align=center><img src="images/x.gif"></td>';
1629                                         } else {
1630                                                 $indiv_willing=1;
1631                                                 $willing_table .= "<td>&nbsp;</td>";
1632                                         }
1633                                 }
1634                                 if(!$found_willingness) {
1635                                         $indiv_willing=1;
1636                                         $willing_table .= "<td>&nbsp;</td>";
1637                                 }
1638                         }
1639                         if(($indiv_willing == 1) || ($filter_unwilling == 'n')) { 
1640                                 $this->t->set_var('willing_table',$willing_table);
1641                                 $this->t->fp('list2','individual_list',True);
1642                                 $this->nextmatchs->template_alternate_row_color(&$this->t);
1643                         } 
1644                 }
1645
1646                 $stat_table = '<td><b>Total Willing to Serve</b></td>';
1647                 for ($j=0; $j < count($assignment_list); $j++) {
1648                         $stat_table .= "<td align=center><b>".$total_willing[$j]."</b></td>";
1649                 }
1650                 $this->t->set_var('stat_table',$stat_table);
1651
1652                 $this->t->set_var('total_width',$total_width);
1653                 $this->t->set_var('individual_width',$indiv_width);
1654                 $this->t->set_var('willing_width',$willing_width);
1655                 $this->t->pfp('out','willing_view_t');
1656                 $this->save_sessiondata(); 
1657         }
1658     
1659         function willing_update()
1660         {
1661                 //print "<font color=red>Willingness Update Under Constrcution</font>";
1662                 //$this->willing_view();
1663                 //return false;
1664
1665                 $this->t->set_file(array('willing_update_t' => 'willing_update.tpl'));
1666                 $this->t->set_block('willing_update_t','assignment_list','list');
1667                 $this->t->set_block('willing_update_t','save','savehandle');
1668
1669                 $individual = get_var('individual',array('GET','POST'));
1670                 $this->t->set_var('individual',$individual);
1671                 $action = get_var('action',array('GET','POST'));
1672
1673                 $this->t->set_var('done_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.willing_view'));
1674                 $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.willing_update&action=save'));
1675                 $this->t->set_var('lang_done','Cancel');
1676                 $this->t->set_var('title','Willingness Update ');
1677
1678                 if($action == 'save') {
1679                         // Delete all the previous willingness entries for this individual
1680                         $this->db->query("DELETE from tc_willingness where individual=" . $individual ,__LINE__,__FILE__);
1681
1682                         // Now, add the assignment willingness that is checked for this individual
1683                         $new_data = get_var('willingness',array('POST'));
1684                         foreach ($new_data as $data) {
1685                                 $data_array = explode("/",$data);
1686                                 $assignment = $data_array[0];
1687                                 $willing = $data_array[1];
1688                                 //print "individual: $individual assignment: $assignment willing: $willing<br>";
1689                                 $this->db->query("INSERT INTO tc_willingness (individual,assignment,willing) " .
1690                                                  "VALUES (" . $individual .",". $assignment .",'". $willing . "')",__LINE__,__FILE__);
1691                         }      
1692                         $this->willing_view();
1693                         return false;
1694                 }
1695
1696                 $assignment_width=300; $willing_width=25; $table_width=$assignment_width + $willing_width;
1697                 $table_data=""; 
1698
1699                 // Find out the individual's name
1700                 $sql = "SELECT * FROM tc_individual WHERE individual=".$individual." AND valid=1";
1701                 $this->db->query($sql,__LINE__,__FILE__);
1702                 if($this->db->next_record()) {
1703                         $indiv_name = $this->db->f('name');
1704                         $this->t->set_var('individual_name',$indiv_name);
1705                 }
1706
1707                 // Select all the assignments
1708                 $sql = "SELECT * FROM tc_assignment ORDER by name ASC";
1709                 $this->db->query($sql,__LINE__,__FILE__);
1710
1711                 while ($this->db->next_record()) {
1712                         $assignment = $this->db->f('assignment');
1713                         $assignment_name = $this->db->f('name');
1714                         $assignment_abbreviation = $this->db->f('abbreviation');
1715
1716                         $this->nextmatchs->template_alternate_row_color(&$this->t);
1717                         $table_data.="<tr bgcolor=". $this->t->get_var('tr_color') ."><td>$assignment_name</td>";
1718
1719                         $header_row="<th width=$comp_width><font size=-2>Assignments</th><th>Willingness</th>";
1720                         $sql = "SELECT * FROM tc_willingness WHERE individual=".$individual." AND assignment=".$assignment;
1721                         $this->db2->query($sql,__LINE__,__FILE__);
1722                         $value = $assignment;
1723
1724                         if($this->db2->next_record()) {
1725                                 if($this->db2->f('willing') == 'y') {
1726                                         $table_data .= '<td width=100 align=center>';
1727                                         $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/y" checked>Y';
1728                                         $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/n">N';
1729                                         $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/"> ';
1730                                         $table_data .= '</td>';
1731                                 } else if($this->db2->f('willing') == 'n') {
1732                                         $table_data .= '<td width=100 align=center>';
1733                                         $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/y">Y';
1734                                         $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/n" checked>N';
1735                                         $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/">';
1736                                         $table_data .= '</td>';
1737                                 } else {
1738                                         $table_data .= '<td width=100 align=center>';
1739                                         $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/y">Y';
1740                                         $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/n">N';
1741                                         $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/" checked> ';
1742                                         $table_data .= '</td>';
1743                                 }
1744                         } else {
1745                                 $table_data .= '<td width=100 align=center>';
1746                                 $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/y">Y';
1747                                 $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/n">N';
1748                                 $table_data .= '<input type="radio" name="willingness['.$assignment.']" value="'.$value.'/" checked> ';
1749                                 $table_data .= '</td>';
1750                         }
1751
1752                         $table_data .= "\n";
1753                         $table_data .= "</tr>"; 
1754                         $table_data .= "<tr><td colspan=20></td></tr>";
1755                 }
1756
1757                 $table_data .= "<tr><td colspan=20><hr></td></tr>";
1758
1759                 $this->t->set_var('table_width',$table_width);
1760                 $this->t->set_var('header_row',$header_row);
1761                 $this->t->set_var('table_data',$table_data);
1762                 $this->t->fp('list','assignment_list',True);
1763
1764                 $this->t->set_var('lang_reset','Clear Form');
1765                 $this->t->set_var('lang_save','Save Changes');
1766                 $this->t->set_var('savehandle','');
1767
1768                 $this->t->pfp('out','willing_update_t');
1769                 $this->t->pfp('addhandle','save');
1770
1771                 $this->save_sessiondata();
1772         }
1773
1774
1775         function ppi_sched()
1776         {
1777                 $this->t->set_file(array('ppi_sched_t' => 'ppi_sched.tpl'));
1778                 $this->t->set_block('ppi_sched_t','individual_list','indivlist');
1779                 $this->t->set_block('ppi_sched_t','appt_list','apptlist');
1780                 $action = get_var('action',array('GET','POST'));
1781
1782                 $this->t->set_var('lang_save','Save Appt / Pri / Notes');
1783                 $this->t->set_var('lang_reset','Clear Changes');
1784
1785                 $this->t->set_var('ppi_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_view'));
1786                 $this->t->set_var('ppi_link_title',$this->ppi_frequency_label . ' PPIs');
1787
1788                 $this->t->set_var('schedule_ppi_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_sched'));
1789                 $this->t->set_var('schedule_ppi_link_title','Schedule ' . $this->ppi_frequency_label . ' PPIs');
1790
1791                 $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_sched&action=save'));
1792                 $this->t->set_var('title',$this->ppi_frequency_label . ' PPI Scheduler');
1793
1794                 $header_row = "<th ><font size=-2>Individual Name</th>";
1795                 $header_row.= "<th><font size=-2>Phone</th>";
1796                 $header_row.= "<th><font size=-2>Priority</th>";
1797                 $header_row.= "<th><font size=-2>Last PPI</th>";
1798                 $header_row.= "<th><font size=-2>Scheduling Notes</th>";
1799                 $table_data=""; $completed_data=""; $totals_data="";
1800
1801                 $year = date('Y');
1802                 $month = date('m');
1803                 $period = intval(($month-1)/$this->ppi_frequency) + 1;
1804                 $start_of_period = ($period-1)*$this->ppi_frequency + 1;
1805                 $end_of_period = $period * $this->ppi_frequency;
1806
1807                 if($action == 'save') {
1808                         // Save any changes made to the appointment table
1809                         $new_data = get_var('appt_notes',array('POST'));
1810                         if($new_data != "") {
1811                                 foreach ($new_data as $entry) {
1812                                         $indiv = $entry['individual'];
1813                                         $appointment = $entry['appointment'];
1814                                         $location = $entry['location'];
1815                                     $presidency_location = $entry['presidency_location'];
1816                                     if($location == "") { $location = $presidency_location; }
1817                                         if($indiv == 0) { $location = ""; }
1818
1819                                         //Only perform a database update if we have made a change to this appointment
1820                                         $sql = "SELECT * FROM tc_appointment where appointment='$appointment' and individual='$indiv' and location='$location'";
1821                                         $this->db->query($sql,__LINE__,__FILE__);
1822                                         if(!$this->db->next_record()) {
1823                                                 // Perform database save actions here
1824                                                 $this->db->query("UPDATE tc_appointment set " .
1825                                                                  " individual='" . $indiv . "'" .
1826                                                                  ",location='" . $location . "'" .
1827                                                                  " WHERE appointment=" . $appointment,__LINE__,__FILE__);
1828                                                 // Email the appointment
1829                                                 $this->email_appt($appointment);
1830                                         }
1831                                 }
1832                         }
1833
1834                         // Save any changes made to the ppi notes table
1835                         $new_data = get_var('notes',array('POST'));
1836                         foreach ($new_data as $entry) {
1837                                 $notes = $entry['notes'];
1838                                 $individual = $entry['individual'];
1839                                 $priority = $entry['pri'];
1840
1841                                 // Perform database save actions here
1842                                 $sql = "SELECT * FROM tc_individual WHERE individual='$individual'";
1843                                 $this->db->query($sql,__LINE__,__FILE__);
1844                                 if ($this->db->next_record()) {
1845                                         $scheduling_priority = $this->db->f('scheduling_priority');
1846                                         //$this->logToFile("ppi_sched", "UPDATE tc_scheduling_priority SET priority='$priority', notes=\"$notes\" WHERE scheduling_priority='$scheduling_priority'");
1847                                         $this->db2->query("UPDATE tc_scheduling_priority SET priority='$priority', notes=\"$notes\" WHERE scheduling_priority='$scheduling_priority'", __LINE__, __FILE__);
1848                                 }
1849                         }
1850
1851                         $take_me_to_url = $GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_sched');
1852                         //Header('Location: ' . $take_me_to_url);
1853                 }
1854
1855                 // create the individual id -> individual name mapping
1856                 $sql = "SELECT * FROM tc_individual where valid=1 and steward='$this->default_stewardship' ORDER BY name ASC";
1857                 $this->db->query($sql,__LINE__,__FILE__);
1858                 $i=0;
1859                 $individual = NULL;
1860                 $indiv_name = NULL;
1861                 while ($this->db->next_record()) {
1862                         $indiv_name[$i] = $this->db->f('name');
1863                         $individual[$i] = $this->db->f('individual');
1864                         $i++;
1865                 }
1866                 array_multisort($indiv_name, $individual);
1867
1868                 // APPOINTMENT TABLE
1869                 $appt_header_row = "<th><font size=-2>Date</th>";
1870                 $appt_header_row.= "<th><font size=-2>Time</th>";      
1871                 $appt_header_row.= "<th><font size=-2>Individual</th>";
1872                 $appt_header_row.= "<th><font size=-2>Location</th>";
1873                 $appt_table_data = "";
1874                 $table_data="";
1875
1876                 $total_indivs=0; $indivs_with_yearly_ppi=0;
1877
1878                 // Get the President
1879                 $sql = "SELECT * FROM tc_presidency AS tp JOIN tc_individual AS ti where tp.individual=ti.individual AND tp.valid=1 AND ";
1880                 if($this->yearly_ppi_interviewer == 1) { $sql .= " (tp.president=1)"; }
1881                 if($this->yearly_ppi_interviewer == 2) { $sql .= " (tp.president=1 OR tp.counselor=1)"; }
1882                 if($this->yearly_ppi_interviewer == 3) { $sql .= " (tp.president=1 OR tp.counselor=1 OR tp.secretary=1)"; }
1883                 $this->db->query($sql,__LINE__,__FILE__);
1884                 while ($this->db->next_record()) {
1885                   $presidency_name = $this->db->f('name');
1886                   $presidency_name_array = explode(",",$presidency_name);
1887                   $presidency_last_name = $presidency_name_array[0];
1888                   $presidency_id = $this->db->f('presidency');
1889                   $presidency_address = $this->db->f('address');
1890                   $presidency_location = "$presidency_last_name"." home ($presidency_address)";
1891                   $appt_table_data = "";
1892
1893                   // Display a scheduling table for this presidency member
1894                   $not_completed_table_title = "All individuals with " . $this->ppi_frequency_label . " PPI Not Completed";
1895                   $appt_table_title = $presidency_name . ": " . $this->ppi_frequency_label." PPI Appointment Slots";
1896                   $this->t->set_var('not_completed_table_title',$not_completed_table_title);
1897                   $this->t->set_var('appt_table_title',$appt_table_title);
1898
1899                   // query the database for all the appointments
1900                   $sql = "SELECT * FROM tc_appointment where presidency=".$presidency_id." and date>=CURDATE() ORDER BY date ASC, time ASC";
1901                   $this->db2->query($sql,__LINE__,__FILE__);
1902
1903                   while ($this->db2->next_record()) {
1904                         $appointment = $this->db2->f('appointment');
1905                         $indiv = $this->db2->f('individual');
1906                         $location = $this->db2->f('location');
1907                         if(($location == "") && ($indiv > 0)) { $location = $presidency_location; }
1908
1909                         $date = $this->db2->f('date');
1910                         $date_array = explode("-",$date);
1911                         $year = $date_array[0]; $month = $date_array[1]; $day = $date_array[2];
1912                         $day_string = date("l d-M-Y", mktime(0,0,0,$month,$day,$year));
1913
1914                         $time = $this->db2->f('time');
1915                         $time_array = explode(":",$time);
1916                         $time_string = date("g:i a", mktime($time_array[0], $time_array[1], $time_array[2]));
1917
1918                         $appt_table_data.= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
1919                         $appt_table_data.= "<td align=center>$day_string</td>";
1920                         $appt_table_data.= "<td align=center>$time_string</td>";
1921
1922                         $appt_table_data.= '<td align=center><select name=appt_notes['.$appointment.'][individual]>';
1923                         $appt_table_data.= '<option value=0></option>';
1924                         for ($i=0; $i < count($individual); $i++) {
1925                           $id = $individual[$i];
1926                           $name = $indiv_name[$i];
1927                           if($individual[$i] == $indiv) { 
1928                                 $selected[$id] = 'selected="selected"'; 
1929                           } else { 
1930                                 $selected[$id] = ''; 
1931                           }
1932                           $appt_table_data.= '<option value='.$id.' '.$selected[$id].'>'.$name.'</option>';
1933                         }
1934                         $appt_table_data.='</select></td>';
1935
1936                         $appt_table_data.= '<td align=center><input type=text size="35" maxlength="120" ';
1937                         $appt_table_data.= 'name="appt_notes['.$appointment.'][location]" value="'.$location.'">';
1938
1939                         $appt_table_data.= '<input type=hidden name="appt_notes['.$appointment.'][appointment]" value="'.$appointment.'">';
1940
1941                         $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
1942                         $this->t->set_var('tr_color',$tr_color);
1943                   }
1944                   $this->t->set_var('appt_table_data',$appt_table_data);
1945                   $this->t->set_var('appt_header_row',$appt_header_row);
1946                   $this->t->set_var('lang_save','Save Appts for ' . $presidency_name);
1947
1948                   $this->t->fp('apptlist','appt_list',True);
1949                 }
1950                 
1951                 // PPI SCHEDULING TABLE
1952                 $sql = "SELECT * FROM tc_individual AS ti JOIN tc_scheduling_priority AS tsp WHERE ti.scheduling_priority=tsp.scheduling_priority AND steward='$this->default_stewardship' AND valid=1 ORDER BY tsp.priority ASC, ti.name ASC";
1953                 $this->db->query($sql,__LINE__,__FILE__);
1954
1955                 $i=0; 
1956                 $individual = NULL;
1957                 while ($this->db->next_record()) {
1958                         $individual[$i] = $this->db->f('individual');
1959                         $indiv_name[$i] = $this->db->f('name');
1960                         $indiv_phone[$individual[$i]] = $this->db->f('phone');
1961                         $indiv_priority[$individual[$i]] = $this->db->f('priority');
1962                         $indiv_notes[$individual[$i]] = $this->db->f('notes');
1963                         $i++;
1964                         $total_indivs++;
1965                 }
1966
1967                 $max = count($individual);
1968                 
1969                 for($i=0; $i < $max; $i++) {
1970                         $id = $individual[$i];
1971                         $name = $indiv_name[$i];
1972                         $phone = $indiv_phone[$id];
1973                         $priority = $indiv_priority[$id];
1974                         $notes = $indiv_notes[$id];
1975
1976                         // If this individual has had a PPI this period, don't show him on the schedule list
1977                         $year_start = $year . "-" . $start_of_period . "-01";
1978                         $year_end = $year . "-" . $end_of_period . "-31";
1979                         $sql = "SELECT * FROM tc_interview WHERE date >= '$year_start' AND date <= '$year_end' ".
1980                                "AND individual=" . $id . " AND interview_type='ppi' ORDER BY date DESC";
1981                         $this->db2->query($sql,__LINE__,__FILE__);
1982
1983                         if(!$this->db2->next_record()) {
1984                                 $sql = "SELECT * FROM tc_interview WHERE individual=" . $id . " AND interview_type='ppi' ORDER BY date DESC";
1985                                 $this->db->query($sql,__LINE__,__FILE__);
1986                                 if($this->db->next_record()) { 
1987                                         $date = $this->db->f('date'); 
1988                                 } else { 
1989                                         $date = ""; 
1990                                 }
1991                                 $link_data['menuaction'] = 'tc.tc.ppi_update';
1992                                 $link_data['individual'] = $id;
1993                                 $link_data['name'] = $name;
1994                                 $link_data['interview'] = '';
1995                                 $link_data['interview_type'] = 1;
1996                                 $link_data['action'] = 'add';
1997                                 $link_data['interviewer'] = $interviewer;
1998                                 $link = $GLOBALS['phpgw']->link('/tc/index.php',$link_data);
1999                                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
2000                                 $this->t->set_var('tr_color',$tr_color);
2001                                 $table_data.= "<tr bgcolor=". $this->t->get_var('tr_color') ."><td title=\"$phone\"><a href=$link>$name</a></td>";
2002                                 $table_data.= "<td align=center>$phone</td>";
2003                                 //$table_data.= "<td align=center>$priority</td>";
2004                                 $table_data.= "<td align=center>";
2005                                 $table_data.= '<select name=notes['.$i.'][pri]>';
2006                                 foreach(range(0,6) as $num) {
2007                                         if($num == 0) { $num = 1; } else {$num = $num*5; }
2008                                         if($priority == $num) { 
2009                                                 $selected[$num] = 'selected="selected"'; 
2010                                         } else { 
2011                                                 $selected[$num] = ''; 
2012                                         }
2013                                         $table_data.= '<option value='.$num.' '.$selected[$num].'>'.$num.'</option>';
2014                                 }
2015                                 $table_data.= '</select></td>';
2016                                 $table_data.= "<td align=center>$date</td>";
2017                                 $table_data.= '<td><input type=text size="50" maxlength="128" name="notes['.$i.'][notes]" value="'.$notes.'">';
2018                                 $table_data.= '<input type=hidden name="notes['.$i.'][individual]" value="'.$id.'">';
2019                                 $table_data.= '<input type=hidden name="notes['.$i.'][indiv_name]" value="'.$name.'">';
2020                                 $table_data.= '</td>';
2021                                 $table_data.= '</tr>';
2022                         } else {
2023                                 $link_data['menuaction'] = 'tc.tc.ppi_update';
2024                                 $link_data['interviewer'] = $this->db2->f('interviewer');
2025                                 $link_data['individual'] = $this->db2->f('individual');
2026                                 $link_data['name'] = $name;
2027                                 $link_data['interview'] = $this->db2->f('interview');
2028                                 $link_data['interview_type'] = $this->db2->f('interview_type');
2029                                 $link_data['action'] = 'view';
2030                                 $link = $GLOBALS['phpgw']->link('/tc/index.php',$link_data);    
2031                                 $indivs_with_yearly_ppi++;
2032                                 $date = $this->db2->f('date');
2033                                 $notes = $this->db2->f('notes');
2034                                 if(strlen($notes) > 40) { $notes = substr($notes,0,40) . "..."; }
2035                                 $tr_color2 = $this->nextmatchs->alternate_row_color($tr_color2);
2036                                 $this->t->set_var('tr_color2',$tr_color2);
2037                                 $completed_data.= "<tr bgcolor=". $this->t->get_var('tr_color2') ."><td title=\"$phone\"><a href=$link>$name</a></td>";
2038                                 $completed_data.= "<td align=center>$phone</td>";
2039                                 $completed_data.= "<td align=center><a href=".$link.">$date</a></td>";
2040                                 $completed_data.= "<td align=left>$notes</td>";
2041                                 $completed_data.= '</tr>';
2042                         }
2043                 } // End for individuals Loop
2044
2045                 $completed_table_title = "All individuals with " . $this->ppi_frequency_label . " PPI Completed";
2046                 $completed_header_row = "<th><font size=-2>Individual</th>";
2047                 $completed_header_row.= "<th><font size=-2>Phone</th>";      
2048                 $completed_header_row.= "<th><font size=-2>Date</th>";
2049                 $completed_header_row.= "<th><font size=-2>PPI Notes</th>";
2050
2051                 $this->t->set_var('completed_table_title',$completed_table_title);
2052                 $this->t->set_var('header_row',$header_row);
2053                 $this->t->set_var('table_data',$table_data);
2054                 $this->t->set_var('completed_header_row',$completed_header_row);
2055                 $this->t->set_var('completed',$completed_data);
2056                 $this->t->set_var('lang_save','Save Pri / Notes'); 
2057                 $this->t->fp('indivlist','individual_list',True); 
2058
2059                 $totals_header_row = "<th><font size=-2>Individuals</th>";
2060                 $totals_header_row.= "<th><font size=-2>$year</th>";
2061                 $totals_data.= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
2062                 $totals_data.= "<td align=left><font size=-2><b>Total Individuals with " . $this->ppi_frequency_label . " PPIs completed:</b></font></td>";
2063                 $totals_data.= "<td align=center><font size=-2><b>$indivs_with_yearly_ppi / $total_indivs</b></font></td>";
2064                 $percent = ceil(($indivs_with_yearly_ppi / $total_indivs)*100);
2065                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
2066                 $this->t->set_var('tr_color',$tr_color);
2067                 $totals_data.= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
2068                 $totals_data.= "<td align=left><font size=-2><b>Percentage:</b></font></td>";
2069                 $totals_data.= "<td align=center><font size=-2><b>$percent%</b></font></td>";
2070                 $totals_data.= "</tr>";
2071
2072                 $this->t->set_var('totals',$totals_data);
2073                 $this->t->set_var('totals_header_row',$totals_header_row);
2074                 $this->t->set_var('ppi_frequency_label',$this->ppi_frequency_label);
2075
2076                 $this->t->pfp('out','ppi_sched_t');
2077                 $this->save_sessiondata(); 
2078
2079         }
2080   
2081         function int_sched()
2082         {
2083                 $this->t->set_file(array('int_sched_t' => 'int_sched.tpl'));
2084                 $this->t->set_block('int_sched_t','individual_list','indivlist');
2085                 $this->t->set_block('int_sched_t','appt_list','apptlist');
2086                 $action = get_var('action',array('GET','POST'));
2087
2088                 $this->t->set_var('lang_reset','Clear Changes');
2089
2090                 $this->t->set_var('int_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_view'));
2091                 $this->t->set_var('int_link_title','Hometeaching Interviews');
2092
2093                 $this->t->set_var('schedule_int_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_sched'));
2094                 $this->t->set_var('schedule_int_link_title','Schedule Hometeaching Interviews');
2095
2096                 $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_sched&action=save'));
2097                 $this->t->set_var('title','Hometeaching Interviews Scheduler');
2098
2099                 $header_row = "<th><font size=-2>Individual</th>";
2100                 $header_row.= "<th><font size=-2>Phone</th>";
2101                 $header_row.= "<th><font size=-2>Priority</th>";
2102                 $header_row.= "<th><font size=-2>Last Interview</th>";
2103                 $header_row.= "<th><font size=-2>Scheduling Notes</th>";
2104                 $table_data=""; $completed_data=""; $totals_data="";
2105
2106                 $year = date('Y');
2107                 $month = date('m');
2108                 $nextyear = $year + 1;
2109                 if($month >= 1 && $month <= 3) { $quarter_start=$year."-01-01"; $quarter_end=$year."-04-01"; }
2110                 if($month >= 4 && $month <= 6) { $quarter_start=$year."-04-01"; $quarter_end=$year."-07-01"; }
2111                 if($month >= 7 && $month <= 9) { $quarter_start=$year."-07-01"; $quarter_end=$year."-10-01"; }
2112                 if($month >= 10 && $month <= 12) { $quarter_start=$year."-10-01"; $quarter_end=$nextyear."-01-01"; }
2113                 //print "year: $year month: $month quarter_start: $quarter_start quarter_end: $quarter_end<br>";
2114
2115                 // create the individual id -> individual name mapping
2116                 $sql = "SELECT * FROM tc_individual where steward='$this->default_stewardship' and valid=1 ORDER BY name ASC";
2117                 $this->db->query($sql,__LINE__,__FILE__);
2118                 $i=0;
2119                 $individual_data = NULL;
2120                 $indiv_name_data = NULL;
2121                 while ($this->db->next_record()) {
2122                         $indiv_name_data[$i] = $this->db->f('name');
2123                         $individual_data[$i] = $this->db->f('individual');
2124                         $individ2name[$individual_data[$i]] = $indiv_name_data[$i];
2125                         $i++;
2126                 }
2127                 // add any YM that are home teachers
2128                 $sql = "SELECT * FROM tc_companionship where valid=1";
2129                 $this->db->query($sql,__LINE__,__FILE__);
2130                 while ($this->db->next_record()) {
2131                         $tmp_individual = $this->db->f('individual');
2132                         $sql = "Select * FROM tc_individual where individual='$tmp_individual' and steward='' and valid=1";
2133                         $this->db2->query($sql,__LINE__,__FILE__);
2134                         while ($this->db2->next_record()) {
2135                                 $indiv_name_data[$i] = $this->db2->f('name');
2136                                 $individual_data[$i] = $this->db2->f('individual');
2137                                 $individ2name[$individual_data[$i]] = $indiv_name_data[$i];
2138                                 $i++;
2139                         }
2140                 }
2141                 array_multisort($indiv_name_data, $individual_data);
2142
2143                 if($action == 'save') {
2144                         // Save any changes made to the appointment table
2145                         $new_data = get_var('appt_notes',array('POST'));
2146                         if($new_data != "") {
2147                                 foreach ($new_data as $entry) {
2148                                         $indiv = $entry['individual'];
2149                                         $appointment = $entry['appointment'];
2150                                         $location = $entry['location'];
2151                                         if($location == "") {
2152                                                 $supervisor = $entry['supervisor'];
2153                                                 $supervisor_array = explode(",", $individ2name[$supervisor]);
2154                                                 $supervisor_last_name = $supervisor_array[0];
2155                                                 $sql = "SELECT * FROM tc_individual where individual='$supervisor'";
2156                                                 $this->db2->query($sql,__LINE__,__FILE__);
2157                                                 if($this->db2->next_record()) {
2158                                                         $supervisor_address = $this->db2->f('address');
2159                                                 }
2160                                                 $location = "$supervisor_last_name"." home ($supervisor_address)";
2161                                         }
2162                                         if($indiv == 0) { $location = ""; }
2163
2164                                         //print "indiv: $indiv appointment: $appointment <br>";
2165                                         //Only perform a database update if we have made a change to this appointment
2166                                         $sql = "SELECT * FROM tc_appointment where appointment='$appointment' and individual='$indiv' and location='$location'";
2167                                         $this->db->query($sql,__LINE__,__FILE__);
2168                                         if(!$this->db->next_record()) {
2169                                                 // Perform database save actions here
2170                                                 $this->db->query("UPDATE tc_appointment set " .
2171                                                                  " individual='" . $indiv . "'" .
2172                                                                  ",location='" . $location . "'" .
2173                                                                  " WHERE appointment=" . $appointment,__LINE__,__FILE__);
2174                                                 // Email the appointment
2175                                                 $this->email_appt($appointment);
2176                                         }
2177                                 }
2178                         }
2179
2180                         // Save any changes made to the int notes table
2181                         $new_data = get_var('hti_notes',array('POST'));
2182                         foreach ($new_data as $entry) {
2183                                 $hti_notes = $entry['notes'];
2184                                 $individual = $entry['individual'];
2185                                 $indiv_name = $entry['indiv_name'];
2186                                 $hti_pri = $entry['pri'];
2187                                 //print "hti_notes: $hti_notes indiv_name: $indiv_name <Br>";
2188                                 // Perform database save actions here
2189                                 $this->db->query("SELECT * FROM tc_companion WHERE individual=$individual and valid=1",__LINE__,__FILE__);
2190                                 if ($this->db->next_record()) {
2191                                         $scheduling_priority = $this->db->f('scheduling_priority');
2192                                         //$this->logToFile("int_sched", "UPDATE tc_scheduling_priority SET priority='$hti_pri', notes=\"$hti_notes\" WHERE scheduling_priority='$scheduling_priority'");
2193                                         $this->db2->query("UPDATE tc_scheduling_priority SET priority='$hti_pri', notes=\"$hti_notes\" WHERE scheduling_priority='$scheduling_priority'",__LINE__,__FILE__);
2194                                 }
2195                         }
2196
2197                         $take_me_to_url = $GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_sched');
2198                         //Header('Location: ' . $take_me_to_url);
2199                 }
2200
2201                 // Get the Districts
2202                 $sql = "SELECT * FROM tc_district AS td JOIN (tc_presidency AS tp, tc_individual AS ti) WHERE td.district=tp.district AND td.supervisor=ti.individual AND td.valid=1 ORDER BY td.district ASC";
2203                 $this->db->query($sql,__LINE__,__FILE__);
2204                 $i=0;
2205                 while ($this->db->next_record()) {
2206                         $district = $this->db->f('district');
2207                         $districts[$i]['district'] = $this->db->f('district');
2208                         $districts[$i]['name'] = $this->db->f('name');
2209                         $districts[$i]['supervisor'] = $this->db->f('supervisor');
2210                         $districts[$i]['presidency'] = $this->db->f('presidency');
2211                         $i++;
2212                 }
2213
2214                 // APPOINTMENT TABLE
2215                 $district = 1;
2216                 $appt_header_row = "<th><font size=-2>Date</th>";
2217                 $appt_header_row.= "<th><font size=-2>Time</th>";      
2218                 $appt_header_row.= "<th><font size=-2>Individual</th>";
2219                 $appt_header_row.= "<th><font size=-2>Location</th>";
2220                 $appt_table_data = ""; 
2221
2222                 $total_comps=0; $comps_with_quarterly_int=0;
2223
2224                 // Display a scheduling table for each district
2225                 for ($d=0; $d < count($districts); $d++) {
2226                         $table_data=""; $appt_table_data="";
2227                         $this->t->set_var('district_number',$districts[$d]['district']);
2228                         $this->t->set_var('district_name',$districts[$d]['name']);      
2229                         $supervisor = $districts[$d]['supervisor'];
2230                         $supervisor_array = explode(",", $supervisor);
2231                         $supervisor_last_name = $supervisor_array[0];
2232                         $sql = "SELECT * FROM tc_individual where individual='$supervisor'";
2233                         $this->db2->query($sql,__LINE__,__FILE__);
2234                         if($this->db2->next_record()) {
2235                                 $supervisor_address = $this->db2->f('address');
2236                         }
2237                         $location = "$supervisor_last_name"." home ($supervisor_address)";
2238                         $table_title = "District ".$districts[$d]['district'].": ".$districts[$d]['name'].": All Individuals with Interviews Not Completed";
2239                         $appt_table_title = "District ".$districts[$d]['district'].": ".$districts[$d]['name'].": Interview Appointment Slots";
2240                         $this->t->set_var('table_title',$table_title);
2241                         $this->t->set_var('appt_table_title',$appt_table_title);
2242
2243                         // query the database for all the appointments
2244                         $sql = "SELECT * FROM tc_appointment where presidency=".$districts[$d]['presidency']." and date>=CURDATE() ORDER BY date ASC, time ASC";
2245                         $this->db->query($sql,__LINE__,__FILE__);
2246
2247                         while ($this->db->next_record()) {
2248                                 $appointment = $this->db->f('appointment');
2249                                 $indiv = $this->db->f('individual');
2250                                 $location = $this->db->f('location');
2251                                 if(($location == "") && ($indiv > 0)) { $location = "$supervisor_last_name"." home ($supervisor_address)"; }
2252
2253                                 $date = $this->db->f('date');
2254                                 $date_array = explode("-",$date);
2255                                 $year = $date_array[0]; $month = $date_array[1]; $day = $date_array[2];
2256                                 $day_string = date("l d-M-Y", mktime(0,0,0,$month,$day,$year));
2257
2258                                 $time = $this->db->f('time');
2259                                 $time_array = explode(":",$time);
2260                                 $time_string = date("g:i a", mktime($time_array[0], $time_array[1], $time_array[2]));
2261
2262                                 $appt_table_data.= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
2263                                 $appt_table_data.= "<td align=center>$day_string</td>";
2264                                 $appt_table_data.= "<td align=center>$time_string</td>";
2265
2266                                 $appt_table_data.= '<td align=center><select name=appt_notes['.$appointment.'][individual]>';
2267                                 $appt_table_data.= '<option value=0></option>';
2268                                 for ($i=0; $i < count($individual_data); $i++) {
2269                                         $id = $individual_data[$i];
2270                                         $name = $indiv_name_data[$i];
2271                                         if($individual_data[$i] == $indiv) { 
2272                                                 $selected[$id] = 'selected="selected"'; 
2273                                         } else { 
2274                                                 $selected[$id] = ''; 
2275                                         }
2276                                         $appt_table_data.= '<option value='.$id.' '.$selected[$id].'>'.$name.'</option>';
2277                                 }
2278                                 $appt_table_data.='</select></td>';
2279
2280                                 $appt_table_data.= '<td align=center><input type=text size="35" maxlength="120" ';
2281                                 $appt_table_data.= 'name="appt_notes['.$appointment.'][location]" value="'.$location.'">';
2282
2283                                 $appt_table_data.= '<input type=hidden name="appt_notes['.$appointment.'][appointment]" value="'.$appointment.'">';
2284                                 $appt_table_data.= '<input type=hidden name="appt_notes['.$appointment.'][supervisor]" value="'.$supervisor.'">';
2285
2286                                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
2287                                 $this->t->set_var('tr_color',$tr_color);
2288                         }
2289
2290                         $this->t->set_var('appt_table_data',$appt_table_data);
2291                         $this->t->set_var('appt_header_row',$appt_header_row);
2292
2293                         // INTERVIEW SCHEDULING TABLE
2294
2295                         // Select all the unique companionship numbers for this district
2296                         $sql = "SELECT distinct companionship FROM tc_companionship where valid=1 and district=". $districts[$d]['district'];
2297                         $this->db->query($sql,__LINE__,__FILE__);
2298                         $j=0; $unique_companionships = '';
2299                         while ($this->db->next_record())
2300                         {
2301                                 $unique_companionships[$j]['companionship'] = $this->db->f('companionship');
2302                                 $j++;
2303                         }
2304
2305                         $i=0;
2306                         for ($j=0; $j < count($unique_companionships); $j++) {
2307                                 // Select all the companions from each companionship
2308                                 $sql = "SELECT * FROM tc_companion AS tc JOIN (tc_scheduling_priority AS tsp, tc_individual AS ti) WHERE tc.scheduling_priority=tsp.scheduling_priority AND tc.individual=ti.individual AND tc.valid=1 AND tc.companionship=". $unique_companionships[$j]['companionship'];
2309                                 $this->db->query($sql,__LINE__,__FILE__);
2310                                 $k=0; $int_completed=0;
2311                                 $comp = $unique_companionships[$j]['companionship'];
2312                                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
2313                                 $this->t->set_var('tr_color',$tr_color);
2314                                 $total_comps++;
2315                                 while ($this->db->next_record()) {
2316                                         // Get this companions information
2317                                         $individual = $this->db->f('individual');
2318
2319                                         $id = $this->db->f('individual');
2320                                         $name = $this->db->f('name');
2321                                         $phone = $this->db->f('phone');
2322                                         $hti_pri = $this->db->f('priority');
2323                                         $hti_notes = $this->db->f('notes');
2324
2325                                         // If the companionship has already had its quarterly interview,
2326                                         // Skip the other companion in the companionship.
2327                                         if($int_completed == 1) {
2328                                                 $completed_data.= "<tr bgcolor=". $this->t->get_var('tr_color2') ."><td title=\"$phone\"><a href=$link>$name</a></td>";
2329                                                 $completed_data.= "<td align=center>$phone</td>";
2330                                                 $completed_data.= "<td align=center><a href=".$link.">$date</a></td>";
2331                                                 $completed_data.= "<td align=left>$hti_notes</td>";
2332                                                 $completed_data.= '</tr>';
2333                                                 $tr_color2 = $this->nextmatchs->alternate_row_color($tr_color2);
2334                                                 $this->t->set_var('tr_color2',$tr_color2);
2335                                                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
2336                                                 $this->t->set_var('tr_color',$tr_color);
2337                                                 continue;
2338                                         }
2339
2340                                         // If this companionship has had a hometeaching interview this quarter, don't show them on the schedule list
2341                                         $sql = "SELECT * FROM tc_interview WHERE date >= '$quarter_start' AND date < '$quarter_end' AND individual='$id' AND interview_type='hti'";
2342                                         $this->db2->query($sql,__LINE__,__FILE__);
2343
2344                                         if(!$this->db2->next_record()) {
2345                                                 $sql = "SELECT * FROM tc_interview WHERE individual='$id' AND interview_type='hti' ORDER BY date DESC";
2346                                                 $this->db3->query($sql,__LINE__,__FILE__);
2347                                                 if($this->db3->next_record()) { 
2348                                                         $date = $this->db3->f('date'); 
2349                                                 } else { 
2350                                                         $date = ""; 
2351                                                 }
2352                                                 $link_data['menuaction'] = 'tc.tc.int_update';
2353                                                 $link_data['individual'] = $id;
2354                                                 $link_data['name'] = $name;
2355                                                 $link_data['interview'] = '';
2356                                                 $link_data['action'] = 'add';
2357                                                 $link_data['interview_type'] = 'hti';
2358                                                 $link_data['interviewer'] = $districts[$d]['supervisor'];
2359                                                 $link = $GLOBALS['phpgw']->link('/tc/index.php',$link_data);
2360                                                 $table_data.= "<tr bgcolor=". $this->t->get_var('tr_color') ."><td title=\"$phone\"><a href=$link>$name</a></td>";
2361                                                 $table_data.= "<td align=center>$phone</td>";
2362                                                 $table_data.= "<td align=center>";
2363                                                 $table_data.= '<select name=hti_notes['.$i.'][pri]>';
2364                                                 foreach(range(0,6) as $num) {
2365                                                         if($num == 0) { $num = 1; } else {$num = $num*5; }
2366                                                         if($hti_pri == $num) { 
2367                                                                 $selected[$num] = 'selected="selected"'; 
2368                                                         } else { 
2369                                                                 $selected[$num] = ''; 
2370                                                         }
2371                                                         $table_data.= '<option value='.$num.' '.$selected[$num].'>'.$num.'</option>';
2372                                                 }
2373                                                 $table_data.= '</select></td>';
2374                                                 $table_data.= "<td align=center>$date</td>";
2375                                                 $table_data.= '<td><input type=text size="50" maxlength="128" name="hti_notes['.$i.'][notes]" value="'.$hti_notes.'">';
2376                                                 $table_data.= '<input type=hidden name="hti_notes['.$i.'][individual]" value="'.$id.'">';
2377                                                 $table_data.= '<input type=hidden name="hti_notes['.$i.'][indiv_name]" value="'.$name.'">';
2378                                                 $table_data.= '</td>';
2379                                                 $table_data.= '</tr>'."\n";
2380                                                 $i++;
2381                                         } else {
2382                                                 $link_data['menuaction'] = 'tc.tc.int_update';
2383                                                 $link_data['interviewer'] = $this->db2->f('interviewer');
2384                                                 $link_data['individual'] = $this->db2->f('individual');
2385                                                 $link_data['name'] = $name;
2386                                                 $link_data['interview'] = $this->db2->f('interview');
2387                                                 $link_data['interview_type'] = 'hti';
2388                                                 $link_data['action'] = 'view';
2389                                                 $link = $GLOBALS['phpgw']->link('/tc/index.php',$link_data);    
2390                                                 $comps_with_quarterly_int++;
2391                                                 $int_completed=1;
2392                                                 $date = $this->db2->f('date');
2393                                                 $hti_notes = $this->db2->f('notes');
2394                                                 if(strlen($hti_notes) > 40) { $hti_notes = substr($hti_notes,0,40) . "..."; }
2395                                                 $completed_data.= "<tr bgcolor=". $this->t->get_var('tr_color2') ."><td title=\"$phone\"><a href=$link>$name</a></td>";
2396                                                 $completed_data.= "<td align=center>$phone</td>";
2397                                                 $completed_data.= "<td align=center><a href=".$link.">$date</a></td>";
2398                                                 $completed_data.= "<td align=left>$hti_notes</td>";
2399                                                 $completed_data.= '</tr>';
2400                                         }
2401                                 }
2402                         }
2403
2404                         $completed_header_row = "<th><font size=-2>Individual</th>";
2405                         $completed_header_row.= "<th><font size=-2>Phone</th>";      
2406                         $completed_header_row.= "<th><font size=-2>Date</th>";
2407                         $completed_header_row.= "<th><font size=-2>Interview Notes</th>";
2408
2409                         $this->t->set_var('header_row',$header_row);
2410                         $this->t->set_var('table_data',$table_data);
2411                         $this->t->set_var('completed_header_row',$completed_header_row);
2412                         $this->t->set_var('completed',$completed_data);
2413                         $this->t->set_var('lang_save_appt','Save Appts for ' . $districts[$d]['name']);
2414                         $this->t->set_var('lang_save_pri_notes','Save Pri / Notes for '. $districts[$d]['name']);
2415                         $this->t->fp('indivlist','individual_list',True);
2416
2417                 } // End for each district loop
2418
2419
2420                 $totals_header_row = "<th><font size=-2>Individuals</th>";
2421                 $totals_header_row.= "<th><font size=-2>$year</th>";
2422                 $totals_data.= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
2423                 $totals_data.= "<td align=left><font size=-2><b>Total Companionships with interviews completed:</b></font></td>";
2424                 $totals_data.= "<td align=center><font size=-2><b>$comps_with_quarterly_int / $total_comps</b></font></td>";
2425                 $percent = ceil(($comps_with_quarterly_int / $total_comps)*100);
2426                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
2427                 $this->t->set_var('tr_color',$tr_color);
2428                 $totals_data.= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
2429                 $totals_data.= "<td align=left><font size=-2><b>Percentage:</b></font></td>";
2430                 $totals_data.= "<td align=center><font size=-2><b>$percent%</b></font></td>";
2431                 $totals_data.= "</tr>";
2432
2433                 $this->t->set_var('totals',$totals_data);
2434                 $this->t->set_var('totals_header_row',$totals_header_row);
2435
2436                 $this->t->pfp('out','int_sched_t');
2437                 $this->save_sessiondata(); 
2438
2439         }
2440   
2441         function vis_sched()
2442         {
2443                 $this->t->set_file(array('vis_sched_t' => 'vis_sched.tpl'));
2444                 $this->t->set_block('vis_sched_t','family_list','familylist');
2445                 $this->t->set_block('vis_sched_t','appt_list','apptlist');
2446                 $action = get_var('action',array('GET','POST'));
2447
2448                 $this->t->set_var('lang_reset','Clear Changes');
2449
2450                 $this->t->set_var('vis_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_view'));
2451                 $this->t->set_var('vis_link_title','View Yearly Visits');
2452
2453                 $this->t->set_var('schedule_vis_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_sched'));
2454                 $this->t->set_var('schedule_vis_link_title','Schedule Yearly Visits');
2455
2456                 $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_sched&action=save'));
2457                 $this->t->set_var('title','Presidency Yearly Visit Scheduler');
2458
2459                 $header_row = "<th><font size=-2>Family Name</th>";
2460                 $header_row.= "<th><font size=-2>Phone</th>";
2461                 $header_row.= "<th><font size=-2>Priority</th>";
2462                 $header_row.= "<th><font size=-2>Last Visit</th>";
2463                 $header_row.= "<th><font size=-2>Scheduling Notes</th>";
2464                 $table_data=""; $completed_data=""; $totals_data="";
2465
2466                 $year = date('Y');
2467
2468                 // create the family id -> family name mapping
2469                 $sql = "SELECT * FROM tc_family AS tf JOIN tc_individual AS ti WHERE tf.individual=ti.individual AND tf.valid=1 AND tf.individual != 0 AND tf.companionship != 0 AND ti.steward='$this->default_stewardship' ORDER BY ti.name ASC";
2470                 $this->db->query($sql,__LINE__,__FILE__);
2471                 $i=0;
2472                 $family_id = NULL;
2473                 while ($this->db->next_record()) {
2474                         $family_id[$i] = $this->db->f('family');
2475                         $family_name[$i] = $this->db->f('name');
2476                         $familyid2name[$family_id[$i]] = $family_name[$i];
2477                         $familyid2address[$family_id[$i]] = $this->db->f('address');
2478                         $i++;
2479                 }
2480                 array_multisort($family_name, $family_id);
2481
2482                 if($action == 'save') {
2483                         // Save any changes made to the appointment table
2484                         $new_data = get_var('appt_notes',array('POST'));
2485                         if($new_data != "") {
2486                                 foreach ($new_data as $entry) {
2487                                         $family = $entry['family'];
2488                                         $appointment = $entry['appointment'];
2489                                         $location = $entry['location'];
2490                                         if($location == "") {
2491                                                 $family_name_array = explode(",", $familyid2name[$family]);
2492                                                 $family_last_name = $family_name_array[0];
2493                                                 $family_address = $familyid2address[$family];
2494                                                 $location = "$family_last_name"." home ($family_address)";
2495                                         }
2496                                         if($family == 0) { $location = ""; }
2497
2498                                         //Only perform a database update if we have made a change to this appointment
2499                                         $sql = "SELECT * FROM tc_appointment where appointment='$appointment' and family='$family' and location='$location'";
2500                                         $this->db->query($sql,__LINE__,__FILE__);
2501                                         if(!$this->db->next_record()) {
2502                                                 // Perform database save actions here
2503                                                 $this->db->query("UPDATE tc_appointment set " .
2504                                                                  " family='" . $family . "'" .
2505                                                                  ",location='" . $location . "'" .
2506                                                                  " WHERE appointment=" . $appointment,__LINE__,__FILE__);
2507
2508                                                 // Email the appointment
2509                                                 $this->email_appt($appointment);
2510                                         }
2511                                 }
2512                         }
2513
2514                         // Save any changes made to the visit notes table
2515                         $new_data = get_var('vis_notes',array('POST'));
2516                         foreach ($new_data as $entry) {
2517                                 $visit_notes = $entry['notes'];
2518                                 $family = $entry['family_id'];
2519                                 $visit_pri = $entry['pri'];
2520                                 // Perform database save actions here
2521                                 $this->db->query("SELECT * FROM tc_family WHERE family='$family'",__LINE__,__FILE__);
2522                                 if ($this->db->next_record()) {
2523                                         $scheduling_priority = $this->db->f('scheduling_priority');
2524                                         $this->db2->query("UPDATE tc_scheduling_priority SET priority='$visit_pri', notes=\"$visit_notes\" WHERE scheduling_priority='$scheduling_priority'", __LINE__, __FILE__);
2525                                 }
2526                         }
2527
2528                         $take_me_to_url = $GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_sched');
2529                         //Header('Location: ' . $take_me_to_url);
2530                 }
2531
2532                 // APPOINTMENT TABLE
2533                 $appt_header_row = "<th><font size=-2>Date</th>";
2534                 $appt_header_row.= "<th><font size=-2>Time</th>";      
2535                 $appt_header_row.= "<th><font size=-2>Family</th>";
2536                 $appt_header_row.= "<th><font size=-2>Location</th>";
2537                 $appt_table_data = ""; 
2538
2539                 // Find out what the President ID is
2540                 $sql = "SELECT * FROM tc_presidency AS tp JOIN tc_individual AS ti WHERE tp.individual=ti.individual AND tp.president=1 AND tp.valid=1";
2541                 $this->db->query($sql,__LINE__,__FILE__);
2542                 if($this->db->next_record()) {
2543                         $presidency_name = $this->db->f('name');
2544                         $presidency_id = $this->db->f('presidency');
2545                 } else {
2546                         print "<hr><font color=red><h3>-E- Unable to locate Presidency in tc_presidency table</h3></font></hr>";
2547                         return;
2548                 }
2549
2550                 // query the database for all the appointments
2551                 $sql = "SELECT * FROM tc_appointment where presidency=$presidency_id and date>=CURDATE() ORDER BY date ASC, time ASC";
2552                 $this->db->query($sql,__LINE__,__FILE__);
2553
2554                 while ($this->db->next_record()) {
2555                         $appointment = $this->db->f('appointment');
2556                         $family = $this->db->f('family');
2557                         $location = $this->db->f('location');
2558                         $family_name_array = explode(",", $familyid2name[$family]);
2559                         $family_last_name = $family_name_array[0];
2560                         $family_address = $familyid2address[$family];
2561                         if(($location == "") && ($family > 0)) { $location = "$family_last_name"." home ($family_address)"; }
2562
2563                         $date = $this->db->f('date');
2564                         $date_array = explode("-",$date);
2565                         $year = $date_array[0]; $month = $date_array[1]; $day = $date_array[2];
2566                         $day_string = date("l d-M-Y", mktime(0,0,0,$month,$day,$year));
2567
2568                         $time = $this->db->f('time');
2569                         $time_array = explode(":",$time);
2570                         $time_string = date("g:i a", mktime($time_array[0], $time_array[1], $time_array[2]));
2571
2572                         $appt_table_data.= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
2573                         $appt_table_data.= "<td align=center>$day_string</td>";
2574                         $appt_table_data.= "<td align=center>$time_string</td>";
2575
2576                         $appt_table_data.= '<td align=center><select name=appt_notes['.$appointment.'][family]>';
2577                         $appt_table_data.= '<option value=0></option>';
2578                         for ($i=0; $i < count($family_id); $i++) {
2579                                 $id = $family_id[$i];
2580                                 $name = $family_name[$i];
2581                                 if($family_id[$i] == $family) { 
2582                                         $selected[$id] = 'selected="selected"'; 
2583                                 } else { 
2584                                         $selected[$id] = ''; 
2585                                 }
2586                                 $appt_table_data.= '<option value='.$id.' '.$selected[$id].'>'.$name.' Family</option>';
2587                         }
2588                         $appt_table_data.='</select></td>';
2589
2590                         $appt_table_data.= '<td align=center><input type=text size="35" maxlength="120" ';
2591                         $appt_table_data.= 'name="appt_notes['.$appointment.'][location]" value="'.$location.'">';
2592
2593                         $appt_table_data.= '<input type=hidden name="appt_notes['.$appointment.'][appointment]" value="'.$appointment.'">';
2594
2595                         $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
2596                         $this->t->set_var('tr_color',$tr_color);
2597                 }
2598
2599                 $this->t->set_var('appt_table_data',$appt_table_data);
2600                 $this->t->set_var('appt_header_row',$appt_header_row);
2601
2602
2603                 // VISIT SCHEDULING TABLE
2604                 $sql = "SELECT * FROM tc_family AS tf JOIN (tc_scheduling_priority AS tsp, tc_individual as ti) WHERE tf.scheduling_priority=tsp.scheduling_priority AND tf.individual=ti.individual AND tf.valid=1 AND tf.individual != 0  AND tf.companionship != 0 AND ti.steward='$this->default_stewardship' ORDER BY tsp.priority ASC, ti.name ASC";
2605                 $this->db->query($sql,__LINE__,__FILE__);
2606
2607                 $total_families=0; $families_with_yearly_visit=0;
2608
2609                 while ( $this->db->next_record()) {
2610                         $total_families++;
2611                         $id = $this->db->f('family');
2612                         $name = $this->db->f('name');
2613                         $phone = $this->db->f('phone');
2614                         $vis_pri = $this->db->f('priority');
2615                         $vis_notes = $this->db->f('notes');
2616
2617                         // If this family has had a yearly visit this year, don't show them on the schedule list
2618                         $year_start = $year - 1 . "-12-31"; $year_end = $year + 1 . "-01-01";
2619                         $sql = "SELECT * FROM tc_visit WHERE date > '$year_start' AND date < '$year_end' ".
2620                                "AND family=" . $id . " AND companionship=0";
2621                         $this->db2->query($sql,__LINE__,__FILE__);
2622
2623                         if(!$this->db2->next_record()) {
2624                                 $sql = "SELECT * FROM tc_visit WHERE family=" . $id . " AND companionship=0 ORDER BY date DESC";
2625                                 $this->db3->query($sql,__LINE__,__FILE__);
2626                                 if($this->db3->next_record()) { 
2627                                         $date = $this->db3->f('date'); 
2628                                 } else { 
2629                                         $date = ""; 
2630                                 }
2631                                 $link_data['menuaction'] = 'tc.tc.vis_update';
2632                                 $link_data['visit'] = '';
2633                                 $link_data['family'] = $id;
2634                                 $link_data['name'] = $name;
2635                                 $link_data['action'] = 'add';
2636                                 $link = $GLOBALS['phpgw']->link('/tc/index.php',$link_data);
2637                                 $table_data.= "<tr bgcolor=". $this->t->get_var('tr_color') ."><td title=\"$phone\"><a href=$link>$name Family</a></td>";
2638                                 $table_data.= "<td align=center>$phone</td>";
2639                                 $table_data.= "<td align=center>";
2640                                 $table_data.= '<select name=vis_notes['.$id.'][pri]>';
2641                                 foreach(range(0,6) as $num) {
2642                                         if($num == 0) { $num = 1; } else {$num = $num*5; }
2643                                         if($vis_pri == $num) { 
2644                                                 $selected[$num] = 'selected="selected"'; 
2645                                         } else { 
2646                                                 $selected[$num] = ''; 
2647                                         }
2648                                         $table_data.= '<option value='.$num.' '.$selected[$num].'>'.$num.'</option>';
2649                                 }
2650                                 $table_data.= '</select></td>';
2651                                 $table_data.= "<td align=center>$date</td>";
2652                                 $table_data.= '<td><input type=text size="50" maxlength="128" name="vis_notes['.$id.'][notes]" value="'.$vis_notes.'">';
2653                                 $table_data.= '<input type=hidden name="vis_notes['.$id.'][family_id]" value="'.$id.'">';
2654                                 $table_data.= '<input type=hidden name="vis_notes['.$id.'][family_name]" value="'.$name.'">';
2655                                 $table_data.= '</td>';
2656                                 $table_data.= '</tr>';
2657                                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
2658                                 $this->t->set_var('tr_color',$tr_color);
2659                         } else {
2660                                 $link_data['menuaction'] = 'tc.tc.vis_update';
2661                                 $link_data['visit'] = $this->db2->f('visit');
2662                                 $link_data['family'] = $this->db2->f('family');
2663                                 $link_data['name'] = $name;
2664                                 $link_data['date'] = $this->db2->f('date');
2665                                 $link_data['action'] = 'view';
2666                                 $link = $GLOBALS['phpgw']->link('/tc/index.php',$link_data);    
2667                                 $families_with_yearly_visit++;
2668                                 $date = $this->db2->f('date');
2669                                 $vis_notes = $this->db2->f('notes');
2670                                 if(strlen($vis_notes) > 40) { $vis_notes = stripslashes(substr($vis_notes,0,40) . "..."); }
2671                                 $completed_data.= "<tr bgcolor=". $this->t->get_var('tr_color2') ."><td title=\"$phone\"><a href=$link>$name Family</a></td>";
2672                                 $completed_data.= "<td align=center>$phone</td>";
2673                                 $completed_data.= "<td align=center><a href=".$link.">$date</a></td>";
2674                                 $completed_data.= "<td align=left>$vis_notes</td>";
2675                                 $completed_data.= '</tr>';
2676                                 $tr_color2 = $this->nextmatchs->alternate_row_color($tr_color2);
2677                                 $this->t->set_var('tr_color2',$tr_color2);
2678                         }
2679                 }
2680
2681                 $completed_header_row = "<th><font size=-2>Family Name</th>";
2682                 $completed_header_row.= "<th><font size=-2>Phone</th>";      
2683                 $completed_header_row.= "<th><font size=-2>Date</th>";
2684                 $completed_header_row.= "<th><font size=-2>Visit Notes</th>";
2685
2686                 $totals_header_row = "<th><font size=-2>Families</th>";
2687                 $totals_header_row.= "<th><font size=-2>$year</th>";
2688                 $totals_data.= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
2689                 $totals_data.= "<td align=left><font size=-2><b>Total Families with yearly Visits completed:</b></font></td>";
2690                 $totals_data.= "<td align=center><font size=-2><b>$families_with_yearly_visit / $total_families</b></font></td>";
2691                 $percent = ceil(($families_with_yearly_visit / $total_families)*100);
2692                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
2693                 $this->t->set_var('tr_color',$tr_color);
2694                 $totals_data.= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
2695                 $totals_data.= "<td align=left><font size=-2><b>Percentage:</b></font></td>";
2696                 $totals_data.= "<td align=center><font size=-2><b>$percent%</b></font></td>";
2697                 $totals_data.= "</tr>";
2698
2699                 $this->t->set_var('header_row',$header_row);
2700                 $this->t->set_var('table_data',$table_data);
2701                 $this->t->set_var('totals_header_row',$totals_header_row);
2702                 $this->t->set_var('completed_header_row',$completed_header_row);
2703                 $this->t->set_var('completed',$completed_data);
2704                 $this->t->set_var('totals',$totals_data);
2705                 $this->t->fp('familylist','family_list',True);
2706                 $this->t->set_var('lang_save_appt','Save Appts');
2707                 $this->t->set_var('lang_save_pri_notes','Save Pri / Notes');
2708                 $this->t->fp('apptlist','appt_list',True);
2709
2710                 $this->t->pfp('out','vis_sched_t');
2711                 $this->save_sessiondata(); 
2712         }
2713   
2714         function ppi_view()
2715         {
2716                 $this->t->set_file(array('ppi_view_t' => 'ppi_view.tpl'));
2717                 $this->t->set_block('ppi_view_t','district_list','list');
2718
2719                 $this->t->set_var('linkurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_view'));
2720                 $num_months = get_var('num_months',array('GET','POST'));
2721                 if($num_months == '') { $num_months = $this->default_ppi_num_months; }
2722                 $this->t->set_var('num_months',$num_months);
2723                 if($num_months == 1) { 
2724                         $this->t->set_var('lang_num_months','Month of History'); 
2725                 } else {  
2726                         $this->t->set_var('lang_num_months','Months of History'); 
2727                 }
2728                 $this->t->set_var('lang_filter','Filter');
2729                 $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_view'));
2730
2731                 $this->t->set_var('ppi_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_view'));
2732                 $this->t->set_var('ppi_link_title',$this->ppi_frequency_label . ' PPIs'); 
2733
2734                 $this->t->set_var('schedule_ppi_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_sched'));
2735                 $this->t->set_var('schedule_ppi_link_title','Schedule ' . $this->ppi_frequency_label . ' PPIs');
2736
2737                 $this->t->set_var('title',$this->ppi_frequency_label . ' PPIs');
2738                 $num_months = get_var('num_months',array('GET','POST'));
2739                 if($num_months == '') { $num_months = $this->default_ppi_num_years; }
2740                 $this->t->set_var('num_months',$num_months);
2741                 if($num_months == 1) { 
2742                         $this->t->set_var('lang_num_months','Year of History'); 
2743                 } else { 
2744                         $this->t->set_var('lang_num_months','Years of History');
2745                 }
2746
2747                 $sql = "SELECT * FROM tc_presidency AS tp JOIN tc_individual AS ti WHERE tp.individual=ti.individual AND tp.president=1 AND tp.valid=1";
2748                 $this->db->query($sql,__LINE__,__FILE__);
2749                 if($this->db->next_record()) {
2750                         $president_name = $this->db->f('name');
2751                         $interviewer = $this->db->f('individual');
2752                 } else {
2753                         print "<hr><font color=red><h3>-E- Unable to locate President in tc_presidency table</h3></font></hr>";
2754                         return;
2755                 }
2756                 $this->t->set_var('district_number','*');
2757                 $this->t->set_var('district_name',$president_name);
2758
2759                 $sql = "SELECT * FROM tc_individual AS ti JOIN tc_scheduling_priority as tsp where ti.scheduling_priority=tsp.scheduling_priority and ti.steward='$this->default_stewardship' and ti.valid=1 ORDER BY ti.individual ASC";
2760                 $this->db->query($sql,__LINE__,__FILE__);
2761                 $i=0;
2762                 while ($this->db->next_record()) {
2763                         $individual[$i] = $this->db->f('individual');
2764                         $indiv_name[$i] = $this->db->f('name');
2765                         $indiv_phone[$individual[$i]] = $this->db->f('phone');
2766                         $indiv_priority[$individual[$i]] = $this->db->f('priority');
2767                         $indiv_notes[$individual[$i]] = $this->db->f('notes');
2768                         $i++;
2769                 }
2770                 $total_indivs=$i;
2771                 array_multisort($indiv_name, $individual);
2772                 //var_dump($indiv_name); print "<br><br>"; var_dump($individual);
2773
2774                 $header_row="<th width=$comp_width><font size=-2>Individual</th>";
2775
2776                 $indiv_width=400; $ppi_width=75; $table_width=$indiv_width + $num_months*$ppi_width;
2777                 $table_data="";
2778                 for($m=$num_months; $m >= 0; $m--) {
2779                         $year = date('Y') - $m;
2780                         $header_row .= "<th width=150><font size=-2>$year</th>"; 
2781                         $ppis[$m] = 0;
2782                 }
2783
2784                 for ($j=0; $j < count($individual); $j++) {
2785                         $id = $individual[$j];
2786                         $name = $indiv_name[$j];
2787                         $phone = $indiv_phone[$id];
2788
2789                         $link_data['menuaction'] = 'tc.tc.ppi_update';
2790                         $link_data['interviewer'] = $interviewer;
2791                         $link_data['individual'] = $id;
2792                         $link_data['name'] = $name;
2793                         $link_data['interview'] = '';
2794                         $link_data['interview_type'] = 'ppi'; 
2795                         $link_data['action'] = 'add';
2796                         $link = $GLOBALS['phpgw']->link('/tc/index.php',$link_data);
2797                         $this->nextmatchs->template_alternate_row_color(&$this->t);
2798                         $table_data.= "<tr bgcolor=". $this->t->get_var('tr_color') ."><td title=\"$phone\"><a href=$link>$name</a></td>";
2799
2800                         // Find out how many times PPIs were performed in the past $num_months for this individual
2801                         for($m=$num_months; $m >= 0; $m--) {
2802                                 $year = date('Y') - $m;
2803                                 $year_start = $year - 1 . "-12-31"; $year_end = $year + 1 . "-01-01";
2804                                 $sql = "SELECT * FROM tc_interview WHERE date > '$year_start' AND date < '$year_end' ".
2805                                        "AND individual=" . $id . " AND interview_type='ppi' ORDER BY date DESC";
2806                                 $this->db2->query($sql,__LINE__,__FILE__);
2807
2808                                 if(!$total_ppis[$m]) { $total_ppis[$m] = 0; }
2809                                 if($this->db2->next_record()) {
2810                                         $ppis[$m]++; $total_ppis[$m]++; $ppi_recorded[$companionship][$m]=1;
2811                                         $link_data['menuaction'] = 'tc.tc.ppi_update';
2812                                         $link_data['companionship'] = $companionship;
2813                                         $link_data['interviewer'] = $this->db2->f('interviewer');
2814                                         $link_data['indiv'] = $id;
2815                                         $link_data['name'] = $name;
2816                                         $link_data['interview'] = $this->db2->f('interview');
2817                                         $link_data['interview_type'] = 'ppi';
2818                                         $link_data['action'] = 'view';
2819                                         $date = $this->db2->f('date');
2820                                         $date_array = explode("-",$date);
2821                                         $month = $date_array[1];
2822                                         $day   = $date_array[2];
2823                                         $link = $GLOBALS['phpgw']->link('/tc/index.php',$link_data);
2824                                         $table_data .= '<td align=center><a href='.$link.'><img src="images/checkmark.gif">&nbsp;'.$month.'-'.$day.'</a></td>';
2825                                 } else { 
2826                                         $table_data .= "<td>&nbsp;</td>"; 
2827                                 }
2828                         }
2829                         $table_data .= "</tr>\n"; 
2830                 }
2831                 $table_data .= "<tr><td colspan=20><hr></td></tr>";
2832
2833                 $stat_data = "<tr><td><b><font size=-2>$total_indivs Individuals<br>PPI Totals:</font></b></td>";
2834                 for($m=$num_months; $m >=0; $m--) {
2835                         $percent = ceil(($ppis[$m] / $total_indivs)*100);
2836                         $stat_data .= "<td align=center><font size=-2><b>$ppis[$m]<br>$percent%</font></b></td>";
2837                 }
2838                 $stat_data .= "</tr>";
2839
2840                 $this->t->set_var('table_width',$table_width);
2841                 $this->t->set_var('header_row',$header_row);
2842                 $this->t->set_var('table_data',$table_data);
2843                 $this->t->set_var('stat_data',$stat_data);
2844                 $this->t->pfp('out','ppi_view_t');
2845                 $this->save_sessiondata(); 
2846         }
2847
2848         function ppi_update()
2849         {
2850                 $this->t->set_file(array('form' => 'ppi_update.tpl'));
2851                 $this->t->set_block('form','interviewer_list','int_list');
2852                 $this->t->set_block('form','add','addhandle');
2853                 $this->t->set_block('form','edit','edithandle');
2854
2855                 $this->t->set_var('done_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_view'));
2856                 $this->t->set_var('readonly','');
2857                 $this->t->set_var('disabled','');
2858
2859                 $action = get_var('action',array('GET','POST'));
2860                 $companionship = get_var('companionship',array('GET','POST'));
2861                 $interviewer = get_var('interviewer',array('GET','POST'));      
2862                 $name = get_var('name',array('GET','POST'));
2863                 $interview = get_var('interview',array('GET','POST'));
2864                 $individual = get_var('individual',array('GET','POST'));
2865                 $date = get_var('date',array('GET','POST'));
2866                 $notes = get_var('notes',array('GET','POST'));
2867                 $interview_type = get_var('interview_type',array('GET','POST'));
2868
2869             $sql = "SELECT * FROM tc_presidency AS tp JOIN tc_individual AS ti WHERE tp.individual=ti.individual AND tp.valid=1 AND ";
2870             if($this->yearly_ppi_interviewer == 1) { $sql .= " (tp.president=1)"; }
2871                 if($this->yearly_ppi_interviewer == 2) { $sql .= " (tp.president=1 OR tp.counselor=1)"; }
2872                 if($this->yearly_ppi_interviewer == 3) { $sql .= " (tp.president=1 OR tp.counselor=1 OR tp.secretary=1)"; }
2873                 $this->db2->query($sql,__LINE__,__FILE__);
2874                 while ($this->db2->next_record()) {
2875                         $indiv = $this->db2->f('individual');
2876                         $interviewer_name = $this->db2->f('name');
2877                         if($indiv == $interviewer) {
2878                                 $this->t->set_var('interviewer',$indiv . ' selected');
2879                         } else {
2880                                 $this->t->set_var('interviewer',$indiv);
2881                         }
2882                         #print "indiv: $indiv interviewer: $interviewer<br>";
2883                         $this->t->set_var('interviewer_name',$interviewer_name);
2884                         $this->t->set_var('eqpresppi_checked','checked');
2885                         $this->t->fp('int_list','interviewer_list',True);
2886                 }
2887                 #print "selected interviewer: $interviewer<br>";
2888                 if($action == 'save') {
2889                         $notes = get_var('notes',array('POST'));
2890                         $this->db->query("UPDATE tc_interview set " .
2891                                          "   interview='" . $interview . "'" .
2892                                          ", interviewer='" . $interviewer . "'" .
2893                                          ", individual='" . $individual . "'" .
2894                                          ", date='" . $date . "'" .
2895                                          ", notes=\"" . $notes . "\"" .
2896                                          ", interview_type='" . $interview_type . "'" .
2897                                          " WHERE interview=" . $interview,__LINE__,__FILE__);
2898                         $this->ppi_view();
2899                         return false;
2900                 }
2901
2902                 if($action == 'insert') {
2903                         $notes = get_var('notes',array('POST'));
2904                         $this->db->query("INSERT INTO tc_interview (interviewer,individual,date,notes,interview_type) " .
2905                                          "VALUES ('" . $interviewer . "','" . $individual . "','" .
2906                                          $date . "',\"" . $notes . "\",'" . $interview_type  ."')",__LINE__,__FILE__);
2907                         $this->ppi_view();
2908                         return false;
2909                 }
2910
2911                 if($action == 'add') {
2912                         $this->t->set_var('cal_date',$this->jscal->input('date','','','','','','',$this->cal_options));
2913                         $this->t->set_var('interview', '');
2914                         $this->t->set_var('interviewer', $interviewer);
2915                         $this->t->set_var('name',$name);
2916                         $this->t->set_var('individual',$individual);
2917                         $this->t->set_var('date','');
2918                         $this->t->set_var('notes','');
2919                         $this->t->set_var('interview_type',$interview_type);
2920                         $this->t->set_var('eqpresppi_checked','checked');
2921                         $this->t->set_var('lang_done','Cancel');
2922                         $this->t->set_var('lang_action','Adding New PPI');
2923                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_update&interview=' .
2924                                           $interview . '&action=' . 'insert'));
2925                 }
2926
2927                 if($action == 'edit' || $action == 'view') {
2928                         $sql = "SELECT * FROM tc_interview WHERE interview=" . $interview . " AND interview_type='ppi'";
2929                         $this->db->query($sql,__LINE__,__FILE__);
2930                         $this->db->next_record();
2931                         $this->t->set_var('interview',$interview);
2932                         $this->t->set_var('name',$name);
2933                         $this->t->set_var('interviewer', $this->db->f('interviewer'));
2934                         $this->t->set_var('individual',$this->db->f('individual'));
2935                         $this->t->set_var('date',$this->db->f('date'));
2936                         $this->t->set_var('notes',$this->db->f('notes'));
2937                         $this->t->set_var('interview_type',$this->db->f('interview_type'));
2938                         if($this->db->f('interview_type') == 'ppi') { $this->t->set_var('eqpresppi_checked','checked'); }
2939                 }
2940
2941                 if($action == 'edit') {
2942                         $this->t->set_var('cal_date',$this->jscal->input('date',$date,'','','','','',$this->cal_options));
2943                         $this->t->set_var('lang_done','Cancel');
2944                         $this->t->set_var('lang_action','Editing PPI');
2945                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_update&interview='. 
2946                                           $interview . '&action=' . 'save'));
2947                 }
2948
2949                 if($action == 'view') {
2950                         $date = $this->db->f('date');
2951                         $this->t->set_var('cal_date','<input type=text size="10" maxlength="10" name="date" value="'.$date.'" readonly>');
2952                         $this->t->set_var('readonly','READONLY');
2953                         $this->t->set_var('disabled','DISABLED');
2954                         $this->t->set_var('lang_done','Done');
2955                         $this->t->set_var('lang_action','Viewing PPI');
2956                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_update&interview=' .
2957                                           $interview . '&action=' . 'edit'));
2958                 }
2959
2960                 $this->t->set_var('lang_reset','Clear Form');
2961                 $this->t->set_var('lang_add','Add PPI');
2962                 $this->t->set_var('lang_save','Save Changes');
2963                 $this->t->set_var('edithandle','');
2964                 $this->t->set_var('addhandle','');
2965
2966                 $this->t->pfp('out','form');
2967
2968                 if($action == 'view') { $this->t->set_var('lang_save','Edit PPI'); }
2969                 if($action == 'edit' || $action == 'view') { $this->t->pfp('addhandle','edit'); }
2970                 if($action == 'add') { $this->t->pfp('addhandle','add'); }
2971
2972                 $this->save_sessiondata(); 
2973         }
2974
2975         function int_view()
2976         {
2977                 $this->t->set_file(array('int_view_t' => 'int_view.tpl'));
2978                 $this->t->set_block('int_view_t','district_list','list');
2979
2980                 $this->t->set_var('linkurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_view'));
2981                 $num_quarters = get_var('num_quarters',array('GET','POST'));
2982                 if($num_quarters == '') { $num_quarters = $this->default_int_num_quarters; }
2983                 $this->t->set_var('num_quarters',$num_quarters);
2984                 if($num_quarters == 1) { 
2985                         $this->t->set_var('lang_num_quarters','Quarter of History'); 
2986                 } else {
2987                         $this->t->set_var('lang_num_quarters','Quarters of History'); 
2988                 }
2989                 $this->t->set_var('lang_filter','Filter');
2990
2991                 $this->t->set_var('int_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_view'));
2992                 $this->t->set_var('int_link_title','Hometeaching Interviews'); 
2993
2994                 $this->t->set_var('schedule_int_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_sched'));
2995                 $this->t->set_var('schedule_int_link_title','Schedule Hometeaching Interviews');
2996
2997                 $this->t->set_var('title','Hometeaching Interviews'); 
2998
2999                 $num_months = $num_quarters * 3 - 1;
3000                 $current_month = $this->current_month;
3001                 if($current_month >= 1 && $current_month <= 3) { $current_month=3; }
3002                 else if($current_month >= 4 && $current_month <= 6) { $current_month=6; }
3003                 else if($current_month >= 7 && $current_month <= 9) { $current_month=9; }
3004                 else if($current_month >= 10 && $current_month <= 12) { $current_month=12; }
3005
3006                 $sql = "SELECT * FROM tc_district AS td JOIN tc_individual AS ti WHERE td.supervisor=ti.individual AND td.valid=1 ORDER BY td.district ASC";
3007                 $this->db->query($sql,__LINE__,__FILE__);
3008                 $i=0;
3009                 while ($this->db->next_record()) {
3010                         $districts[$i]['district'] = $this->db->f('district');
3011                         $districts[$i]['name'] = $this->db->f('name');
3012                         $districts[$i]['supervisor'] = $this->db->f('supervisor');
3013                         $i++;
3014                 }
3015
3016                 $sql = "SELECT * FROM tc_individual where valid=1 ORDER BY individual ASC";
3017                 $this->db->query($sql,__LINE__,__FILE__);
3018                 $i=0;
3019                 while ($this->db->next_record()) {
3020                         $individual[$i] = $this->db->f('individual');
3021                         $indiv_name[$i] = $this->db->f('name');
3022                         $indiv_phone[$individual[$i]] = $this->db->f('phone');
3023                         $i++;
3024                 }
3025                 array_multisort($indiv_name, $individual);
3026                 for($i=0; $i < count($individual); $i++) {
3027                         $id = $individual[$i];
3028                         $indivs[$id] = $indiv_name[$i];
3029                 }      
3030
3031                 $total_companionships = 0;
3032                 $this->nextmatchs->template_alternate_row_color(&$this->t);
3033                 for ($i=0; $i < count($districts); $i++) {
3034                         $this->t->set_var('district_number',$districts[$i]['district']);
3035                         $this->t->set_var('district_name',$districts[$i]['name']);      
3036                         $supervisor = $districts[$i]['supervisor'];
3037
3038                         // Select all the unique companionship numbers for this district
3039                         $sql = "SELECT distinct companionship FROM tc_companionship where valid=1 and district=". $districts[$i]['district'];
3040                         $this->db->query($sql,__LINE__,__FILE__);
3041                         $j=0; $unique_companionships = '';
3042                         while ($this->db->next_record()) {
3043                                 $unique_companionships[$j]['companionship'] = $this->db->f('companionship');
3044                                 $j++;
3045                         }
3046
3047                         $comp_width=250; $int_width=75; $table_width=$comp_width + $num_months*$int_width;
3048                         $table_data=""; $num_companionships = $j; $num_indivs = 0;
3049                         for($m=$num_months; $m >= 0; $m--) { $ints[$m] = 0; }
3050                         for ($j=0; $j < count($unique_companionships); $j++) {
3051                                 // Select all the companions in each companionship
3052                                 $sql = "SELECT * FROM tc_companion where valid=1 and ".
3053                                        "companionship=". $unique_companionships[$j]['companionship'];
3054                                 $this->db->query($sql,__LINE__,__FILE__);
3055                                 $k=0;
3056                                 $comp = $unique_companionships[$j]['companionship'];
3057                                 for($m=$num_months; $m >= 0; $m--) { $int_recorded[$comp][$m] = 0; }
3058                                 while ($this->db->next_record()) {
3059                                         // Get this companions information
3060                                         $num_indivs++;
3061                                         $companionship = $this->db->f('companionship');
3062                                         $individual = $this->db->f('individual');
3063                                         $name = $indivs[$individual];
3064                                         $phone = $indiv_phone[$individual];
3065                                         $link_data['menuaction'] = 'tc.tc.int_update';
3066                                         $link_data['companionship'] = $companionship;
3067                                         $link_data['interviewer'] = $supervisor;
3068                                         $link_data['individual'] = $individual;
3069                                         $link_data['name'] = $name;
3070                                         $link_data['interview'] = '';
3071                                         $link_data['interview_type'] = 'hti';
3072                                         $link_data['action'] = 'add';
3073                                         $link = $GLOBALS['phpgw']->link('/tc/index.php',$link_data);
3074                                         $table_data.= "<tr bgcolor=". $this->t->get_var('tr_color') ."><td title=\"$phone\"><a href=$link>$name</a></td>";
3075
3076                                         // Find out how many times Interviews were performed in the past $num_months for this individual
3077                                         $header_row="<th width=$comp_width><font size=-2>Companionship</th>";
3078                                         for($m=$num_months; $m >= 0; $m--) {
3079                                                 $month = $current_month - $m;
3080                                                 $year = $this->current_year;
3081                                                 if($month <= 0) { 
3082                                                         $remainder = $month; 
3083                                                         $month = 12 + $remainder; 
3084                                                         $year=$year-1; 
3085                                                 }
3086                                                 if($month < 10) { $month = "0"."$month"; }
3087                                                 $month_start = "$year"."-"."$month"."-"."01";
3088                                                 $month_end = "$year"."-"."$month"."-"."31";
3089                                                 $month = "$month"."/"."$year";
3090                                                 $sql = "SELECT * FROM tc_interview WHERE date >= '$month_start' AND date <= '$month_end' ".
3091                                                        "AND individual=" . $individual . " AND interview_type='hti' ORDER BY date DESC";
3092                                                 $this->db2->query($sql,__LINE__,__FILE__);
3093                                                 $header_row .= "<th width=$int_width><font size=-2>$month</th>";
3094
3095                                                 if(!$total_ints[$m]) { $total_ints[$m] = 0; }
3096                                                 if($this->db2->next_record()) {
3097                                                         if(!$int_recorded[$companionship][$m]) {
3098                                                                 $ints[$m]++; 
3099                                                                 $total_ints[$m]++; 
3100                                                                 $int_recorded[$companionship][$m]=1;
3101                                                         }
3102                                                         $link_data['menuaction'] = 'tc.tc.int_update';
3103                                                         $link_data['companionship'] = $companionship;
3104                                                         $link_data['interviewer'] = $this->db2->f('interviewer');
3105                                                         $link_data['individual'] = $individual;
3106                                                         $link_data['name'] = $name;
3107                                                         $link_data['interview'] = $this->db2->f('interview');
3108                                                         $link_data['action'] = 'view';
3109                                                         $link_data['interview_type'] = 'hti';
3110                                                         $date = $this->db2->f('date');
3111                                                         $date_array = explode("-",$date);
3112                                                         $month = $date_array[1];
3113                                                         $day   = $date_array[2];
3114                                                         $link = $GLOBALS['phpgw']->link('/tc/index.php',$link_data);
3115                                                         $table_data .= '<td align=center><a href='.$link.'><img src="images/checkmark.gif">&nbsp;'.$month.'-'.$day.'</a></td>';
3116                                                 }
3117                                                 else { 
3118                                                         $table_data .= "<td>&nbsp;</td>"; 
3119                                                 }
3120                                         }
3121                                         $table_data .= "</tr>"; 
3122                                         $k++;
3123                                 }
3124                                 $table_data .= "<tr><td colspan=20><hr></td></tr>";
3125                         }
3126                         $total_companionships += $num_companionships;
3127                         $stat_data = "<tr><td><b><font size=-2>$num_companionships Companionships<br>Interview Totals:</font></b></td>";
3128
3129                         // Print the hometeaching interview stats
3130                         for($m=$num_months; $m >=0; $m--) {
3131                                 $month = $current_month - $m;
3132                                 if($month < 0) { $month = 12 + $month; } // Handle going backwards over a year boundary
3133                                 $month_begins = $month % $this->monthly_hometeaching_interview_stats;
3134                                 //print "$month % $this->monthly_hometeaching_interview_stats = $month_begins <br>";
3135                                 if($this->monthly_hometeaching_interview_stats == 1) { $month_begins = 1; }
3136                                 if(($month_begins) == 1) { 
3137                                         $total = $ints[$m]; 
3138                                 } else { 
3139                                         $total += $ints[$m]; 
3140                                 }
3141                                 $percent = ceil(($total / $num_companionships)*100);
3142                                 $stat_data .= "<td align=center><font size=-2><b>$total<br>$percent%</font></b></td>";
3143                         }
3144                         $stat_data .= "</tr>";
3145
3146                         $this->t->set_var('table_width',$table_width);
3147                         $this->t->set_var('header_row',$header_row);
3148                         $this->t->set_var('table_data',$table_data);
3149                         $this->t->set_var('stat_data',$stat_data);
3150                         $this->t->fp('list','district_list',True);
3151                 }
3152
3153                 // Display the totals
3154                 $total = 0;
3155                 $totals = "<tr><td><b><font size=-2>$total_companionships Total Comps<br>Interview Totals:</font></b></td>";
3156                 for($m=$num_months; $m >=0; $m--) {
3157                         $month = $current_month - $m;
3158                         if($month < 0) { $month = 12 + $month; } // Handle going backwards over a year boundary
3159                         $month_begins = $month % $this->monthly_hometeaching_interview_stats;
3160                         if($this->monthly_hometeaching_interview_stats == 1) { $month_begins = 1; }
3161                         if(($month_begins) == 1) { 
3162                                 $total = $total_ints[$m]; 
3163                         } else { 
3164                                 $total += $total_ints[$m]; 
3165                         }
3166                         $percent = ceil(($total / $total_companionships)*100);
3167                         $totals .= "<td align=center><font size=-2><b>$total<br>$percent%</font></b></td>";
3168                 }
3169                 $totals .= "</tr>";
3170
3171                 $this->t->set_var('totals',$totals);
3172                 $this->t->pfp('out','int_view_t');
3173                 $this->save_sessiondata(); 
3174         }
3175
3176         function int_update()
3177         {
3178                 $this->t->set_file(array('form' => 'int_update.tpl'));
3179                 $this->t->set_block('form','interviewer_list','int_list');
3180                 $this->t->set_block('form','add','addhandle');
3181                 $this->t->set_block('form','edit','edithandle');
3182
3183                 $this->t->set_var('done_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_view'));
3184                 $this->t->set_var('readonly','');
3185                 $this->t->set_var('disabled','');
3186                 $this->t->set_var('eqpresppi','');
3187
3188                 $action = get_var('action',array('GET','POST'));
3189                 $companionship = get_var('companionship',array('GET','POST'));
3190                 $interviewer = get_var('interviewer',array('GET','POST'));      
3191                 $name = get_var('name',array('GET','POST'));
3192                 $interview = get_var('interview',array('GET','POST'));
3193                 $individual = get_var('individual',array('GET','POST'));
3194                 $date = get_var('date',array('GET','POST'));
3195                 $notes = get_var('notes',array('GET','POST'));
3196                 $interview_type = get_var('interview_type',array('GET','POST'));
3197
3198                 $sql = "SELECT * FROM tc_presidency AS tp JOIN tc_individual AS ti WHERE tp.individual=ti.individual AND tp.valid=1 AND (tp.president=1 OR tp.counselor=1 OR tp.secretary=1 OR tp.district!=0)";
3199                 $this->db2->query($sql,__LINE__,__FILE__);
3200                 while ($this->db2->next_record()) {
3201                         $indiv = $this->db2->f('individual');
3202                         $interviewer_name = $this->db2->f('name');
3203                         if($indiv == $interviewer) {
3204                                 $this->t->set_var('interviewer',$indiv . ' selected');
3205                         } else {
3206                                 $this->t->set_var('interviewer',$indiv);
3207                         }
3208                         $this->t->set_var('interviewer_name',$interviewer_name);
3209                         $this->t->fp('int_list','interviewer_list',True);
3210                 }
3211
3212                 if($action == 'save') {
3213                         $notes = get_var('notes',array('POST'));
3214                         $this->db->query("UPDATE tc_interview set " .
3215                                          "   interview='" . $interview . "'" .
3216                                          ", interviewer='" . $interviewer . "'" .
3217                                          ", individual='" . $individual . "'" .
3218                                          ", date='" . $date . "'" .
3219                                          ", notes=\"" . $notes . "\"" .
3220                                          ", interview_type='" . $interview_type . "'" .
3221                                          " WHERE interview=" . $interview,__LINE__,__FILE__);
3222                         $this->int_view();
3223                         return false;
3224                 }
3225
3226                 if($action == 'insert') {
3227                         $notes = get_var('notes',array('POST'));
3228                         $this->db->query("INSERT INTO tc_interview (interviewer,individual,date,notes,interview_type) " .
3229                                          "VALUES ('" . $interviewer . "','" . $individual . "','" .
3230                                          $date . "',\"" . $notes ."\",'" . $interview_type . "')",__LINE__,__FILE__);
3231                         $this->int_view();
3232                         return false;
3233                 }
3234
3235                 if($action == 'add') {
3236                         $this->t->set_var('cal_date',$this->jscal->input('date','','','','','','',$this->cal_options));
3237                         $this->t->set_var('interview', '');
3238                         $this->t->set_var('interviewer', $interviewer);
3239                         $this->t->set_var('name',$name);
3240                         $this->t->set_var('individual',$individual);
3241                         $this->t->set_var('date','');
3242                         $this->t->set_var('notes','');
3243                         $this->t->set_var('interview_type',$interview_type);
3244                         $this->t->set_var('lang_done','Cancel');
3245                         $this->t->set_var('lang_action','Adding New Interview');
3246                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_update&interview=' .
3247                                           $interview . '&action=' . 'insert'));
3248                 }
3249
3250                 if($action == 'edit' || $action == 'view') {
3251                         $sql = "SELECT * FROM tc_interview WHERE interview=" . $interview . " AND interview_type='hti'";
3252                         $this->db->query($sql,__LINE__,__FILE__);
3253                         $this->db->next_record();
3254                         $this->t->set_var('interview',$interview);
3255                         $this->t->set_var('name',$name);
3256                         $this->t->set_var('interviewer', $this->db->f('interviewer'));
3257                         $this->t->set_var('individual',$this->db->f('individual'));
3258                         $this->t->set_var('date',$this->db->f('date'));
3259                         $this->t->set_var('notes',$this->db->f('notes'));
3260                         $this->t->set_var('interview_type',$this->db->f('interview_type'));
3261                         if($this->db->f('interview_type') == 'ppi') { $this->t->set_var('eqpresppi_checked','checked'); }
3262                 }
3263
3264                 if($action == 'edit') {
3265                         $this->t->set_var('cal_date',$this->jscal->input('date',$date,'','','','','',$this->cal_options));
3266                         $this->t->set_var('lang_done','Cancel');
3267                         $this->t->set_var('lang_action','Editing Interview');
3268                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_update&interview=' .
3269                                           $interview . '&action=' . 'save'));
3270                 }
3271
3272                 if($action == 'view') {
3273                         $date = $this->db->f('date');
3274                         $this->t->set_var('cal_date','<input type=text size="10" maxlength="10" name="date" value="'.$date.'" readonly>');
3275                         $this->t->set_var('readonly','READONLY');
3276                         $this->t->set_var('disabled','DISABLED');
3277                         $this->t->set_var('lang_done','Done');
3278                         $this->t->set_var('lang_action','Viewing Interview');
3279                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_update&interview=' .
3280                                           $interview . '&action=' . 'edit'));
3281                 }
3282
3283                 $this->t->set_var('lang_reset','Clear Form');
3284                 $this->t->set_var('lang_add','Add Interview');
3285                 $this->t->set_var('lang_save','Save Changes');
3286                 $this->t->set_var('edithandle','');
3287                 $this->t->set_var('addhandle','');
3288
3289                 $this->t->pfp('out','form');
3290
3291                 if($action == 'view') { $this->t->set_var('lang_save','Edit Interview'); }
3292                 if($action == 'edit' || $action == 'view') { $this->t->pfp('addhandle','edit'); }
3293                 if($action == 'add') { $this->t->pfp('addhandle','add'); }
3294
3295                 $this->save_sessiondata(); 
3296         }
3297
3298         function vis_view()
3299         {
3300                 $this->t->set_file(array('vis_view_t' => 'vis_view.tpl'));
3301                 $this->t->set_block('vis_view_t','visit_list','list1');
3302                 $this->t->set_block('vis_view_t','family_list','list2');
3303
3304                 $this->t->set_var('lang_name','Family Name');
3305                 $this->t->set_var('lang_date','Date');
3306
3307                 $this->t->set_var('vis_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_view'));
3308                 $this->t->set_var('vis_link_title','View Yearly Visits');
3309
3310                 $this->t->set_var('schedule_vis_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_sched'));
3311                 $this->t->set_var('schedule_vis_link_title','Schedule Yearly Visits');
3312
3313                 $this->t->set_var('linkurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_view'));
3314                 $num_years = get_var('num_years',array('GET','POST'));
3315                 if($num_years == '') { $num_years = $this->default_vis_num_years; }
3316                 $this->t->set_var('num_years',$num_years);
3317                 if($num_years == 1) { 
3318                         $this->t->set_var('lang_num_years','Year of History'); 
3319                 } else {  
3320                         $this->t->set_var('lang_num_years','Years of History'); 
3321                 }
3322                 $this->t->set_var('lang_filter','Filter');
3323
3324                 $year = date('Y') - $num_years + 1;
3325                 $year_start = $year - 1 . "-12-31"; $year_end = $year + 1 . "-01-01";
3326
3327                 $sql = "SELECT * FROM tc_visit WHERE companionship=0 and date > '$year_start' ORDER BY date DESC";
3328                 $this->db->query($sql,__LINE__,__FILE__);
3329                 $total_records = $this->db->num_rows();
3330
3331                 $i = 0;
3332                 while ($this->db->next_record()) {
3333                         $visit_list[$i]['visit'] = $this->db->f('visit');
3334                         $visit_list[$i]['family'] = $this->db->f('family');
3335                         $visit_list[$i]['date']  = $this->db->f('date');
3336                         $i++;
3337                 }
3338
3339                 for ($i=0; $i < count($visit_list); $i++) {
3340                         $this->nextmatchs->template_alternate_row_color(&$this->t);
3341
3342                         $sql = "SELECT * FROM tc_family AS tf JOIN tc_individual AS ti WHERE tf.individual=ti.individual AND tf.family=".$visit_list[$i]['family']." AND ti.steward='$this->default_stewardship'";
3343                         $this->db->query($sql,__LINE__,__FILE__);
3344                         $this->db->next_record();
3345
3346                         $this->t->set_var('family',$visit_list[$i]['family']);
3347                         $this->t->set_var('family_name',$this->db->f('name'));
3348                         $this->t->set_var('date',$visit_list[$i]['date']);
3349
3350                         $link_data['menuaction'] = 'tc.tc.vis_update';
3351                         $link_data['visit'] = $visit_list[$i]['visit'];
3352                         $link_data['name'] = $this->db->f('name');
3353                         $link_data['date'] = $visit_list[$i]['date'];
3354                         $link_data['action'] = 'view';
3355                         $this->t->set_var('view',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
3356                         $this->t->set_var('lang_view','View');
3357
3358                         $link_data['menuaction'] = 'tc.tc.vis_update';
3359                         $link_data['visit'] = $visit_list[$i]['visit'];
3360                         $link_data['name'] = $this->db->f('name');
3361                         $link_data['date'] = $visit_list[$i]['date'];
3362                         $link_data['action'] = 'edit';
3363                         $this->t->set_var('edit',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
3364                         $this->t->set_var('lang_edit','Edit');
3365
3366                         $this->t->fp('list1','visit_list',True);
3367                 }
3368
3369                 // List the families that are available to record a visit against
3370                 $sql = "SELECT * FROM tc_family AS tf JOIN tc_individual AS ti WHERE tf.individual=ti.individual AND tf.companionship != 0 AND tf.valid=1 AND ti.steward='$this->default_stewardship'";
3371                 $this->db->query($sql,__LINE__,__FILE__);
3372                 $total_records = $this->db->num_rows();
3373
3374                 $i = 0;
3375                 while ($this->db->next_record()) {
3376                         $family_names[$i] = $this->db->f('name');
3377                         $family_ids[$i] = $this->db->f('family');
3378                         $i++;
3379                 } array_multisort($family_names, $family_ids);
3380
3381                 for ($i=0; $i < count($family_names); $i++) {
3382                         $link_data['menuaction'] = 'tc.tc.vis_update';
3383                         $link_data['visit'] = '';
3384                         $link_data['family'] = $family_ids[$i];
3385                         $link_data['action'] = 'add';
3386                         $link_data['name'] = $family_names[$i];
3387                         $this->t->set_var('add',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
3388
3389                         $this->t->set_var('name',$family_names[$i]);
3390                         if(($i+1) % 3 == 0) { 
3391                                 $this->t->set_var('table_sep',"</td></tr><tr>"); 
3392                         } else { 
3393                                 $this->t->set_var('table_sep',"</td>"); 
3394                         }
3395                         if(($i) % 3 == 0) { $this->nextmatchs->template_alternate_row_color(&$this->t); }
3396
3397                         $this->t->fp('list2','family_list',True);
3398                 }   
3399
3400                 $this->t->pfp('out','vis_view_t');
3401                 $this->save_sessiondata(); 
3402         }
3403
3404         function vis_update()
3405         {
3406                 $this->t->set_file(array('form' => 'vis_update.tpl'));
3407                 $this->t->set_block('form','add','addhandle');
3408                 $this->t->set_block('form','edit','edithandle');
3409
3410                 $this->t->set_var('done_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_view'));
3411                 $this->t->set_var('readonly','');
3412                 $this->t->set_var('disabled','');
3413
3414                 $action = get_var('action',array('GET','POST'));
3415                 $visit = get_var('visit',array('GET','POST'));
3416                 $family = get_var('family',array('GET','POST'));
3417                 $name = get_var('name',array('GET','POST'));
3418                 $date = get_var('date',array('GET','POST'));
3419                 $notes = get_var('notes',array('GET','POST'));
3420                 $companionship = 0;
3421
3422                 if($action == 'save') {
3423                         $notes = get_var('notes',array('POST'));
3424                         $this->db->query("UPDATE tc_visit set " .
3425                                          "  date='" . $date . "'" .
3426                                          ", notes=\"" . $notes . "\"" .
3427                                          " WHERE visit=" . $visit,__LINE__,__FILE__);
3428                         $this->vis_view();
3429                         return false;
3430                 }
3431
3432                 if($action == 'insert') {
3433                         $notes = get_var('notes',array('POST'));
3434                         $this->db->query("INSERT INTO tc_visit (family,companionship,date,notes) " .
3435                                          "VALUES ('" . $family . "','" . $companionship . "','" .
3436                                          $date . "',\"" . $notes . "\")",__LINE__,__FILE__);
3437                         $this->vis_view();
3438                         return false;
3439                 }
3440
3441                 if($action == 'add') {
3442                         $this->t->set_var('cal_date',$this->jscal->input('date','','','','','','',$this->cal_options));
3443                         $this->t->set_var('family', $family);
3444                         $this->t->set_var('visit', '');
3445                         $this->t->set_var('name', $name);
3446                         $this->t->set_var('date','');
3447                         $this->t->set_var('notes','');
3448                         $this->t->set_var('lang_done','Cancel');
3449                         $this->t->set_var('lang_action','Adding New Visit');
3450                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_update&family=' .
3451                                           $family . '&action=' . 'insert'));
3452                 }
3453
3454                 if($action == 'edit' || $action == 'view') {
3455                         $sql = "SELECT * FROM tc_visit WHERE visit=".$visit;
3456                         $this->db->query($sql,__LINE__,__FILE__);
3457                         $this->db->next_record();
3458                         $this->t->set_var('visit',$visit);
3459                         $this->t->set_var('name',$name);
3460                         $this->t->set_var('family', $family);
3461                         $this->t->set_var('date',$this->db->f('date'));
3462                         $this->t->set_var('notes',$this->db->f('notes'));
3463                 }
3464
3465                 if($action == 'edit') {
3466                         $this->t->set_var('cal_date',$this->jscal->input('date',$date,'','','','','',$this->cal_options));
3467                         $this->t->set_var('lang_done','Cancel');
3468                         $this->t->set_var('lang_action','Editing Visit');
3469                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_update&visit=' .
3470                                           $visit . '&action=' . 'save'));
3471                 }
3472
3473                 if($action == 'view') {
3474                         $date = $this->db->f('date');
3475                         $this->t->set_var('cal_date','<input type=text size="10" maxlength="10" name="date" value="'.$date.'" readonly>');
3476                         $this->t->set_var('readonly','READONLY');
3477                         $this->t->set_var('disabled','DISABLED');
3478                         $this->t->set_var('lang_done','Done');
3479                         $this->t->set_var('lang_action','Viewing Visit');
3480                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_update&visit=' .
3481                                           $visit . '&action=' . 'edit'));
3482                 }
3483
3484                 $this->t->set_var('lang_reset','Clear Form');
3485                 $this->t->set_var('lang_add','Add Visit');
3486                 $this->t->set_var('lang_save','Save Changes');
3487                 $this->t->set_var('edithandle','');
3488                 $this->t->set_var('addhandle','');
3489
3490                 $this->t->pfp('out','form');
3491
3492                 if($action == 'view') { $this->t->set_var('lang_save','Edit Visit'); }
3493                 if($action == 'edit' || $action == 'view') { $this->t->pfp('addhandle','edit'); }
3494                 if($action == 'add') { $this->t->pfp('addhandle','add'); }
3495
3496                 $this->save_sessiondata(); 
3497         }
3498
3499         function att_view()
3500         {
3501                 $monthnum['Jan']=1; $monthnum['Feb']=2; $monthnum['Mar']=3; $monthnum['Apr']=4;
3502                 $monthnum['May']=5; $monthnum['Jun']=6; $monthnum['Jul']=7; $monthnum['Aug']=8;
3503                 $monthnum['Sep']=9; $monthnum['Oct']=10; $monthnum['Nov']=11; $monthnum['Dec']=12;
3504
3505                 $this->t->set_file(array('att_view_t' => 'att_view.tpl'));
3506                 $this->t->set_block('att_view_t','act_list','list');
3507
3508                 $this->t->set_block('att_view_t','month_list','list1');
3509                 $this->t->set_block('att_view_t','header_list','list2');
3510                 $this->t->set_block('att_view_t','individual_list','list3');
3511
3512                 $this->t->set_var('linkurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.att_view'));
3513                 $num_quarters = get_var('num_quarters',array('GET','POST'));
3514                 if($num_quarters == '') { $num_quarters = $this->default_att_num_quarters; }
3515                 $this->t->set_var('num_quarters',$num_quarters);
3516                 $this->t->set_var('lang_filter','Filter');
3517                 if($num_quarters == 1) { 
3518                         $this->t->set_var('lang_num_quarters','Quarter of History'); 
3519                 } else { 
3520                         $this->t->set_var('lang_num_quarters','Quarters of History'); 
3521                 }
3522
3523                 $num_months = $num_quarters * 3;
3524                 $current_month = $this->current_month;
3525                 if($current_month >= 1 && $current_month <= 3) { $current_month=3; }
3526                 else if($current_month >= 4 && $current_month <= 6) { $current_month=6; }
3527                 else if($current_month >= 7 && $current_month <= 9) { $current_month=9; }
3528                 else if($current_month >= 10 && $current_month <= 12) { $current_month=12; }
3529
3530                 $sql = "SELECT * FROM tc_individual where steward='$this->default_stewardship' and valid=1";
3531                 $this->db->query($sql,__LINE__,__FILE__);
3532                 $i=0;
3533                 while ($this->db->next_record()) {
3534                         $individual_name[$i] = $this->db->f('name');
3535                         $individual[$i] = $this->db->f('individual');
3536                         $i++;
3537                 }
3538                 array_multisort($individual_name, $individual);
3539
3540                 // Create a list of sunday dates for a window of 3 months back and current month
3541                 $i=0; 
3542                 $last_time = 0; 
3543                 $found_sunday = 0;
3544                 $sunday_list[0]['date'] = date("Y-m-d", mktime(0, 0, 0, ($current_month-$num_months)+1, 1, date("y")));
3545                 $last_date = explode("-",$sunday_list[0]['date']);
3546                 $last_time = mktime(0, 0, 0, $last_date[1], $last_date[2], $last_date[0]);
3547                 $time_limit = mktime(0, 0, 0, $current_month, 31, date("y"));
3548                 while($last_time < $time_limit) {
3549                         $day = date("w",$last_time);
3550                         if(date("w",$last_time) == 0) {
3551                                 $sunday_list[$i]['date'] = date("Y-m-d", $last_time);
3552                                 $last_date = explode("-",$sunday_list[$i]['date']);
3553                                 $last_time = mktime(0, 0, 0, $last_date[1], $last_date[2], $last_date[0]);
3554                                 $sunday_list[$i]['day'] = $last_date[2];
3555                                 $sunday_list[$i]['month'] = date("M",$last_time);
3556                                 $sunday_list[$i]['year'] = $last_date[0];
3557                                 $found_sunday = 1;
3558                                 $last_date = $sunday_list[$i]['date'];
3559                         }
3560                         $last_time += 90000;
3561                         if($found_sunday) { $i++; $found_sunday=0; }
3562                 }
3563
3564                 $total_individuals = count($individual);
3565                 $old_month=$sunday_list[0]['month']; $span=0;
3566                 for ($i=0; $i < count($sunday_list); $i++) {
3567                         $date = $sunday_list[$i]['date'];
3568                         $this->t->set_var('date',$sunday_list[$i]['date']);
3569                         $this->t->set_var('day',$sunday_list[$i]['day']);
3570                         if(($old_month != $sunday_list[$i]['month']) || $i == count($sunday_list)-1) {
3571                                 if($i == count($sunday_list)-1) { $span++; }
3572                                 $cur_month = $sunday_list[$i]['month'];
3573                                 $old_month = $sunday_list[$i]['month'];   
3574                                 $link_data['menuaction'] = 'tc.tc.att_update';
3575                                 $link_data['month'] = $sunday_list[$i-1]['month'];
3576                                 $link_data['year'] = $sunday_list[$i-1]['year'];
3577                                 $link_data['action'] = 'update_month';
3578                                 $cur_month = $sunday_list[$i-1]['month'];
3579                                 $cur_year = $sunday_list[$i-1]['year'];
3580                                 $header_row .= "<th><font size=-3>$cur_month&nbsp;$cur_year</font></th>";
3581                                 $this->t->set_var('update_month',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
3582                                 $this->t->set_var('month',$sunday_list[$i-1]['month']);
3583                                 $this->t->set_var('year',$sunday_list[$i-1]['year']);
3584                                 $this->t->set_var('span',$span); $span=0;
3585                                 $this->t->fp('list1','month_list',True);
3586                         }
3587                         $span++;
3588                 }
3589                 $this->t->set_var('total_individuals',$total_individuals);
3590                 $this->t->set_var('header_row',$header_row);
3591
3592                 $individual_width=200; $att_width=25; $total_width=$individual_width; 
3593                 for ($i=0; $i < count($sunday_list); $i++) {
3594                         $link_data['menuaction'] = 'tc.tc.att_update';
3595                         $link_data['month'] = $sunday_list[$i]['month'];
3596                         $link_data['year'] = $sunday_list[$i]['year'];
3597                         $link_data['day'] = $sunday_list[$i]['day'];
3598                         $link_data['date'] = $sunday_list[$i]['date'];
3599                         $link_data['action'] = 'update_day';
3600                         $this->t->set_var('update_day',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
3601                         $this->t->set_var('date',$sunday_list[$i]['date']);
3602                         $this->t->set_var('day',$sunday_list[$i]['day']);
3603                         $this->t->set_var('month',$sunday_list[$i]['month']);
3604                         $this->t->set_var('year',$sunday_list[$i]['year']);
3605                         $this->t->fp('list2','header_list',True);
3606                         $total_width += $att_width;
3607                         $attendance[$monthnum[$sunday_list[$i]['month']]]=0;
3608                 }
3609
3610                 for ($i=0; $i < count($individual); $i++) {
3611                         $att_table = "";
3612                         $this->nextmatchs->template_alternate_row_color(&$this->t);
3613                         $this->t->set_var('individual_name',$individual_name[$i]);
3614                         #print "checking for individual: " . $individual[$i] . "<br>";
3615                         for ($j=0; $j < count($sunday_list); $j++) {
3616                                 #print "checking for date: " .  $sunday_list[$j]['date'] . "<br>";
3617                                 #print "SELECT * FROM tc_attendance WHERE date='"
3618                                 #  . $sunday_list[$j]['date'] . "' AND individual=" . $individual[$i] . "<br>";
3619                                 $sql = "SELECT * FROM tc_attendance WHERE date='" .
3620                                        $sunday_list[$j]['date'] . "' AND individual=" . $individual[$i];
3621                                 $this->db->query($sql,__LINE__,__FILE__);
3622                                 if($this->db->next_record()) {
3623                                         $cur_month = $sunday_list[$j]['month'];
3624                                 if($attended[$i][$cur_month] != 1) {
3625                                         $attended[$i][$cur_month]=1;
3626                                         $attendance[$monthnum[$cur_month]]++;
3627                                 } 
3628                                         $att_table .= '<td align=center><img src="images/checkmark.gif"></td>';
3629                                 } else {
3630                                         $att_table .= '<td>&nbsp;</td>';
3631                                 }
3632                         }
3633                         $this->t->set_var('att_table',$att_table);
3634                         $this->t->fp('list3','individual_list',True);
3635                 }
3636                 $this->t->set_var('total_width',$total_width);
3637                 $this->t->set_var('individual_width',$individual_width);
3638                 $this->t->set_var('att_width',$att_width);
3639
3640                 # Now calculate attendance for these months
3641                 $attendance_str = "";
3642                 $nonattendance_str = "";
3643                 $aveattendance_str = "";
3644                 $avenonattendance_str = "";
3645                 $num_months=0;
3646                 $ave_total_attended=0;
3647                 ksort($attendance);
3648                 foreach($attendance as $att => $value) {
3649                         $total_attended = $attendance[$att];
3650                         $ave_total_attended += $attendance[$att]; $num_months++;
3651                         $percent = ceil(($total_attended / $total_individuals)*100);
3652                         $attendance_str.="<td align=center><font size=-2><b>$total_attended ($percent%)</b></font></td>";
3653                         $total_nonattended = $total_individuals - $total_attended;
3654                         $percent = ceil(($total_nonattended / $total_individuals)*100);
3655                         $nonattendance_str.="<td align=center><font size=-2><b>$total_nonattended ($percent%)</b></font></td>";
3656
3657                         $total_attended = ceil(($ave_total_attended / $num_months));
3658                         $percent = ceil(($total_attended / $total_individuals)*100);
3659                         $aveattendance_str .= "<td align=center><font size=-2><b>$total_attended ($percent%)</b></font></td>";
3660                         $total_attended = $total_individuals - ceil(($ave_total_attended / $num_months));
3661                         $percent = ceil(($total_attended / $total_individuals)*100);
3662                         $avenonattendance_str .= "<td align=center><font size=-2><b>$total_attended ($percent%)</b></font></td>";
3663                 }
3664
3665                 $this->t->set_var('attendance',$attendance_str);
3666                 $this->t->set_var('aveattendance',$aveattendance_str);
3667                 $this->t->set_var('nonattendance',$nonattendance_str);
3668                 $this->t->set_var('avenonattendance',$avenonattendance_str);
3669
3670                 $this->t->pfp('out','att_view_t');
3671                 $this->save_sessiondata(); 
3672         }
3673
3674         function att_update()
3675         {
3676                 $monthnum['Jan']=1; $monthnum['Feb']=2; $monthnum['Mar']=3; $monthnum['Apr']=4;
3677                 $monthnum['May']=5; $monthnum['Jun']=6; $monthnum['Jul']=7; $monthnum['Aug']=8;
3678                 $monthnum['Sep']=9; $monthnum['Oct']=10; $monthnum['Nov']=11; $monthnum['Dec']=12;
3679
3680                 $this->t->set_file(array('form' => 'att_update.tpl'));
3681                 $this->t->set_block('form','edit','edithandle');
3682
3683                 $this->t->set_block('form','month_list','list1');
3684                 $this->t->set_block('form','header_list','list2');
3685                 $this->t->set_block('form','individual_list','list3');
3686
3687                 $this->t->set_var('done_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.att_view'));
3688
3689                 $action = get_var('action',array('GET','POST'));
3690                 $month = get_var('month',array('GET','POST'));
3691                 $year = get_var('year',array('GET','POST'));
3692                 $day = get_var('day',array('GET','POST'));
3693                 $date = get_var('date',array('GET','POST'));
3694
3695                 if($action == 'save_month' || $action == 'save_day') {
3696                         $new_data = get_var('individuals_attended',array('POST'));
3697                         $month = $monthnum[$month]; if($month < 10) { $month = "0" . $month; }
3698
3699                         if($action == 'save_month') {
3700                                 $this->db->query("DELETE from tc_attendance where date LIKE '".$year."-".$month."-%'",__LINE__,__FILE__);
3701                         }
3702
3703                         if($action == 'save_day') {
3704                                 $this->db->query("DELETE from tc_attendance where date LIKE '".$year."-".$month."-".$day."'",__LINE__,__FILE__);
3705                         }   
3706
3707                         foreach ($new_data as $data) {
3708                                 $data_array = explode("-",$data);
3709                                 $indiv = $data_array[0];
3710                                 $date  = "$data_array[1]-$data_array[2]-$data_array[3]";              
3711                                 $this->db->query("INSERT INTO tc_attendance (individual,date) " .
3712                                                  "VALUES (" . $indiv . ",'". $date . "')",__LINE__,__FILE__);
3713                         }
3714
3715                         $this->att_view();
3716                         return false;
3717                 }
3718
3719                 $sql = "SELECT * FROM tc_individual where steward='$this->default_stewardship' and valid=1";
3720                 $this->db->query($sql,__LINE__,__FILE__);
3721                 $i=0;
3722                 while ($this->db->next_record()) {
3723                         $indiv_name[$i] = $this->db->f('name');
3724                         $individual[$i] = $this->db->f('individual');
3725                         $indiv_attending[$individual[$i]] = $this->db->f('attending');
3726                         $i++;
3727                 }
3728                 array_multisort($indiv_name, $individual);
3729
3730                 if($action == 'update_month') {
3731                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.att_update&action=save_month'));
3732                         $i=0; 
3733                         $last_time = 0; 
3734                         $found_sunday = 0;
3735                         $sunday_list[0]['date'] = date("Y-m-d", mktime(0, 0, 0, $monthnum[$month], 1, $year));
3736                         $last_date = explode("-",$sunday_list[0]['date']);
3737                         $last_time = mktime(0, 0, 0, $last_date[1], $last_date[2], $last_date[0]);
3738                         $time_limit = mktime(0, 0, 0, $monthnum[$month], 31, $year);
3739                         while($last_time <= $time_limit) {
3740                                 $day = date("w",$last_time);
3741                                         if(date("w",$last_time) == 0) { 
3742                                         $sunday_list[$i]['date'] = date("Y-m-d", $last_time); 
3743                                         $last_date = explode("-",$sunday_list[$i]['date']);
3744                                         $last_time = mktime(0, 0, 0, $last_date[1], $last_date[2], $last_date[0]);
3745                                         $sunday_list[$i]['day'] = $last_date[2];
3746                                         $sunday_list[$i]['month'] = date("M",$last_time);
3747                                         $sunday_list[$i]['year'] = $last_date[0];
3748                                         $found_sunday = 1; 
3749                                 }
3750                                 $last_time += 90000;
3751                                 if($found_sunday) { $i++; $found_sunday=0; }
3752                         }
3753
3754                         $this->t->set_var('span', $i);
3755                         $this->t->set_var('month',$sunday_list[$i-1]['month']);
3756                         $this->t->set_var('year',$sunday_list[$i-1]['year']);
3757                         $this->t->fp('list1','month_list',True);
3758                         $indiv_width=200; $att_width=25; $total_width=$indiv_width;
3759                         for ($i=0; $i < count($sunday_list); $i++) {
3760                                 $link_data['menuaction'] = 'tc.tc.att_update';
3761                                 $link_data['month'] = $sunday_list[$i]['month'];
3762                                 $link_data['year'] = $sunday_list[$i]['year'];
3763                                 $link_data['day'] = $sunday_list[$i]['day'];
3764                                 $link_data['date'] = $sunday_list[$i]['date'];
3765                                 $link_data['action'] = 'update_day';
3766                                 $this->t->set_var('update_day',$GLOBALS['phpgw']->link('/tc/index.php',$link_data));
3767                                 $this->t->set_var('date',$sunday_list[$i]['date']);
3768                                 $this->t->set_var('day',$sunday_list[$i]['day']);
3769                                 $this->t->set_var('month',$sunday_list[$i]['month']);
3770                                 $this->t->set_var('year',$sunday_list[$i]['year']);
3771                                 $this->t->fp('list2','header_list',True);
3772                                 $total_width += $att_width;
3773                         }     
3774                 }
3775
3776                 if($action == 'update_day') {
3777                         $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.att_update&action=save_day'));
3778                         $sunday_list[0]['date'] = date("Y-m-d", mktime(0, 0, 0, $monthnum[$month], $day, $year));
3779                         $this->t->set_var('month',$month);
3780                         $this->t->set_var('year',$year);
3781                         $this->t->fp('list1','month_list',True);
3782                         $this->t->set_var('date',$date);
3783                         $this->t->set_var('day',$day);
3784                         $this->t->set_var('month',$month);
3785                         $this->t->set_var('year',$year);
3786                         $this->t->fp('list2','header_list',True);
3787                 }           
3788
3789                 for ($i=0; $i < count($individual); $i++) {
3790                         $att_table = "";
3791                         $this->nextmatchs->template_alternate_row_color(&$this->t);
3792                         $this->t->set_var('individual_name',$indiv_name[$i]);
3793                         for ($j=0; $j < count($sunday_list); $j++) {
3794                                 $sql = "SELECT * FROM tc_attendance WHERE date='" .
3795                                        $sunday_list[$j]['date'] . "' AND individual=" . $individual[$i];
3796                                 $this->db->query($sql,__LINE__,__FILE__);
3797                                 $value = $individual[$i] . "-" . $sunday_list[$j]['date'];
3798                                 if($this->db->next_record()) {
3799                                         $att_table .= '<td align=center><input type="checkbox" name="individuals_attended[]" value="'.$value.'" checked></td>';
3800                                 } else if($indiv_attending[$individual[$i]] == 1) {
3801                                         $att_table .= '<td align=center><input type="checkbox" name="individuals_attended[]" value="'.$value.'" checked></td>';
3802                                 } else {
3803                                         $att_table .= '<td align=center><input type="checkbox" name="individuals_attended[]" value="'.$value.'"></td>';
3804                                 }
3805                         }
3806                         $this->t->set_var('att_table',$att_table);
3807                         $this->t->fp('list3','individual_list',True);
3808                 } 
3809
3810                 $this->t->set_var('lang_done', 'Cancel');
3811                 $this->t->set_var('lang_reset','Clear Form');
3812                 $this->t->set_var('lang_save','Save Changes');
3813
3814                 $this->t->pfp('out','form');
3815                 $this->t->pfp('addhandle','edit');
3816
3817                 $this->save_sessiondata();       
3818         }
3819
3820         function dir_view()
3821         {
3822                 $this->t->set_file(array('dir_view_t' => 'dir_view.tpl'));
3823                 $this->t->set_block('dir_view_t','dir_list','list');
3824
3825                 $sql = "SELECT * FROM tc_individual where valid=1 and hh_position='Head of Household' ORDER BY name ASC";
3826                 $this->db->query($sql,__LINE__,__FILE__);
3827                 $i=0;
3828                 while ($this->db->next_record()) {
3829                         $parent[$i]['id'] = $this->db->f('individual');
3830                         $parent[$i]['name'] = $this->db->f('name');
3831                         $parent[$i]['phone'] = $this->db->f('phone');
3832                         $parent[$i]['address'] = $this->db->f('address');
3833                         $i++;
3834                 }   
3835
3836                 for ($i=0; $i < count($parent); $i++) {
3837                         $name = $parent[$i]['name'];
3838                         $phone = $parent[$i]['phone'];
3839                         $address = $parent[$i]['address'];
3840                         $this->t->set_var('name', $name);
3841                         $this->t->set_var('address', $address);
3842                         $this->t->set_var('phone', $phone);
3843                         $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
3844                         $this->t->set_var('tr_color',$tr_color);
3845                         $this->t->fp('list','dir_list',True);
3846                         //print "$phone $name $address<br>";
3847                 }
3848                 $this->t->pfp('out','dir_view_t');
3849                 $this->save_sessiondata();   
3850         }
3851   
3852         function org_view()
3853         {
3854                 $this->t->set_file(array('org_view_t' => 'org_view.tpl'));
3855                 $this->t->set_block('org_view_t','calling_list','list1');
3856                 $this->t->set_block('org_view_t','org_list','list2');
3857
3858                 # Display a list ordered alphabetically
3859                 $sql = "SELECT * FROM tc_calling AS tc JOIN tc_individual AS ti WHERE tc.individual=ti.individual ORDER BY name ASC";
3860                 $this->db->query($sql,__LINE__,__FILE__);
3861                 $i=0;
3862                 while ($this->db->next_record()) {
3863                         $calling[$i]['name'] = $this->db->f('name');
3864                         $calling[$i]['position'] = $this->db->f('position');
3865                         $calling[$i]['sustained'] = $this->db->f('sustained');
3866                         $calling[$i]['organization'] = $this->db->f('organization');
3867                         $i++;
3868                 }   
3869                 for ($i=0; $i < count($calling); $i++) {
3870                         $name = $calling[$i]['name'];
3871                         $position = $calling[$i]['position'];
3872                         $sustained = $calling[$i]['sustained'];
3873                         $organization = $calling[$i]['organization'];
3874                         $this->t->set_var('name', $name);
3875                         $this->t->set_var('position', $position);
3876                         $this->t->set_var('sustained', $sustained);
3877                         $this->t->set_var('organization', $organization);
3878                         $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
3879                         $this->t->set_var('tr_color',$tr_color);
3880                         $this->t->fp('list1','calling_list',True);
3881                 }
3882
3883                 # Display a list ordered by organization
3884                 $sql = "SELECT * FROM tc_calling AS tc JOIN tc_individual AS ti where tc.individual=ti.individual ORDER BY organization ASC";
3885                 $this->db->query($sql,__LINE__,__FILE__);
3886                 $i=0;
3887                 while ($this->db->next_record()) {
3888                         $calling[$i]['name'] = $this->db->f('name');
3889                         $calling[$i]['position'] = $this->db->f('position');
3890                         $calling[$i]['sustained'] = $this->db->f('sustained');
3891                         $calling[$i]['organization'] = $this->db->f('organization');
3892                         $i++;
3893                 }   
3894                 for ($i=0; $i < count($calling); $i++) {
3895                         $name = $calling[$i]['name'];
3896                         $position = $calling[$i]['position'];
3897                         $sustained = $calling[$i]['sustained'];
3898                         $organization = $calling[$i]['organization'];
3899                         $this->t->set_var('name', $name);
3900                         $this->t->set_var('position', $position);
3901                         $this->t->set_var('sustained', $sustained);
3902                         $this->t->set_var('organization', $organization);
3903                         $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
3904                         $this->t->set_var('tr_color',$tr_color);
3905                         $this->t->fp('list2','org_list',True);
3906                 }
3907
3908                 $this->t->pfp('out','org_view_t');
3909                 $this->save_sessiondata();   
3910         }
3911   
3912         function schedule()
3913         {
3914                 $this->t->set_file(array('sched_t' => 'schedule.tpl'));
3915                 $this->t->set_block('sched_t','presidency_list','list');
3916
3917                 $action = get_var('action',array('GET','POST'));
3918
3919                 $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.schedule&action=save'));
3920                 $this->t->set_var('title','Scheduling Tool');
3921
3922                 $this->t->set_var('lang_save','Save Schedule');
3923                 $this->t->set_var('lang_reset','Cancel');
3924
3925                 $this->t->set_var('schedule_vis_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.vis_sched'));
3926                 $this->t->set_var('schedule_vis_link_title','Schedule Yearly Visits');
3927
3928                 $this->t->set_var('schedule_int_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.int_sched'));
3929                 $this->t->set_var('schedule_int_link_title','Schedule Hometeaching Interviews');
3930
3931                 $this->t->set_var('schedule_ppi_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.ppi_sched'));
3932                 $this->t->set_var('schedule_ppi_link_title','Schedule ' . $this->ppi_frequency_label . ' PPIs');
3933
3934                 $date_width=160; $time_width=220; $indiv_width=170; $family_width=180; $location_width=100;
3935                 $table_width=$date_width + $time_width + $indiv_width + $family_width + $location_width;
3936                 $header_row = "<th width=$date_width><font size=-2>Date</th>";
3937                 $header_row.= "<th width=$time_width><font size=-2>Time</th>";      
3938                 $header_row.= "<th width=$indiv_width><font size=-2>Individual</th>";
3939                 $header_row.= "<th width=$family_width><font size=-2>Family</th>";
3940                 $header_row.= "<th width=$location_width><font size=-2>Location</th>";
3941                 $table_data = "";
3942
3943                 $sql = "SELECT * FROM tc_presidency AS tp JOIN tc_individual AS ti WHERE tp.individual=ti.individual AND tp.valid=1 GROUP BY tp.individual ORDER BY ti.name ASC";
3944                 $this->db->query($sql,__LINE__,__FILE__);
3945                 $i=0;
3946                 while ($this->db->next_record()) {
3947                         $presidency_data[$i]['id'] = $this->db->f('presidency');
3948                         $presidency_data[$i]['name'] = $this->db->f('name');
3949                         $presidency_data[$i]['indiv'] = $this->db->f('individual');
3950                         $presidency2name[$presidency_data[$i]['id']] = $presidency_data[$i]['name'];
3951                         $presidency2indiv[$presidency_data[$i]['id']] = $presidency_data[$i]['indiv'];
3952                         $i++;
3953                 }
3954
3955                 $sql = "SELECT * FROM tc_family AS tf JOIN tc_individual AS ti WHERE tf.individual=ti.individual AND ti.steward='$this->default_stewardship' AND tf.valid=1 AND tf.individual != 0 ORDER BY ti.name ASC";
3956                 $this->db->query($sql,__LINE__,__FILE__);
3957                 $i=0;
3958                 while ($this->db->next_record()) {
3959                         $family_id[$i] = $this->db->f('family');
3960                         $family_name[$i] = $this->db->f('name');
3961                         $familyid2name[$family_id[$i]] = $family_name[$i];
3962                         $familyid2address[$family_id[$i]] = $this->db->f('address');
3963                         $i++;
3964                 }
3965                 array_multisort($family_name, $family_id);
3966
3967                 if($action == 'save') {
3968                         $new_data = get_var('sched',array('POST'));
3969                         foreach ($new_data as $presidency_array) {
3970                                 foreach ($presidency_array as $entry) {
3971                                         $presidency = $entry['presidency'];
3972                                         $appointment = $entry['appointment'];
3973                                         $location = $entry['location'];
3974                                         $date = $entry['date'];
3975                                         $hour = $entry['hour'];
3976                                         $minute = $entry['minute'];
3977                                         $pm = $entry['pm'];
3978                                         $indiv = $entry['individual'];
3979                                         $family = $entry['family'];
3980                                         $location = $entry['location'];
3981                                         if($pm) { $hour = $hour + 12; }
3982                                         $time = $hour.':'.$minute.':'.'00';
3983                                         $uid = 0;
3984
3985                                         // Zero out family or individual if they are invalid
3986                                         if($indiv == "") { $indiv=0; }
3987                                         if($family == "") { $family=0; }
3988
3989                                         // Update our location
3990                                         if($location == "") {
3991                                                 if($family > 0) {
3992                                                         $family_name_array = explode(",", $familyid2name[$family]);
3993                                                         $family_last_name = $family_name_array[0];
3994                                                         $family_address = $familyid2address[$family];
3995                                                         $location = "$family_last_name"." home ($family_address)";
3996                                                 } else if($indiv > 0) {
3997                                                         $supervisor_name_array = explode(",",$presidency2name[$presidency]);
3998                                                         $supervisor_last_name = $supervisor_name_array[0];
3999                                                         #print "presidency2indiv: $presidency $presidency2indiv[$presidency]<br>";
4000                                                         $sql = "SELECT * FROM tc_individual where individual='$presidency2indiv[$presidency]'";
4001                                                         $this->db2->query($sql,__LINE__,__FILE__);
4002                                                         if($this->db2->next_record()) {
4003                                                                 $supervisor_address = $this->db2->f('address');
4004                                                         }
4005                                                         $location = "$supervisor_last_name"." home ($supervisor_address)";
4006                                                 }
4007                                         }
4008
4009                                         // Zero out the family or individual if date = NULL
4010                                         if($date == "") {
4011                                                 $indiv = 0;
4012                                                 $family = 0;
4013                                                 $location = "";
4014                                         }
4015
4016                                         if(($indiv == 0) && ($family == 0)) { $location = ""; }
4017
4018                                         // Update an existing appointment
4019                                         if($appointment < $this->max_appointments)
4020                                         {
4021                                                 //Only perform a database update if we have made a change to this appointment
4022                                                 $sql = "SELECT * FROM tc_appointment where " .
4023                                                        "appointment='$appointment'" .
4024                                                        " and presidency='$presidency'" .
4025                                                        " and individual='$indiv'" .
4026                                                        " and family='$family'" .
4027                                                        " and date='$date'" .
4028                                                        " and time='$time'" .
4029                                                        " and location='$location'";
4030                                                 $this->db->query($sql,__LINE__,__FILE__);
4031                                                 if(!$this->db->next_record()) {
4032                                                         $old_date = $this->db->f('date');
4033                                                         $old_time = $this->db->f('time');
4034                                                         $this->db2->query("UPDATE tc_appointment set" .
4035                                                                           " family=" . $family . 
4036                                                                           " ,individual=" . $indiv . 
4037                                                                           " ,date='" . $date . "'" .
4038                                                                           " ,time='" . $time . "'" .
4039                                                                           " ,location='" . $location . "'" .
4040                                                                           " ,presidency='" . $presidency . "'" .
4041                                                                           " WHERE appointment=" . $appointment,__LINE__,__FILE__);
4042
4043                                                         // Email the appointment
4044                                                         $this->email_appt($appointment);
4045                                                 }
4046                                         }
4047
4048                                         // Add a new appointment
4049                                         else if(($appointment >= $this->max_appointments) && ($date != "") && ($time != ""))
4050                                         {
4051                                                 //print "adding entry: appt=$appointment date: $date time: $time individual: $indiv family: $family<br>";
4052                                                 $this->db2->query("INSERT INTO tc_appointment (appointment,presidency,family,individual,date,time,location,uid) " .
4053                                                                   "VALUES (NULL,'" . $presidency . "','" . $family . "','" . $indiv . "','" .
4054                                                                   $date . "','" . $time  . "','" . $location . "','" . $uid ."')",__LINE__,__FILE__);
4055
4056                                                 // Now reselect this entry from the database to see if we need
4057                                                 // to send an appointment out for it.
4058                                                 $sql = "SELECT * FROM tc_appointment where " .
4059                                                        "individual='$indiv'" .
4060                                                        " and family='$family'" .
4061                                                        " and presidency='$presidency'" .
4062                                                        " and date='$date'" .
4063                                                        " and time='$time'" .
4064                                                        " and uid='$uid'" .
4065                                                        " and location='$location'";
4066                                                 $this->db3->query($sql,__LINE__,__FILE__);
4067                                                 if($this->db3->next_record()) {
4068                                                         // Email the appointment if warranted
4069                                                         if(($date != "") && ($time != "") && (($indiv > 0) || $family > 0)) { 
4070                                                                 $this->email_appt($this->db3->f('appointment'));
4071                                                         }
4072                                                 }
4073                                         }
4074                                 }
4075                         }
4076
4077                         $take_me_to_url = $GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.schedule');
4078                         //Header('Location: ' . $take_me_to_url);
4079                 }
4080
4081                 $sql = "SELECT * FROM tc_individual where steward='$this->default_stewardship' and valid=1 ORDER BY individual ASC";
4082                 $this->db->query($sql,__LINE__,__FILE__);
4083                 $i=0;
4084                 while ($this->db->next_record()) {
4085                         $individual[$i] = $this->db->f('individual');
4086                         $indiv_name[$i] = $this->db->f('name');
4087                         $indiv_phone[$individual[$i]] = $this->db->f('phone');
4088                         $i++;
4089                 }
4090                 array_multisort($indiv_name, $individual);
4091
4092                 for ($i=0; $i < count($presidency_data); $i++) {
4093                         $presidency = $presidency_data[$i]['id'];
4094                         $interviewer = $presidency_data[$i]['individual'];
4095                         $name = $presidency_data[$i]['name'];
4096                         $this->t->set_var('presidency_name',$name);
4097                         $table_data="";
4098
4099                         // query the database for all the appointments
4100                         $sql = "SELECT * FROM tc_appointment where presidency=$presidency and date>=CURDATE() ORDER BY date ASC, time ASC";
4101                         $this->db->query($sql,__LINE__,__FILE__);
4102
4103                         // Prefill any existing appointment slots
4104                         while ($this->db->next_record()) {
4105                                 $appointment = $this->db->f('appointment');
4106                                 $indiv = $this->db->f('individual');
4107                                 $family = $this->db->f('family');
4108                                 $location = $this->db->f('location');
4109
4110                                 if($location == "") {
4111                                         if($family > 0) {
4112                                                 $family_name_array = explode(",", $familyid2name[$family]);
4113                                                 $family_last_name = $family_name_array[0];
4114                                                 $family_address = $familyid2address[$family];
4115                                                 $location = "$family_last_name"." home ($family_address)";
4116                                         } else if($indiv > 0) {
4117                                                 $supervisor_name_array = explode(",",$presidency2name[$presidency]);
4118                                                 $supervisor_last_name = $supervisor_name_array[0];
4119                                                 $sql = "SELECT * FROM tc_individual where individual='$presidency2indiv[$presidency]'";
4120                                                 $this->db2->query($sql,__LINE__,__FILE__);
4121                                                 if($this->db2->next_record()) {
4122                                                         $supervisor_address = $this->db2->f('address');
4123                                                 }
4124                                                 $location = "$supervisor_last_name"." home ($supervisor_address)";
4125                                         }
4126                                 }
4127
4128                                 $date = $this->db->f('date');
4129                                 $date_array = explode("-",$date);
4130                                 $year = $date_array[0]; $month = $date_array[1]; $day = $date_array[2];
4131                                 $day_string = date("l d-M-Y", mktime(0,0,0,$month,$day,$year));
4132
4133                                 $time = $this->db->f('time');
4134                                 $time_array = explode(":",$time);
4135                                 $hour = $time_array[0];
4136                                 $minute = $time_array[1];
4137                                 $pm = 0;
4138                                 if($hour > 12) { $pm=1; $hour = $hour - 12; }
4139                                 $time_string = date("g:i a", mktime($time_array[0], $time_array[1], $time_array[2]));
4140
4141                                 $table_data.= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
4142
4143                                 // Date selection
4144                                 $table_data.= '<td align=left>';
4145                                 $table_data.= $this->jscal->input('sched['.$presidency.']['.$appointment.'][date]',$date,'','','','','',$this->cal_options);
4146                                 $table_data.= '</td>';
4147
4148                                 // Hour & Minutes selection
4149                                 $table_data.= "<td align=center>";
4150                                 $table_data .= $this->get_time_selection_form($hour, $minute, $pm, $presidency, $appointment);
4151                                 $table_data.= "</td>";
4152
4153                                 // individual drop down list (for PPIs)
4154                                 $table_data.= '<td align=center><select name=sched['.$presidency.']['.$appointment.'][individual] STYLE="font-size : 8pt">';
4155                                 $table_data.= '<option value=0></option>';  
4156                                 for ($j=0; $j < count($individual); $j++) {
4157                                         $id = $individual[$j];
4158                                         $name = $indiv_name[$j];
4159                                         if($individual[$j] == $indiv) {
4160                                                 $selected[$id] = 'selected="selected"'; 
4161                                         } else {
4162                                                 $selected[$id] = ''; 
4163                                         }
4164                                         $table_data.= '<option value='.$id.' '.$selected[$id].'>'.$name.'</option>';
4165                                 }
4166                                 $table_data.='</select></td>';
4167
4168                                 // Family drop down list (for Visits)
4169                                 $table_data.= '<td align=center><select name=sched['.$presidency.']['.$appointment.'][family] STYLE="font-size : 8pt">';
4170                                 $table_data.= '<option value=0></option>';          
4171                                 for ($j=0; $j < count($individual); $j++) {
4172                                         $id = $family_id[$j];
4173                                         $name = $family_name[$j];
4174                                         if($family_id[$j] == $family) { 
4175                                                 $selected[$id] = 'selected="selected"'; 
4176                                         } else { 
4177                                                 $selected[$id] = ''; 
4178                                         }
4179                                         $table_data.= '<option value='.$id.' '.$selected[$id].'>'.$name.' Family</option>';
4180                                 }
4181                                 $table_data.='</select></td>';
4182
4183                                 // Location text box
4184                                 $table_data.= '<td align=center><input type=text size="25" maxlength="120" ';
4185                                 $table_data.= 'name="sched['.$presidency.']['.$appointment.'][location]" value="'.$location.'" STYLE="font-size : 8pt">';
4186
4187                                 $table_data.= '<input type=hidden name="sched['.$presidency.']['.$appointment.'][appointment]" value="'.$appointment.'">';
4188                                 $table_data.= '<input type=hidden name="sched['.$presidency.']['.$appointment.'][presidency]" value="'.$presidency.'">';
4189
4190                                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
4191                                 $this->t->set_var('tr_color',$tr_color);
4192                         }
4193
4194                         // Create blank appointment slot
4195                         for ($b=0; $b < 4; $b++) {
4196                                 $appointment = $this->max_appointments + $b;
4197                                 $table_data.= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
4198
4199                                 // Date selection
4200                                 $table_data.= '<td align=left>';
4201                                 $table_data.= $this->jscal->input('sched['.$presidency.']['.$appointment.'][date]','','','','','','',$this->cal_options);
4202                                 $table_data.= '</td>';
4203
4204                                 // Time selection
4205                                 $table_data.= "<td align=center>";
4206                                 $table_data .= $this->get_time_selection_form(0, 0, 0, $presidency, $appointment);
4207                                 $table_data.= "</td>";
4208
4209                                 // individual drop down list
4210                                 $table_data.= '<td align=center><select name=sched['.$presidency.']['.$appointment.'][individual] STYLE="font-size : 8pt">';
4211                                 $table_data.= '<option value=0></option>';  
4212                                 for ($j=0; $j < count($individual); $j++) {
4213                                         $id = $individual[$j];
4214                                         $name = $indiv_name[$j];
4215                                         $table_data.= '<option value='.$id.'>'.$name.'</option>';
4216                                 }
4217                                 $table_data.='</select></td>';
4218
4219                                 // Family drop down list
4220                                 $table_data.= '<td align=center><select name=sched['.$presidency.']['.$appointment.'][family] STYLE="font-size : 8pt">';
4221                                 $table_data.= '<option value=0></option>';          
4222                                 for ($j=0; $j < count($individual); $j++) {
4223                                         $id = $family_id[$j];
4224                                         $name = $family_name[$j];
4225                                         $table_data.= '<option value='.$id.'>'.$name.' Family</option>';
4226                                 }
4227                                 $table_data.='</select></td>';
4228
4229                                 // Location text box
4230                                 $table_data.= '<td align=center><input type=text size="25" maxlength="120" ';
4231                                 $table_data.= 'name="sched['.$presidency.']['.$appointment.'][location]" value="" STYLE="font-size : 8pt">';
4232
4233                                 $table_data.= '<input type=hidden name="sched['.$presidency.']['.$appointment.'][appointment]" value="'.$appointment.'">';
4234                                 $table_data.= '<input type=hidden name="sched['.$presidency.']['.$appointment.'][presidency]" value="'.$presidency.'">';
4235
4236                                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
4237                                 $this->t->set_var('tr_color',$tr_color);
4238                         }
4239
4240                         $this->t->set_var('table_data',$table_data);
4241                         $this->t->set_var('header_row',$header_row);
4242                         $this->t->set_var('table_width',$table_width);
4243                         $this->t->fp('list','presidency_list',True);
4244                 }
4245
4246                 $this->t->pfp('out','sched_t');
4247                 $this->save_sessiondata();   
4248         }
4249
4250         function email()
4251         {
4252                 $this->t->set_file(array('email_t' => 'email.tpl'));
4253                 $this->t->set_block('email_t','individual_list','list');
4254
4255                 $action = get_var('action',array('GET','POST'));
4256
4257                 $this->t->set_var('actionurl',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.email'));
4258                 $this->t->set_var('title','Email Tool');
4259
4260                 $this->t->set_var('lang_email','Send Email');
4261                 $this->t->set_var('lang_reset','Cancel');
4262
4263                 $this->t->set_var('email_member_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.email&action=member'));
4264                 $this->t->set_var('email_member_link_title','Email Quorum Member');
4265
4266                 $this->t->set_var('email_quorum_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.email&action=quorum'));
4267                 $this->t->set_var('email_quorum_link_title','Email Quorum');
4268
4269                 $this->t->set_var('email_reminder_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.email&action=reminder'));
4270                 $this->t->set_var('email_reminder_link_title','Email Reminders');
4271
4272                 $this->t->set_var('email_edit_link',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.email&action=edit'));
4273                 $this->t->set_var('email_edit_link_title','Edit Email Addresses');
4274
4275                 $table_width=600;
4276                 $this->t->set_var('table_width',$table_width);
4277
4278                 $this->t->pfp('out','email_t');
4279                 $this->save_sessiondata();   
4280         }
4281
4282         function admin()
4283         {
4284                 $this->t->set_file(array('admin_t' => 'admin.tpl'));
4285                 $this->t->set_block('admin_t','upload','uploadhandle');
4286                 $this->t->set_block('admin_t','admin','adminhandle');
4287                 $this->t->set_block('admin_t','cmd','cmdhandle');
4288                 $this->t->set_block('admin_t','presidency','presidencyhandle');
4289
4290                 $this->t->set_var('upload_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.admin&action=upload'));
4291                 $this->t->set_var('presidency_action',$GLOBALS['phpgw']->link('/tc/index.php','menuaction=tc.tc.admin&action=presidency'));
4292
4293                 $action = get_var('action',array('GET','POST'));
4294
4295                 $this->t->pfp('out','admin_t');
4296
4297                 $sql = "SELECT * FROM tc_individual where steward='$this->default_stewardship' and valid=1 ORDER BY individual ASC";
4298                 $this->db->query($sql,__LINE__,__FILE__);
4299                 $i=0;
4300                 while ($this->db->next_record()) {
4301                         $individual[$i] = $this->db->f('individual');
4302                         $indiv_name[$i] = $this->db->f('name');
4303                         $indiv2name[$individual[$i]] = $indiv_name[$i];
4304                         $i++;
4305                 }
4306                 array_multisort($indiv_name, $individual);
4307
4308                 if($action == 'upload') {
4309                         $target_path = $this->upload_target_path . '/' . basename( $_FILES['uploadedfile']['name']);
4310
4311                         if(($_FILES['uploadedfile']['type'] == "application/zip") ||
4312                            ($_FILES['uploadedfile']['type'] == "application/x-zip-compressed") ||
4313                            ($_FILES['uploadedfile']['type'] == "application/x-zip") ||
4314                            ($_FILES['uploadedfile']['type'] == "application/octet-stream")) {
4315
4316                                 if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
4317                                         $uploadstatus = "<b><font color=red> -E- Unable to move the uploaded file to ";
4318                                         $uploadstatus.= "the target path (check the path and permissions) of: $target_path</font></b>";
4319                                         $uploadstatus = "<b>The following file was uploaded successfully: </b><br><br>";
4320                                         $uploadstatus.= "Tmp Filename : " . $_FILES['uploadedfile']['tmp_name'] . "<br>";
4321                                         $uploadstatus.= "Filename     : " . $_FILES['uploadedfile']['name'] . "<br>";
4322                                         $uploadstatus.= "Type         : " . $_FILES['uploadedfile']['type'] . "<br>";
4323                                         $uploadstatus.= "Size         : " . $_FILES['uploadedfile']['size'] . "<br>";
4324                                         $uploadstatus.= "Error        : " . $_FILES['uploadedfile']['error'] . "<br>";   
4325                                         $this->t->set_var('uploadstatus',$uploadstatus);
4326                                         $this->t->pfp('uploadhandle','upload',True);
4327                                         return 0;
4328                                 }
4329
4330                                 $uploadstatus = "<b>The following file was uploaded successfully: </b><br><br>";
4331                                 $uploadstatus.= "Filename : " . $_FILES['uploadedfile']['name'] . "<br>";
4332                                 $uploadstatus.= "Type     : " . $_FILES['uploadedfile']['type'] . "<br>";
4333                                 $uploadstatus.= "Size     : " . $_FILES['uploadedfile']['size'] . "<br>";        
4334                                 $this->t->set_var('uploadstatus',$uploadstatus);
4335                                 $this->t->pfp('uploadhandle','upload');
4336                                 $this->t->set_var('uploadhandle','');
4337                                 print "<table border=1 width=80%><tr><td>\n<pre>";
4338
4339                                 # make a directory for this data to be stored in
4340                                 $date="data_" . date("Y_m_d");
4341                                 $data_dir = $this->upload_target_path . '/' . $date;
4342                                 print "-> Making the data directory: $date<br>\n";
4343                                 exec('mkdir -p ' . $data_dir . ' 2>&1', $result, $return_code);
4344                                 if($return_code != 0) {
4345                                         print implode('\n',$result) . "<br>";
4346                                         print "<b><font color=red>";
4347                                         print "-E- Unable to create the data directory. Aborting import.";
4348                                         print "</font></b>";
4349                                         return 0;
4350                                 }
4351
4352                                 # move the file uploaded into this directory
4353                                 print "-> Moving the uploaded file into the data dir<br>\n";
4354                                 exec('mv ' . $target_path . ' ' . $data_dir . '/' . ' 2>&1', $result, $return_code);
4355                                 if($return_code != 0) {
4356                                         print implode('\n',$result) . "<br>";
4357                                         print "<b><font color=red>";
4358                                         print "-E- Unable to move the uploaded file into the data dir. Aborting import.";
4359                                         print "</font></b>";
4360                                         return 0;
4361                                 }
4362
4363                                 # unzip the data into this directory
4364                                 print "-> Unzipping the data<br>\n";
4365                                 exec($this->unzip_path .' -u '. $data_dir . '/*.zip -d ' . $data_dir . ' 2>&1', $result, $return_code);
4366                                 if($return_code != 0) {
4367                                         print implode('\n',$result) . "<br>";
4368                                         print "<b><font color=red>";
4369                                         print "-E- Unable to unzip the uploaded file into the data dir: $data_dir. Aborting import.";
4370                                         print "</font></b>";
4371                                         return 0;
4372                                 }
4373                                 exec('mv ' . $data_dir . '/*/* '. $data_dir . ' 2>&1', $result, $return_code);
4374
4375                                 # update the data_latest link to point to this new directory
4376                                 print "-> Updating the latest data dir link<br>\n";
4377                                 $data_latest = $this->upload_target_path . '/data_latest';
4378                                 exec('rm ' . $data_latest. '; ln -s ' . $data_dir .' '. $data_latest .' 2>&1', $result, $return_code);
4379                                 if($return_code != 0) {
4380                                         print implode('\n',$result) . "<br>";
4381                                         print "<b><font color=red>";
4382                                         print "-E- Unable to update the data latest link. Aborting import.";
4383                                         print "</font></b>";
4384                                         return 0;
4385                                 }
4386
4387                                 # run the import perl script to encorporate it into the DB
4388                                 ob_start('ob_logstdout', 2);
4389                                 print "-> Importing the data into the database<br>\n";
4390                                 ob_flush(); flush(); sleep(1);
4391                                 $import_log = $this->upload_target_path . '/import.log';
4392                                 $data_log = $this->upload_target_path . '/data.log';
4393                                 $import_cmd = $this->script_path . '/import_ward_data ' . $data_latest . ' 2>&1 | tee ' . $import_log;
4394                                 $parse_cmd = $this->script_path . '/parse_ward_data -v ' . $data_latest . ' > ' . $data_log . '2>&1';
4395                                 #print "import_cmd: $import_cmd<br>";
4396                                 #print "parse_cmd: $parse_cmd<br>";
4397                                 ob_start('ob_logstdout', 2);
4398                                 passthru($import_cmd);
4399                                 passthru($parse_cmd);
4400                                 ob_flush(); flush(); sleep(1);
4401
4402                                 # fix the permissions of the data dir
4403                                 exec('chmod -R o-rwx ' . $data_dir, $result, $return_code);
4404
4405                                 $this->t->pfp('cmdhandle','cmd');
4406                                 print "</pre></td></tr></table>";
4407                         } else if(($_FILES['uploadedfile']['type'] != "application/zip") &&
4408                                   ($_FILES['uploadedfile']['type'] != "application/x-zip-compressed") &&
4409                                   ($_FILES['uploadedfile']['type'] != "application/x-zip") &&
4410                                   ($_FILES['uploadedfile']['type'] != "application/octet-stream")) {
4411                                 $uploadstatus = "<b><font color=red>The file format must be a .zip file, please try again! </font></b>";
4412                                 $uploadstatus.= "<br><br><b>Detected file format: " . $_FILES['uploadedfile']['type'] . "</b>";
4413                                 $this->t->set_var('uploadstatus',$uploadstatus);
4414                                 $this->t->pfp('uploadhandle','upload',True);
4415                         } else {
4416                                 $uploadstatus = "<b><font color=red> There was an error (" . $_FILES['uploadedfile']['error'];
4417                                 $uploadstatus.= ") uploading the file, please try again! </font></b>";
4418                                 $this->t->set_var('uploadstatus',$uploadstatus);
4419                                 $this->t->pfp('uploadhandle','upload',True);
4420                         }
4421                 } else if($action == "presidency") {
4422                         $new_data = get_var('eqpres',array('POST'));
4423                         foreach ($new_data as $entry) {
4424                                 $id = $entry['id'];
4425                                 $email = $entry['email'];
4426                                 $indiv = $entry['indiv'];
4427                                 $name = $entry['name'];
4428                                 $district = $entry['district'];
4429                                 $president = $entry['president'];
4430                                 $counselor = $entry['counselor'];
4431                                 $secretary = $entry['secretary'];
4432                                 // look up the individual name for the ID
4433                                 $name = $indiv2name[$indiv]; 
4434                                 //print "id=$id indiv=$indiv name=$name email=$email district=$district president=$president ";
4435                                 //print "counselor=$counselor secretary=$secretary<br>";
4436
4437                                 if(($indiv > 0) || ($name != "")) {
4438                                         if($id < $this->max_presidency_members) {
4439                                                 //print "Updating Existing Entry<br>";
4440                                                 $this->db2->query("UPDATE tc_presidency set" .
4441                                                                   " individual=" . $indiv . 
4442                                                                   " ,district=" . $district . 
4443                                                                   " ,email='" . $email . "'" .
4444                                                                   " ,president='" . $president . "'" .
4445                                                                   " ,counselor='" . $counselor . "'" .
4446                                                                   " ,secretary='" . $secretary . "'" .
4447                                                                   " WHERE presidency=" . $id,__LINE__,__FILE__);
4448                                         } else {
4449                                                 //print "Adding New Entry<br>";
4450                                                 $this->db2->query("INSERT INTO tc_presidency (presidency,individual,district," .
4451                                                                   "email,president,counselor,secretary,valid) " .
4452                                                                   "VALUES (NULL,'" . $indiv . "','" . $district . "','" .
4453                                                                   $email . "','" . $president  . "','" .
4454                                                                   $counselor . "','" . $secretary . "','1'" .
4455                                                                   ")",__LINE__,__FILE__);
4456                                         }
4457                                 } else {
4458                                         //print "Ignoring Blank Entry<br>";
4459                                 }
4460                         }
4461
4462                         // Now update the tc_district table appropriately
4463
4464                         // Delete all the previous district entries from the table
4465                         $this->db->query("DELETE from tc_district where valid=1",__LINE__,__FILE__);
4466                         $this->db->query("DELETE from tc_district where valid=0",__LINE__,__FILE__);
4467
4468                         // Always add a "District 0" assigned to the High Priests Group
4469                         $district = 0;
4470                         $name = "High Priests";
4471                         $indiv = 0;
4472                         $valid = 0;
4473                         $this->db2->query("INSERT INTO tc_district (district,supervisor,valid) " .
4474                                           "VALUES ('" . $district . "','" . 
4475                                           $indiv . "','" . $valid . "'" .
4476                                           ")",__LINE__,__FILE__);
4477
4478                         // Requery the tc_presidency table
4479                         $sql = "SELECT * FROM tc_presidency AS tp JOIN tc_individual AS ti WHERE tp.individual=ti.individual AND tp.valid=1";
4480                         $this->db->query($sql,__LINE__,__FILE__);
4481                         while ($this->db->next_record()) {
4482                                 // Extract the data for each presidency record
4483                                 $id = $this->db->f('presidency');
4484                                 $indiv = $this->db->f('individual');
4485                                 $name = $this->db->f('name');
4486                                 $district = $this->db->f('district');
4487                                 $valid = 1;
4488
4489                                 // If we have a valid district, add it to the district table
4490                                 if($district > 0) {
4491                                         $this->db2->query("INSERT INTO tc_district (district,supervisor,valid) " .
4492                                                           "VALUES ('" . $district . "','" . 
4493                                                           $indiv . "','" . $valid . "'" .
4494                                                           ")",__LINE__,__FILE__);
4495                                 }
4496                         }
4497
4498                         $this->t->set_var('adminhandle','');
4499                         $this->t->pfp('adminhandle','admin'); 
4500                 }
4501                 else
4502                 {
4503                         $this->t->set_var('adminhandle','');
4504                         $this->t->pfp('adminhandle','admin'); 
4505                 }
4506
4507                 // Now save off the data needed for a Presidency Table Update
4508
4509                 $sql = "SELECT tp.*, ti.name FROM tc_presidency AS tp JOIN tc_individual AS ti WHERE tp.individual=ti.individual AND tp.valid=1";
4510                 $this->db->query($sql,__LINE__,__FILE__);
4511                 $table_data = "";
4512                 $header_row = "<th>Individual</th><th>Email</th><th>District</th><th>President</th><th>Counselor</th><th>Secretary</th>";
4513                 while ($this->db->next_record()) {
4514                         // Extract the data for each presidency record
4515                         $id = $this->db->f('presidency');
4516                         $indiv = $this->db->f('individual');
4517                         $district = $this->db->f('district');
4518                         $name = $this->db->f('name');
4519                         $email = $this->db->f('email');
4520                         $president = $this->db->f('president');
4521                         $counselor = $this->db->f('counselor');
4522                         $secretary = $this->db->f('secretary');
4523
4524                         // Create the forms needed in the table
4525                         $table_data .= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
4526
4527                         // Presidency ID
4528                         $table_data .= '<input type=hidden name="eqpres['.$id.'][id]" value="'.$id.'">';
4529
4530                         // individual
4531                         if($eqpresidency == 0) {
4532                                 $table_data.= '<td align=center><select name="eqpres['.$id.'][indiv]">';
4533                                 $table_data.= '<option value=0></option>';  
4534                                 for ($j=0; $j < count($individual); $j++) {
4535                                         $tmp_id = $individual[$j];
4536                                         $name = $indiv_name[$j];
4537                                         if($individual[$j] == $indiv) { 
4538                                                 $indivname = $name; 
4539                                                 $selected = 'selected="selected"'; 
4540                                         } else { 
4541                                                 $selected = ''; 
4542                                         }
4543                                         $table_data.= '<option value='.$tmp_id.' '.$selected.'>'.$name.'</option>';
4544                                 }
4545                                 $table_data.='</select></td>';
4546                                 $table_data.='<input type=hidden name="eqpres['.$id.'][name]" value="'.$indivname.'">';
4547                         } else {
4548                                 $table_data.= '<td align=left><input type=text size="20" name="eqpresname" value="Presidency"></td>';
4549                                 $table_data.= '<input type=hidden name="eqpres['.$id.'][name]" value="Presidency">';
4550                         }
4551
4552                         // Email Address
4553                         $table_data .= '<td><input type="text" size="50" name="eqpres['.$id.'][email]" value="'.$email.'"></td>';
4554
4555                         // District
4556                         $table_data.= '<td align=center><select name="eqpres['.$id.'][district]">';
4557                         $table_data.= '<option value=0></option>';
4558                         for ($j=0; $j <= $this->max_num_districts; $j++) {
4559                                 if($district == $j) { 
4560                                         $selected = 'selected="selected"'; 
4561                                 } else { 
4562                                         $selected = ''; 
4563                                 }
4564                                 $table_data.= '<option value='.$j.' '.$selected.'>'.$j.'</option>';
4565                         }
4566                         $table_data.='</select></td>';
4567
4568                         // President
4569                         $table_data.= '<td align=center><select name="eqpres['.$id.'][president]">';
4570                         if($president == 1) { $table_data .= '<option value=0>0</option><option value=1 selected="selected">1</option>'; }
4571                         else { $table_data .= '<option value=0 selected="selected">0</option><option value=1>1</option>'; }
4572                         $table_data.='</select></td>';
4573
4574                         // Counselor
4575                         $table_data.= '<td align=center><select name="eqpres['.$id.'][counselor]">';
4576                         if($counselor == 1) { $table_data .= '<option value=0>0</option><option value=1 selected="selected">1</option>'; }
4577                         else { $table_data .= '<option value=0 selected="selected">0</option><option value=1>1</option>'; }
4578                         $table_data.='</select></td>';
4579
4580                         // Secretary
4581                         $table_data.= '<td align=center><select name="eqpres['.$id.'][secretary]">';
4582                         if($secretary == 1) { $table_data .= '<option value=0>0</option><option value=1 selected="selected">1</option>'; }
4583                         else { $table_data .= '<option value=0 selected="selected">0</option><option value=1>1</option>'; }
4584                         $table_data.='</select></td>';
4585
4586                         // End of ROW
4587                         $table_data .= "</tr>\n";
4588                         $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
4589                         $this->t->set_var('tr_color',$tr_color);
4590                 }
4591
4592                 // Now create 1 blank row to always have a line available to add a new individual with
4593                 $id = $this->max_presidency_members;
4594                 $table_data .= "<tr bgcolor=". $this->t->get_var('tr_color') .">";
4595                 // Presidency ID
4596                 $table_data .= '<input type=hidden name="eqpres['.$id.'][id]" value="'.$id.'">';
4597                 // individual
4598                 $table_data.= '<td align=center><select name="eqpres['.$id.'][indiv]">';
4599                 $table_data.= '<option value=0></option>';  
4600                 for ($j=0; $j < count($individual); $j++) {
4601                         $tmp_id = $individual[$j];
4602                         $name = $indiv_name[$j];
4603                         $table_data.= '<option value='.$tmp_id.'>'.$name.'</option>';
4604                 }
4605                 $table_data.='</select></td>';
4606                 $table_data.='<input type=hidden name="eqpres['.$id.'][name]" value="">';
4607                 // Email Address
4608                 $table_data.='<td><input type="text" size="50" name="eqpres['.$id.'][email]" value=""></td>';
4609                 // District
4610                 $table_data.= '<td align=center><select name="eqpres['.$id.'][district]">';
4611                 $table_data.= '<option value=0></option>';
4612                 for ($j=0; $j <= $this->max_num_districts; $j++) {
4613                         if($j == 0) { 
4614                                 $selected = 'selected="selected"'; 
4615                         } else { 
4616                                 $selected = ''; 
4617                         }
4618                         $table_data.= '<option value='.$j.' '.$selected.'>'.$j.'</option>';
4619                 }
4620                 $table_data.='</select></td>';
4621                 // President
4622                 $table_data.= '<td align=center><select name="eqpres['.$id.'][president]">';
4623                 $table_data.= '<option value=0>0</option><option value=1>1</option>';
4624                 $table_data.='</select></td>';
4625                 // Counselor
4626                 $table_data.= '<td align=center><select name="eqpres['.$id.'][counselor]">';
4627                 $table_data.= '<option value=0>0</option><option value=1>1</option>';
4628                 $table_data.='</select></td>';
4629                 // Secretary
4630                 $table_data.= '<td align=center><select name="eqpres['.$id.'][secretary]">';
4631                 $table_data.= '<option value=0>0</option><option value=1>1</option>';
4632                 $table_data.='</select></td>';
4633                 // End of ROW
4634                 $table_data .= "</tr>\n";
4635                 $tr_color = $this->nextmatchs->alternate_row_color($tr_color);
4636                 $this->t->set_var('tr_color',$tr_color);
4637
4638                 $this->t->set_var('header_row',$header_row);
4639                 $this->t->set_var('table_data',$table_data);
4640                 $this->t->pfp('presidencyhandle','presidency',True);
4641
4642                 $this->save_sessiondata();   
4643         }
4644
4645         function email_appt($appointment)
4646         {
4647                 //print "Emailing notification of appointment: $appointment <br>";
4648
4649                 $sql = "SELECT * FROM tc_appointment where appointment='$appointment'";
4650                 $this->db->query($sql,__LINE__,__FILE__);
4651
4652                 while ($this->db->next_record()) {
4653                         $appointment = $this->db->f('appointment');
4654                         $presidency = $this->db->f('presidency');
4655                         $location = $this->db->f('location');
4656                         $interviewer = "";
4657                         $email = "";
4658                         $indiv = $this->db->f('individual');
4659                         $indiv_name = "";
4660                         $family = $this->db->f('family');
4661                         $family_name = "";
4662                         $appt_name = "";
4663                         $phone = "";
4664                         $uid = $this->db->f('uid');
4665
4666                         // Extract the year, month, day, hours, minutes, seconds from the appointment time
4667                         $appt_date = $this->db->f('date');
4668                         $date_array = explode("-",$appt_date);
4669                         $year = $date_array[0]; $month = $date_array[1]; $day = $date_array[2];
4670                         $appt_time = $this->db->f('time');
4671                         $time_array = explode(":",$appt_time);
4672                         $hour = $time_array[0]; $minute = $time_array[1]; $seconds = $time_array[2];
4673
4674                         // Format the appointment time into an iCal UTC equivalent
4675                         $dtstamp = gmdate("Ymd"."\T"."His"."\Z");
4676                         $dtstart = gmdate("Ymd"."\T"."His"."\Z", mktime($hour,$minute,$seconds,$month,$day,$year));
4677                         $dtstartstr = date("l, F d, o g:i A", mktime($hour,$minute,$seconds,$month,$day,$year));
4678
4679                         $sql = "SELECT tp.email AS email1, ti.email AS email2, ti.name AS name FROM tc_presidency AS tp JOIN tc_individual AS ti WHERE tp.individual=ti.individual AND tp.presidency='$presidency'";
4680                         $this->db2->query($sql,__LINE__,__FILE__);
4681                         if($this->db2->next_record()) {
4682                                 if ($this->db2->f('email1') != "") {
4683                                         $email = $this->db2->f('email1');
4684                                 } else { 
4685                                         $email = $this->db2->f('email2');
4686                                 }
4687                                 $interviewer = $this->db2->f('name');
4688                         }
4689
4690                         // Set the email address of the interviewer
4691                         $from = $email;
4692
4693                         if($indiv > 0) {
4694                                 $sql = "SELECT * FROM tc_individual where individual='$indiv'";
4695                                 $this->db2->query($sql,__LINE__,__FILE__);
4696                                 if($this->db2->next_record()) {
4697                                         $indiv_name = $this->db2->f('name');
4698                                         $phone = $this->db2->f('phone');
4699                                         $appt_name = $indiv_name . " Interview";
4700                                         $duration = $this->default_ppi_appt_duration * 60;
4701                                 }
4702                         }
4703
4704                         if($family > 0) {
4705                                 $sql = "SELECT * FROM tc_family WHERE family='$family'";
4706                                 $this->db2->query($sql,__LINE__,__FILE__);
4707                                 if($this->db2->next_record()) {
4708                                         $individual = $this->db2->f('individual');
4709                                         $sql = "SELECT * FROM tc_individual where individual='$individual'";
4710                                         $this->db3->query($sql,__LINE__,__FILE__);
4711                                         if($this->db3->next_record()) {
4712                                                 $phone = $this->db3->f('phone');
4713                                                 $family_name = $this->db3->f('name');
4714                                                 $phone = $this->db3->f('phone');
4715                                         }
4716                                         $appt_name = $family_name . " Family Visit";
4717                                         $duration = $this->default_visit_appt_duration * 60;
4718                                 }
4719                         }
4720
4721                         $dtend = gmdate("Ymd"."\T"."His"."\Z", mktime($hour,$minute,$seconds+$duration,$month,$day,$year));
4722                         $dtendstr = date("g:i A", mktime($hour,$minute,$seconds+$duration,$month,$day,$year));
4723                         $date = $dtstartstr . "-" . $dtendstr;
4724                         $description = "$appt_name : $phone";
4725
4726                         if(($uid == 0) && ($appt_name != "")) {
4727                                 // Create a new calendar item for this appointment, since this must be the first time we
4728                                 // are sending it out.
4729                                 print "Sent new appointment to " . $interviewer . " at " . $email . " for " . $appt_name . "<br>";
4730                                 $uid = rand() . rand(); // Generate a random identifier for this appointment
4731                                 $subject = "Created: $appt_name";
4732
4733                                 $this->db->query("UPDATE tc_appointment set" .
4734                                                  " uid=" . $uid . 
4735                                                  " WHERE appointment=" . $appointment,__LINE__,__FILE__);
4736
4737                                 $action = "PUBLISH";
4738                                 $this->send_ical_appt($action, $email, $from, $subject, $dtstamp, $dtstart,
4739                                                       $dtend, $date, $location, $appt_name, $description, $uid);
4740                         } else if(($uid != 0) && ($appt_name == "")) {
4741                                 // Remove the calendar item for this appointment since it has already been sent
4742                                 // and there is no name we have changed it to.
4743                                 print "Sent deleted appointment to " . $interviewer . " at " . $email . " for " . $appt_date . " " . $appt_time . "<br>";
4744                                 $subject = "Canceled: $appt_date $appt_time";
4745
4746                                 $this->db->query("UPDATE tc_appointment set" .
4747                                                  " uid=0" . 
4748                                                  " WHERE appointment=" . $appointment,__LINE__,__FILE__);
4749
4750                                 $action = "CANCEL";
4751                                 $this->send_ical_appt($action, $email, $from, $subject, $dtstamp, $dtstart,
4752                                                       $dtend, $date, $location, $subject, $subject, $uid);
4753                         } else if($uid != 0) {
4754                                 // Update the existing appointment since we have changed it
4755                                 print "Sent updated appointment to " . $interviewer . " at " . $email . " for " . $appt_name . "<br>";
4756
4757                                 $subject = "Canceled: $appt_date $appt_time";
4758                                 $action = "CANCEL";
4759                                 $this->send_ical_appt($action, $email, $from, $subject, $dtstamp, $dtstart,
4760                                 $dtend, $date, $location, $subject, $subject, $uid);
4761
4762                                 $uid = rand() . rand(); // Generate a random identifier for this appointment
4763                                 $this->db->query("UPDATE tc_appointment set" .
4764                                                  " uid=" . $uid .
4765                                                  " WHERE appointment=" . $appointment,__LINE__,__FILE__);
4766
4767                                 $subject = "Updated: $appt_name";
4768                                 $action = "PUBLISH";
4769                                 $this->send_ical_appt($action, $email, $from, $subject, $dtstamp, $dtstart,
4770                                                       $dtend, $date, $location, $appt_name, $description, $uid);
4771                         }
4772                 }
4773                 return true;
4774         }
4775
4776         function send_ical_appt($action, $to, $from, $subject, $dtstamp, $dtstart, $dtend, $date, $location, $summary, $description, $uid)
4777         {
4778                 // Initialize our local variables
4779                 $boundary = "=MIME_APPOINTMENT_BOUNDARY";
4780                 $message = "";
4781                 $headers = "";
4782
4783                 // Form the headers for the email message
4784                 $headers.="X-Mailer: PHP/" . phpversion() . "\n";
4785                 $headers.="Mime-Version: 1.0\n";
4786                 $headers.="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
4787                 $headers.="Content-Disposition: inline\n";
4788                 $headers.="Reply-To: $from\n";
4789                 $headers.="From: $from\n";
4790
4791                 // Print the plaintext version of the appointment
4792                 $message.="--$boundary\n";
4793                 $message.="Content-Type: text/plain; charset=us-ascii\n";
4794                 $message.="Content-Disposition: inline\n";
4795                 $message.="\n";
4796                 $message.="What: $description\n";
4797                 $message.="When: $date\n";
4798                 $message.="Where: $location\n";
4799                 $message.="\n";
4800
4801                 // Print the .ics attachment version of the appointment
4802                 $message.="--$boundary\n";
4803                 $message.="Content-Type: text/calendar; charset=us-ascii\n";
4804                 $message.="Content-Disposition: attachment; filename=\"appointment.ics\"\n";
4805                 $message.="\n";
4806                 $message.="BEGIN:VCALENDAR" . "\n";
4807                 $message.="VERSION:2.0" . "\n";
4808                 $message.="PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN" . "\n";
4809                 $message.="METHOD:$action" . "\n";
4810                 $message.="BEGIN:VEVENT" . "\n";
4811                 $message.="ORGANIZER:MAILTO:$from". "\n";
4812                 $message.="DTSTAMP:$dtstamp" . "\n";
4813                 $message.="DTSTART:$dtstart" . "\n";
4814                 $message.="DTEND:$dtend" . "\n";
4815                 $message.="SUMMARY:$summary" . "\n";
4816                 $message.="DESCRIPTION:$description" . "\n";
4817                 $message.="LOCATION:$location" . "\n";
4818                 $message.="UID:$uid" ."\n";
4819                 $message.="TRANSP:OPAQUE" . "\n";
4820                 $message.="SEQUENCE:0" . "\n";
4821                 $message.="CLASS:PUBLIC" . "\n";
4822                 $message.="END:VEVENT" . "\n";
4823                 $message.="END:VCALENDAR" . "\n";
4824
4825                 // Complete the message
4826                 $message.="--$boundary\n";
4827
4828                 // Send the message
4829                 mail($to, $subject, $message, $headers);
4830         }
4831
4832         function get_time_selection_form($hour, $minute, $pm, $presidency, $appointment)
4833         {
4834                 $form_data = "";
4835                 $blank = 0;
4836
4837                 if($hour == 0) { $blank = 1; }
4838
4839                 if($this->time_drop_down_lists == 1) {
4840                         // Create drop down lists to get the time
4841                         $form_data.= '<select name=sched['.$presidency.']['.$appointment.'][hour]>';
4842                         if($blank == 1) { $form_data.= '<option value=""></option>'; }
4843                         foreach(range(1,12) as $num) {
4844                                 if($hour == $num) { 
4845                                         $selected = 'selected="selected"'; 
4846                                 } else { 
4847                                         $selected = ''; 
4848                                 }
4849                                 $form_data.= '<option value='.$num.' '.$selected.'>'.$num.'</option>';
4850                         }
4851                         $form_data.= '</select>';
4852                         $form_data.= '&nbsp;:&nbsp;';
4853                         $form_data.= '<select name=sched['.$presidency.']['.$appointment.'][minute]>';
4854                         if($blank == 1) { $form_data.= '<option value=""></option>'; }
4855                         $num = 0;
4856                         while($num < 60) {
4857                                 if($num < 10) { $num = "0" . "$num"; }
4858                                 if($minute == $num) { 
4859                                         $selected = 'selected="selected"'; 
4860                                 } else { 
4861                                         $selected = ''; 
4862                                 }
4863                                 if($blank == 1) { $selected = ""; }
4864                                 $form_data.= '<option value='.$num.' '.$selected.'>'.$num.'</option>';
4865                                 $num = $num + $this->time_drop_down_list_inc;
4866                         }
4867                         $form_data.= '</select>';
4868                 } else {
4869                         // Use free form text fields to get the time
4870                         if($blank == 1) { 
4871                                 $hour = ""; 
4872                                 $minute = ""; 
4873                                 $ampm = ""; 
4874                         }
4875                         $form_data.= '<input type=text size=2 name=sched['.$presidency.']['.$appointment.'][hour] value='.$hour.'>';
4876                         $form_data.= ':';
4877                         $form_data.= '<input type=text size=2 name=sched['.$presidency.']['.$appointment.'][minute] value='.$minute.'>';
4878                         $form_data.= '&nbsp;';
4879                 }
4880                 // Always use a drop-down select form for am/pm
4881                 $form_data.= '<select name=sched['.$presidency.']['.$appointment.'][pm]>';
4882                 if($blank == 0) {
4883                         if($pm == 0) { 
4884                                 $form_data.= '<option value=0 selected>am</option>'; 
4885                                 $form_data.= '<option value=1>pm</option>'; 
4886                         }
4887                         if($pm == 1) { 
4888                                 $form_data.= '<option value=0>am</option>'; 
4889                                 $form_data.= '<option value=1 selected>pm</option>'; 
4890                         }
4891                 } else {
4892                         $form_data.= '<option value=""></option>';
4893                         $form_data.= '<option value=0>am</option>';
4894                         $form_data.= '<option value=1>pm</option>';
4895                 }
4896                 $form_data.= '</select>';
4897
4898                 return $form_data;
4899         }
4900 }
4901
4902 ?>