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