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