// compress result
$sep = $tick_str = "";
for ($i = 0; $i < count($tick_array3); $i++) {
    $tick_str .= $sep . $tick_array3[$i];
    $sep = ",";
}
//	dump($tick_str);
$query = "SELECT *, \n\t\tUNIX_TIMESTAMP(problemstart) AS `problemstart`,\n\t\tUNIX_TIMESTAMP(problemend) AS `problemend`,\n\t\t`u`.`user` AS `theuser`,\n\t\tNULL AS `unit_name`,\n\t\t`t`.`scope` AS `tick_scope`,\n\t\t`t`.`id` AS `tick_id`,\n\t\t`t`.`description` AS `tick_descr`,\n\t\t`t`.`status` AS `tick_status`,\n\t\t`t`.`street` AS `tick_street`,\n\t\t`t`.`city` AS `tick_city`,\n\t\t`t`.`state` AS `tick_state`,\t\t\t\n\t\t`f`.`name` AS `facy_name` \n\t\tFROM `{$GLOBALS['mysql_prefix']}ticket`\t\t\t `t`\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}user`\t\t `u` ON (`t`.`_by` = `u`.`id`)\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}facilities` `f` ON (`t`.`facility` = `f`.`id`)\n\t\tWHERE `t`.`id` NOT IN ({$tick_str})\n\t\tAND `t`.`status` <> '{$GLOBALS['STATUS_RESERVED']}'\n\t\tORDER BY `problemstart` ASC";
$result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
print "<TR><TD COLSPAN=99 ALIGN='center'><B>Not dispatched</B></TD></TR>";
$units_str = "";
while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
    // final while ()
    $deltas[$row['severity']] += $row['problemend'] - $row['problemstart'];
    // stats
    $deltas[3] += $row['problemend'] - $row['problemstart'];
    $counts[$row['severity']]++;
    $counts[3]++;
    do_print($row);
}
print "</TABLE>";
print "<BR /><BR /><SPAN STYLE='margin-left:100px'>Mean incident close times by severity:&nbsp;&nbsp;&nbsp;";
for ($i = 0; $i < 3; $i++) {
    // each severity level
    $mean = round($deltas[$i] / $counts[$i]);
    print "<B>" . ucfirst(get_severity($i)) . "</B> ({$counts[$i]}): " . my_date_diff(0, $mean) . ",&nbsp;&nbsp;&nbsp;&nbsp;";
}
$mean = round($deltas[3] / $counts[3]);
// overall
print "<B>Overall</B>  ({$counts[3]}): " . my_date_diff(0, $mean);
print "</SPAN><BR /><BR /><BR />";
function do_im_report($date_in, $func_in)
{
    // incident mgmt report $frm_date, $mode as params - 9/27/10
    global $types, $tick_array, $deltas, $counts, $severities, $units_str, $evenodd, $logs, $types;
    global $types, $incident, $disposition;
    // 12/7/10
    global $w_tiny, $w_small, $w_medium, $w_large;
    // 4/14/11
    $tick_array = array(0);
    $deltas = array(0, 0, 0, 0);
    // normal, medium, high, total
    $counts = array(0, 0, 0, 0);
    //
    $severities = array("", "M", "H");
    // severity symbols
    $from_to = date_range($date_in, $func_in);
    // get date range as array
    $where = " WHERE `problemstart` >= '{$from_to[0]}' AND `problemstart` < '{$from_to[1]}'";
    function do_print($row_in)
    {
        global $today, $today_ref, $line_ctr, $units_str, $severities, $evenodd;
        global $w_tiny, $w_small, $w_medium, $w_large;
        if (empty($today)) {
            $today_ref = date("z", $row_in['problemstart']);
            $today = substr(format_date($row_in['problemstart']), 0, 5);
        } else {
            if (!($today_ref == date("z", $row_in['problemstart']))) {
                // date change?
                $today_ref = date("z", $row_in['problemstart']);
                $today = substr(format_date($row_in['problemstart']), 0, 5);
            }
        }
        $def_city = get_variable('def_city');
        $def_st = get_variable('def_st');
        print "<TR CLASS = '{$evenodd[$line_ctr % 2]}'  onClick = 'open_tick_window(" . $row_in['tick_id'] . ");' >\n";
        print "<TD>{$today}</TD>\n";
        //		Date -
        $problemstart = format_date($row_in['problemstart']);
        $problemstart_sh = short_ts($problemstart);
        print "<TD onMouseover=\"Tip('{$problemstart}');\" onmouseout='UnTip();'>{$problemstart_sh}</TD>\n";
        //		start
        $problemend = format_date($row_in['problemend']);
        $problemend_sh = short_ts($problemend);
        print "<TD onMouseover=\"Tip('{$problemend}');\" onmouseout='UnTip();'>{$problemend_sh}</TD>\n";
        //		end
        $elapsed = intval($row_in['problemstart']) > 0 && intval($row_in['problemend']) > 0 ? my_date_diff($row_in['problemstart'], $row_in['problemend']) : "na";
        print "<TD>{$elapsed}</TD>\n";
        //		Ending time
        print "<TD ALIGN='center'>{$severities[$row_in['severity']]}</TD>\n";
        $scope = $row_in['tick_scope'];
        $scope_sh = shorten($row_in['tick_scope'], $w_medium);
        print "<TD onMouseover=\"Tip('{$scope}');\" onmouseout='UnTip();'>{$scope_sh}</TD>\n";
        //		Call type
        $comment = $row_in['comments'];
        $short_comment = shorten($row_in['comments'], $w_large);
        print "<TD onMouseover=\"Tip('{$comment}');\" onMouseout='UnTip();'>{$short_comment}</TD>\n";
        //		Comments/Disposition
        $facility = $row_in['facy_name'];
        $facility_sh = shorten($row_in['facy_name'], $w_small);
        print "<TD onMouseover=\"Tip('{$facility}');\" onmouseout='UnTip();'>{$facility_sh}</TD>\n";
        //		Facility
        $city = $row_in['tick_city'] == $def_city ? "" : ", {$row_in['tick_city']}";
        $st = $row_in['tick_state'] == $def_st ? "" : ", {$row_in['tick_state']}";
        $addr = "{$row_in['tick_street']}{$city}{$st}";
        $addr_sh = shorten($row_in['tick_street'] . $city . $st, $w_medium);
        print "<TD onMouseover=\"Tip('{$addr}');\" onMouseout='UnTip();'>{$addr_sh}</TD>\n";
        //		Street addr
        print "<TD>{$units_str}</TD>\n";
        //		Units responding
        print "</TR>\n\n";
        $line_ctr++;
    }
    // end function do print()
    function do_stats($in_row)
    {
        //
        global $deltas, $counts;
        if (intval($in_row['problemstart']) > 0 && intval($in_row['problemend']) > 0) {
            $deltas[$in_row['severity']] += $in_row['problemend'] - $in_row['problemstart'];
            $deltas[3] += $in_row['problemend'] - $in_row['problemstart'];
        }
        $counts[$in_row['severity']]++;
        $counts[3]++;
    }
    // end function do stats()
    // 12/7/10
    function do_print_log($ary_in)
    {
        //     ["code"]=> string(1) "3" ["info"]=>  string(14) "test test test"  ["when"]=>   string(10) "1302117158"
        global $today, $today_ref, $line_ctr, $evenodd, $types;
        global $w_tiny, $w_small, $w_medium, $w_large;
        print "<TR CLASS = '{$evenodd[$line_ctr % 2]}'>\n";
        print "<TD>{$today}</TD>\n";
        //		Date -
        $when = format_date($ary_in['when']);
        $when_sh = short_ts($when);
        print "<TD onMouseover=\"Tip('{$when}');\" onmouseout='UnTip();'>{$when_sh}</TD>\n";
        //		start
        print "<TD  COLSPAN=3></TD>\n";
        //		end	Ending time
        print "<TD><I>Log entry:</I></TD>\n";
        //		Call type
        $info = $ary_in['info'];
        $sh_info = shorten($ary_in['info'], $w_large);
        print "<TD onMouseover=\"Tip('{$info}');\" onMouseout='UnTip();'>{$sh_info}</TD>\n";
        //		Comments/Disposition
        print "<TD>{$ary_in['user']}</TD>\n";
        //		Facility
        print "<TD COLSPAN=2></TD>\n";
        //		Street addr, Units responding
        print "</TR>\n\n";
        $line_ctr++;
    }
    // end function do print_log()
    // populate global logs array
    $where_l = str_replace("problemstart", "when", $where);
    // log version - 7/22/11
    $query = "SELECT `l`.`code`, `l`.`info` AS `info`, UNIX_TIMESTAMP(`l`.`when`) AS `when`, `u`.`user`, `u`.`info` AS `user_info`\n\t\t\t\tFROM `{$GLOBALS['mysql_prefix']}log` `l`\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}user` u ON (`l`.who = u.id)\n\t\t\t\t{$where_l}\n\t\t\t\tAND (`code` = {$GLOBALS['LOG_COMMENT']})\n\t\t\t\tORDER BY `when` ASC";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        array_push($logs, $row);
    }
    unset($result);
    function check_logs($in_time)
    {
        //  prints qualifying log entries
        global $logs;
        while (!empty($logs) && $logs[0]['when'] <= $in_time) {
            do_print_log($logs[0]);
            array_shift($logs);
            // remove 1st entry
        }
    }
    // end function check_logs()
    $query = "SELECT *, UNIX_TIMESTAMP(problemstart) AS `problemstart`,\n\t\t\t\tUNIX_TIMESTAMP(problemend) AS `problemend`,\n\t\t\t\t`a`.`id` AS `assign_id` ,\n\t\t\t\t`a`.`comments` AS `assign_comments`,\n\t\t\t\t`u`.`user` AS `theuser`, `t`.`scope` AS `tick_scope`,\n\t\t\t\t`t`.`id` AS `tick_id`,\n\t\t\t\t`t`.`description` AS `tick_descr`,\n\t\t\t\t`t`.`status` AS `tick_status`,\n\t\t\t\t`t`.`street` AS `tick_street`,\n\t\t\t\t`t`.`city` AS `tick_city`,\n\t\t\t\t`t`.`state` AS `tick_state`,\t\t\t\n\t\t\t\t`r`.`id` AS `unit_id`,\n\t\t\t\t`r`.`name` AS `unit_name` ,\n\t\t\t\t`r`.`type` AS `unit_type` ,\n\t\t\t\t`f`.`name` AS `facy_name` ,\n\t\t\t\t`a`.`as_of` AS `assign_as_of`\n\t\t\t\tFROM `{$GLOBALS['mysql_prefix']}assigns` `a`\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}ticket`\t `t` ON (`a`.`ticket_id` = `t`.`id`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}user`\t\t `u` ON (`a`.`user_id` = `u`.`id`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}responder`\t `r` ON (`a`.`responder_id` = `r`.`id`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}facilities` `f` ON (`a`.`facility_id` = `f`.`id`)\n\t\t\t\t{$where}\n\t\t\t\tAND `t`.`status` <> '{$GLOBALS['STATUS_RESERVED']}'\t\t\t\t\n\t\t\t\tORDER BY `problemstart` ASC";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    //dump($query);
    print "<TABLE BORDER=0 ALIGN='center' cellspacing = 1 CELLPADDING = 4  ID='IM' STYLE='display:block'>";
    $to_str = $func_in == "dr" ? "" : " to {$from_to[3]} " . substr($from_to[1], 0, 4);
    print "<TR CLASS='even'><TH COLSPAN=99 ALIGN = 'center'>" . "{$incident} Management Report - " . $from_to[2] . $to_str . "</TH></TR>\n";
    print "<TR CLASS='odd'>\n\t\t\t\t\t<TD><B>Date</B></TD>\n\t\t\t\t\t<TD><B>Opened</B></TD>\n\t\t\t\t\t<TD><B>Closed</B></TD>\n\t\t\t\t\t<TD><B>Elapsed</B></TD>\n\t\t\t\t\t<TD><B>Severity</B></TD>\n\t\t\t\t\t<TD><B>Call type</B></TD>\n\t\t\t\t\t<TD><B>Comments/{$disposition}</B></TD>\n\t\t\t\t\t<TD><B>Facility</B></TD>\n\t\t\t\t\t<TD><B>Address</B></TD>\n\t\t\t\t\t<TD><B>" . get_text("Unit") . " responding</B></TD>\n\t\t\t\t\t</TR>";
    if (mysql_num_rows($result) == 0) {
        // empty?
        print "<TR CLASS = 'even'><TH COLSPAN=99>none</TH></TR>\n";
        print "<TR CLASS = 'odd'><TD COLSPAN=99><BR /><BR /></TD></TR>\n";
    } else {
        $units_str = "";
        $i = 0;
        $today = $today_ref = "";
        $buffer = "";
        $sep = ", ";
        while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
            // major while ()
            array_push($tick_array, $row['tick_id']);
            // stack them up
            if (empty($buffer)) {
                // first time
                $buffer = $row;
                $units_str = $row['unit_name'];
            } else {
                // not first time
                if ($row['tick_id'] == $buffer['tick_id']) {
                    $units_str .= $sep . $row['unit_name'];
                    // no change, collect unit names
                    //					$buffer = $row;
                } else {
                    check_logs($buffer['problemstart']);
                    // problemstart integer
                    do_print($buffer);
                    // print from buffer
                    do_stats($buffer);
                    $buffer = $row;
                    $units_str = $row['unit_name'];
                }
            }
            // end if/else
        }
        // end while(
        check_logs(time());
        // everything remaining
        do_print($buffer);
        // print from buffer
        do_stats($buffer);
    }
    // end else{}
    $tick_array2 = array_unique($tick_array);
    // delete dupes
    $tick_array3 = array_values($tick_array2);
    // compress result
    $sep = $tick_str = "";
    for ($i = 0; $i < count($tick_array3); $i++) {
        $tick_str .= $sep . $tick_array3[$i];
        $sep = ",";
    }
    $query = "SELECT *, \n\t\t\t\tUNIX_TIMESTAMP(problemstart) AS `problemstart`,\n\t\t\t\tUNIX_TIMESTAMP(problemend) AS `problemend`,\n\t\t\t\t`u`.`user` AS `theuser`,\n\t\t\t\tNULL AS `unit_name`,\n\t\t\t\t`t`.`scope` AS `tick_scope`,\n\t\t\t\t`t`.`id` AS `tick_id`,\n\t\t\t\t`t`.`description` AS `tick_descr`,\n\t\t\t\t`t`.`status` AS `tick_status`,\n\t\t\t\t`t`.`street` AS `tick_street`,\n\t\t\t\t`t`.`city` AS `tick_city`,\n\t\t\t\t`t`.`state` AS `tick_state`,\t\t\t\n\t\t\t\t`f`.`name` AS `facy_name` \n\t\t\t\tFROM `{$GLOBALS['mysql_prefix']}ticket`\t\t\t `t`\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}user`\t\t `u` ON (`t`.`_by` = `u`.`id`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}facilities` `f` ON (`t`.`facility` = `f`.`id`)\n\t\t\t\t{$where}\n\t\t\t\tAND `t`.`id` NOT IN ({$tick_str})\n\t\t\t\tAND `t`.`status` <> '{$GLOBALS['STATUS_RESERVED']}'\n\t\t\t\tORDER BY `problemstart` ASC";
    //		dump($query);
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    print "<TR><TD COLSPAN=99 ALIGN='center'><B>Not dispatched</B></TD></TR>";
    if (mysql_num_rows($result) == 0) {
        print "<TR CLASS='even'><TD COLSPAN=99 ALIGN='center'><B>none</B></TD></TR>";
    } else {
        $units_str = "";
        while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
            // incidents not dispatched
            do_print($row);
            do_stats($row);
        }
    }
    if ($counts[3] > 0) {
        // any stats?
        print "<TR><TD COLSPAN=99 ALIGN='center'><B><BR />Mean incident close times by severity:&nbsp;&nbsp;&nbsp;";
        for ($i = 0; $i < 3; $i++) {
            // each severity level
            if ($counts[$i] > 0) {
                $mean = round($deltas[$i] / $counts[$i]);
                print "<B>" . ucfirst(get_severity($i)) . "</B> ({$counts[$i]}): " . my_date_diff(0, $mean) . ",&nbsp;&nbsp;&nbsp;&nbsp;";
            }
        }
        $mean = round($deltas[3] / $counts[3]);
        // overall
        print "<B>Overall</B>  ({$counts[3]}): " . my_date_diff(0, $mean);
        print "</B></TD></TR>";
    }
    print "</TABLE>";
    return;
}