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