function list_facilities($addon = '', $start)
{
    //	global {$_SESSION['fip']}, $fmp, {$_SESSION['editfile']}, {$_SESSION['addfile']}, {$_SESSION['unitsfile']}, {$_SESSION['facilitiesfile']}, {$_SESSION['routesfile']}, {$_SESSION['facroutesfile']};
    global $iw_width, $u_types, $tolerance;
    //	$assigns = array();
    //	$tickets = array();
    $query = "SELECT `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`, `{$GLOBALS['mysql_prefix']}assigns`.`responder_id`, `{$GLOBALS['mysql_prefix']}ticket`.`scope` AS `ticket` FROM `{$GLOBALS['mysql_prefix']}assigns` LEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` ON `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`=`{$GLOBALS['mysql_prefix']}ticket`.`id`";
    $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_as = stripslashes_deep(mysql_fetch_assoc($result_as))) {
        $assigns[$row_as['responder_id']] = $row_as['ticket'];
        $tickets[$row_as['responder_id']] = $row_as['ticket_id'];
    }
    unset($result_as);
    $calls = array();
    $calls_nr = array();
    $calls_time = array();
    $query = "SELECT * , UNIX_TIMESTAMP(packet_date) AS `packet_date` FROM `{$GLOBALS['mysql_prefix']}tracks` ORDER BY `packet_date` ASC";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), __FILE__, __LINE__);
    while ($row = mysql_fetch_assoc($result)) {
        if (isset($calls[$row['source']])) {
            // array_key_exists ( mixed key, array search )
            $calls_nr[$row['source']]++;
        } else {
            array_push($calls, trim($row['source']));
            $calls[trim($row['source'])] = TRUE;
            $calls_nr[$row['source']] = 1;
        }
        $calls_time[$row['source']] = $row['packet_date'];
        // save latest - note query order
    }
    $query = "SELECT `id` FROM `{$GLOBALS['mysql_prefix']}facilities`";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), __FILE__, __LINE__);
    $facilities = mysql_affected_rows() > 0 ? mysql_affected_rows() : "<I>none</I>";
    unset($result);
    ?>

<SCRIPT >

var color=0;
	var colors = new Array ('odd', 'even');

	function hideDiv(div_area, hide_cont, show_cont) {	//	3/15/11
		if (div_area == "buttons_sh") {
			var controlarea = "hide_controls";
			}
		if (div_area == "resp_list_sh") {
			var controlarea = "resp_list";
			}
		if (div_area == "facs_list_sh") {
			var controlarea = "facs_list";
			}
		if (div_area == "incs_list_sh") {
			var controlarea = "incs_list";
			}
		if (div_area == "region_boxes") {
			var controlarea = "region_boxes";
			}			
		var divarea = div_area 
		var hide_cont = hide_cont 
		var show_cont = show_cont 
		if($(divarea)) {
			$(divarea).style.display = 'none';
			$(hide_cont).style.display = 'none';
			$(show_cont).style.display = '';
			} 
		var params = "f_n=" +controlarea+ "&v_n=h&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";
		var url = "persist2.php";
		sendRequest (url, gb_handleResult, params);			
		} 

	function showDiv(div_area, hide_cont, show_cont) {	//	3/15/11
		if (div_area == "buttons_sh") {
			var controlarea = "hide_controls";
			}
		if (div_area == "resp_list_sh") {
			var controlarea = "resp_list";
			}
		if (div_area == "facs_list_sh") {
			var controlarea = "facs_list";
			}
		if (div_area == "incs_list_sh") {
			var controlarea = "incs_list";
			}
		if (div_area == "region_boxes") {
			var controlarea = "region_boxes";
			}				
		var divarea = div_area
		var hide_cont = hide_cont 
		var show_cont = show_cont 
		if($(divarea)) {
			$(divarea).style.display = '';
			$(hide_cont).style.display = '';
			$(show_cont).style.display = 'none';
			}
		var params = "f_n=" +controlarea+ "&v_n=s&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";
		var url = "persist2.php";
		sendRequest (url, gb_handleResult, params);					
		} 	
	
	function hideGroup(color) {
		for (var i = 0; i < gmarkers.length; i++) {
			if (gmarkers[i]) {
				if (gmarkers[i].id == color) {
					gmarkers[i].show();
					}
				else {
					gmarkers[i].hide();
					}
				}		// end if (gmarkers[i])
			} 	// end for ()
		elem = $("allIcons");
		elem.style.visibility = "visible";
		}			// end function

	function showAll() {
		for (var i = 0; i < gmarkers.length; i++) {
			if (gmarkers[i]) {
				gmarkers[i].show();
				}
			} 	// end for ()
		elem = $("allIcons");
		elem.style.visibility = "hidden";

		}			// end function

	function checkArray(form, arrayName)	{	//	5/3/11
		var retval = new Array();
		for(var i=0; i < form.elements.length; i++) {
			var el = form.elements[i];
			if(el.type == "checkbox" && el.name == arrayName && el.checked) {
				retval.push(el.value);
			}
		}
	return retval;
	}		
		
	function checkForm(form)	{	//	6/10/11
		var errmsg="";
		var itemsChecked = checkArray(form, "frm_group[]");
		if(itemsChecked.length > 0) {
			var params = "f_n=viewed_groups&v_n=" +itemsChecked+ "&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
			var url = "persist3.php";	//	3/15/11	
			sendRequest (url, fvg_handleResult, params);				
//			form.submit();
		} else {
			errmsg+= "\tYou cannot Hide all the regions\n";
			if (errmsg!="") {
				alert ("Please correct the following and re-submit:\n\n" + errmsg);
				return false;
			}
		}
	}
	
	function fvg_handleResult(req) {	// 6/10/11	The persist callback function for viewed groups.
		document.region_form.submit();
		}
		
	function form_validate(theForm) {	//	5/3/11
//		alert("Validating");
		checkForm(theForm);
		}				// end function validate(theForm)			

	function sendRequest(url,callback,postData) {								// 2/14/09
		var req = createXMLHTTPObject();
		if (!req) return;
		var method = (postData) ? "POST" : "GET";
		req.open(method,url,true);
		req.setRequestHeader('User-Agent','XMLHTTP/1.0');
		if (postData)
			req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		req.onreadystatechange = function () {
			if (req.readyState != 4) return;
			if (req.status != 200 && req.status != 304) {
				return;
				}
			callback(req);
			}
		if (req.readyState == 4) return;
		req.send(postData);
		}

	var XMLHttpFactories = [
		function () {return new XMLHttpRequest()	},
		function () {return new ActiveXObject("Msxml2.XMLHTTP")	},
		function () {return new ActiveXObject("Msxml3.XMLHTTP")	},
		function () {return new ActiveXObject("Microsoft.XMLHTTP")	}
		];

	function createXMLHTTPObject() {
		var xmlhttp = false;
		for (var i=0;i<XMLHttpFactories.length;i++) {
			try {
				xmlhttp = XMLHttpFactories[i]();
				}
			catch (e) {
				continue;
				}
			break;
			}
		return xmlhttp;
		}

	function createMarker(point, tabs, color, id, fac_id) {						// (point, myinfoTabs,<?php 
    print $row['type'];
    ?>
, i)
		points = true;													// at least one
//		var letter = to_str(id);
		var fac_id = fac_id;	
		
		var icon = new GIcon(listIcon);
		var icon_url = "./our_icons/gen_fac_icon.php?blank=" + escape(icons[color]) + "&text=" + fac_id;

		icon.image = icon_url;		// 

		var marker = new GMarker(point, icon);
		marker.id = color;				// for hide/unhide - unused

		GEvent.addListener(marker, "click", function() {		// here for both side bar and icon click
			if (marker) {
				map.closeInfoWindow();
				which = id;
				gmarkers[which].hide();
				marker.openInfoWindowTabsHtml(infoTabs[id]);

				setTimeout(function() {										// wait for rendering complete
					if ($("detailmap")) {
						var dMapDiv = $("detailmap");
						var detailmap = new GMap2(dMapDiv);
						detailmap.addControl(new GSmallMapControl());
						detailmap.setCenter(point, 17);  						// larger # = closer
						detailmap.addOverlay(marker);
						}
					else {
						}
					},4000);				// end setTimeout(...)

				}		// end if (marker)
			});			// end GEvent.add Listener()

		gmarkers[id] = marker;									// marker to array for side_bar click function
		infoTabs[id] = tabs;									// tabs to array
		if (!(map_is_fixed)) {
			bounds.extend(point);
			}
		return marker;
		}				// end function create Marker()

	function createdummyMarker(point, tabs, color, id, fac_id) {						// 7/28/10
		points = true;													// at least one
//		var letter = to_str(id);
		var fac_id = fac_id;	
		
		var icon = new GIcon(listIcon);
		var icon_url = "./our_icons/question1.png";

		icon.image = icon_url;		// 

		var dummymarker = new GMarker(point, icon);
		dummymarker.id = color;				// for hide/unhide - unused

		GEvent.addListener(dummymarker, "click", function() {		// here for both side bar and icon click
			if (dummymarker) {
				map.closeInfoWindow();
				which = id;
				gmarkers[which].hide();
				dummymarker.openInfoWindowTabsHtml(infoTabs[id]);

				setTimeout(function() {										// wait for rendering complete
					if ($("detailmap")) {
						var dMapDiv = $("detailmap");
						var detailmap = new GMap2(dMapDiv);
						detailmap.addControl(new GSmallMapControl());
						detailmap.setCenter(point, 17);  						// larger # = closer
						detailmap.addOverlay(dummymarker);
						}
					else {
						}
					},4000);				// end setTimeout(...)

				}		// end if (marker)
			});			// end GEvent.add Listener()

		gmarkers[id] = dummymarker;									// marker to array for side_bar click function
		infoTabs[id] = tabs;									// tabs to array
		if (!(map_is_fixed)) {
			bounds.extend(point);
			}
		return dummymarker;
		}				// end function createdummyMarker()		

	function do_sidebar (sidebar, id, the_class, fac_id) {
		var fac_id = fac_id;
		side_bar_html += "<TR CLASS='" + colors[(id)%2] +"'>";
		side_bar_html += "<TD CLASS='" + the_class + "' onClick = myclick(" + id + "); >" + fac_id + sidebar +"</TD></TR>\n";		// 3/15/11
		}

	function do_sidebar_nm (sidebar, line_no, id, fac_id) {	
		var fac_id = fac_id;	
		var letter = to_str(line_no);	
		side_bar_html += "<TR CLASS='" + colors[(line_no)%2] +"'>";
		side_bar_html += "<TD onClick = myclick_nm(" + id + "); >" + fac_id + sidebar +"</TD></TR>\n";		// 1/23/09, 10/29/09 removed period, 11/11/09, 3/15/11
		}

	function myclick_nm(v_id) {				// Responds to sidebar click - view responder data
		document.view_form.id.value=v_id;
		document.view_form.submit();
		}

	function myclick(id) {					// Responds to sidebar click, then triggers listener above -  note [id]
		GEvent.trigger(gmarkers[id], "click");
		location.href = '#top';		// 11/11/090
		}

	function do_lat (lat) {
		document.forms[0].frm_lat.value=lat.toFixed(6);
		}
	function do_lng (lng) {
		document.forms[0].frm_lng.value=lng.toFixed(6);
		}

	function do_ngs() {											// LL to USNG
		var loc = <?php 
    print get_variable('locale');
    ?>
;
		document.forms[0].frm_ngs.disabled=false;
		if(loc == 0) {
			document.forms[0].frm_ngs.value = LLtoUSNG(document.forms[0].frm_lat.value, document.forms[0].frm_lng.value, 5);
			}
		if(loc == 1) {
			document.forms[0].frm_ngs.value = LLtoOSGB(document.forms[0].frm_lat.value, document.forms[0].frm_lng.value);
			}
		if(loc == 2) {
			document.forms[0].frm_ngs.value = LLtoOSGB(document.forms[0].frm_lat.value, document.forms[0].frm_lng.value);
			}			
		document.forms[0].frm_ngs.disabled=true;
		}

	function do_sel_update_fac (in_unit, in_val) {							// 3/15/11
		to_server_fac(in_unit, in_val);
		}

	function to_server_fac(the_unit, the_status) {									// 3/15/11
		var querystr = "frm_responder_id=" + the_unit;
		querystr += "&frm_status_id=" + the_status;
	
		var url = "as_up_fac_status.php?" + querystr;			// 3/15/11
		var payload = syncAjax(url);						// 
		if (payload.substring(0,1)=="-") {	
			alert ("<?php 
    print __LINE__;
    ?>
: msg failed ");
			return false;
			}
		else {
			parent.frames['upper'].show_msg ('Facility status update applied!')
			return true;
			}				// end if/else (payload.substring(... )
		}		// end function to_server()

	var icons=new Array;							// maps type to icon blank

<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_types` ORDER BY `id`";
    // types in use
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $icons = $GLOBALS['fac_icons'];
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // map type to blank icon id
        $blank = $icons[$row['icon']];
        print "\ticons[" . $row['id'] . "] = " . $row['icon'] . ";\n";
        //
    }
    unset($result);
    $dzf = get_variable('def_zoom_fixed');
    print "\tvar map_is_fixed = ";
    print my_is_int($dzf) && $dzf == 2 || my_is_int($dzf) && $dzf == 3 ? "true;\n" : "false;\n";
    ?>
	var map;
	var side_bar_html = "<TABLE border=0 CLASS='sidebar' ID='tbl_facilities'>";
	side_bar_html += "<TR class='even'>	<TD><B>Icon</B></TD><TD><B>Handle</B></TD><TD ALIGN='left'><B>Name</B></TD><TD ALIGN='left'><B><?php 
    print get_text("Type");
    ?>
</B></TD><TD ALIGN='left'><B><?php 
    print get_text("Status");
    ?>
</B></TD><TD ALIGN='left'><B><?php 
    print get_text("As of");
    ?>
</B></TD></TR>";
	var gmarkers = [];
	var infoTabs = [];
	var which;
	var i = <?php 
    print $start;
    ?>
;					// sidebar/icon index
	var points = false;								// none

	map = new GMap2($("map"));						// create the map
<?php 
    $maptype = get_variable('maptype');
    switch ($maptype) {
        case "1":
            break;
        case "2":
            ?>
		map.setMapType(G_SATELLITE_MAP);<?php 
            break;
        case "3":
            ?>
		map.setMapType(G_PHYSICAL_MAP);<?php 
            break;
        case "4":
            ?>
		map.setMapType(G_HYBRID_MAP);<?php 
            break;
        default:
            print "ERROR in " . basename(__FILE__) . " " . __LINE__ . "<BR />";
    }
    ?>

//	map.addControl(new GSmallMapControl());
	map.setUIToDefault();										// 8/13/10

	map.addControl(new GMapTypeControl());
<?php 
    if (get_variable('terrain') == 1) {
        ?>
	map.addMapType(G_PHYSICAL_MAP);
<?php 
    }
    ?>

	map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
	mapBounds=new GLatLngBounds(map.getBounds().getSouthWest(), map.getBounds().getNorthEast());

	var bounds = new GLatLngBounds();						// create  bounding box
	map.enableScrollWheelZoom();

	do_landb();				// 8/1/11 - show scribbles		
	
	var listIcon = new GIcon();
	listIcon.image = "./markers/yellow.png";	// yellow.png - 16 X 28
	listIcon.shadow = "./markers/sm_shadow.png";
	listIcon.iconSize = new GSize(30, 30);
	listIcon.shadowSize = new GSize(16, 28);
	listIcon.iconAnchor = new GPoint(8, 28);
	listIcon.infoWindowAnchor = new GPoint(9, 2);
	listIcon.infoShadowAnchor = new GPoint(18, 25);

	GEvent.addListener(map, "infowindowclose", function() {		// re-center after  move/zoom
		map.addOverlay(gmarkers[which])
		});

//-----------------------BOUNDARIES STUFF--------------------6/10/11

	var thepoint;
	var points = new Array();
	var boundary = new Array();	
	var bound_names = new Array();
	
	GEvent.addListener(map, "click", function(overlay,boundpoint) {
	for (var n = 0; n < boundary.length; n++) {
		if (boundary[n].Contains(boundpoint)) {
			map.openInfoWindowHtml(boundpoint,"This is " + bound_names[n]);
			}
		}
	});	
<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}' ORDER BY `id` ASC;";
    //	6/10/11
    $result = mysql_query($query);
    //	6/10/11
    $a_gp_bounds = array();
    $gp_bounds = array();
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        //	6/10/11
        $al_groups[] = $row['group'];
        $query2 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}region` WHERE `id`= '{$row['group']}';";
        //	6/10/11
        $result2 = mysql_query($query2);
        // 4/18/11
        while ($row2 = stripslashes_deep(mysql_fetch_assoc($result2))) {
            //	//	6/10/11
            if ($row2['boundary'] != 0) {
                $a_gp_bounds[] = $row2['boundary'];
            }
        }
    }
    if (isset($_SESSION['viewed_groups'])) {
        //	6/10/11
        foreach (explode(",", $_SESSION['viewed_groups']) as $val_vg) {
            $query3 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}region` WHERE `id`= '{$val_vg}';";
            $result3 = mysql_query($query3);
            //	6/10/11
            while ($row3 = stripslashes_deep(mysql_fetch_assoc($result3))) {
                if ($row3['boundary'] != 0) {
                    $gp_bounds[] = $row3['boundary'];
                }
            }
        }
    } else {
        $gp_bounds = $a_gp_bounds;
    }
    foreach ($gp_bounds as $value) {
        //	6/10/11
        ?>
		var points = new Array();
<?php 
        if ($value != 0) {
            $query_bn = "SELECT * FROM `{$GLOBALS['mysql_prefix']}mmarkup` WHERE `id`='{$value}' AND `use_with_f`=1";
            //			print $query_bn;
            $result_bn = mysql_query($query_bn) or do_error($query_bn, mysql_error(), basename(__FILE__), __LINE__);
            while ($row_bn = stripslashes_deep(mysql_fetch_assoc($result_bn))) {
                extract($row_bn);
                $bn_name = $row_bn['line_name'];
                $points = explode(";", $line_data);
                for ($xx = 0; $xx < count($points); $xx++) {
                    $coords = explode(",", $points[$xx]);
                    ?>
					thepoint = new GLatLng(parseFloat(<?php 
                    print $coords[0];
                    ?>
), parseFloat(<?php 
                    print $coords[1];
                    ?>
));
					points.push(thepoint);
<?php 
                }
                // end for ($i = 0 ... )
                ?>

<?php 
                switch ($row_bn['line_type']) {
                    case "p":
                        // poly
                        if (intval($filled) == 1) {
                            //	6/10/11
                            ?>
						var polyline = new GPolygon(points, "<?php 
                            print $line_color;
                            ?>
", <?php 
                            print $line_width;
                            ?>
, <?php 
                            print $line_opacity;
                            ?>
, "<?php 
                            print $fill_color;
                            ?>
", <?php 
                            print $fill_opacity;
                            ?>
, {clickable:false});
						boundary.push(polyline);
						bound_names.push("<?php 
                            print $bn_name;
                            ?>
"); 			
						<?php 
                        } else {
                            ?>
						var polyline = new GPolyline(points, "<?php 
                            print $line_color;
                            ?>
", <?php 
                            print $line_width;
                            ?>
, <?php 
                            print $line_opacity;
                            ?>
, , 0, {clickable:false});
						boundary.push(polyline);
						bound_names.push("<?php 
                            print $bn_name;
                            ?>
"); 			
<?php 
                        }
                        ?>
	
					map.addOverlay(polyline);
<?php 
                        break;
                    case "c":
                        $temp = explode(";", $line_data);
                        $radius = $temp[1];
                        $coords = explode(",", $temp[0]);
                        $lat = $coords[0];
                        $lng = $coords[1];
                        $fill_opacity = intval($filled) == 0 ? 0 : $fill_opacity;
                        echo "\n drawCircle({$lat}, {$lng}, {$radius}, add_hash('{$line_color}'), {$line_opacity}, {$line_width}, add_hash('{$fill_color}'), {$fill_opacity}); // 513\n";
                        break;
                }
            }
            //	End while
        }
        //	end if $value !=0
    }
    //	end foreach $gp_bounds
    //-------------------------END OF BOUNDARIES STUFF-------------------------
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    $status_vals = array();
    // build array of $status_vals
    $status_vals[''] = $status_vals['0'] = "TBD";
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_status` ORDER BY `id`";
    $result_st = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_st = stripslashes_deep(mysql_fetch_assoc($result_st))) {
        $temp = $row_st['id'];
        $status_vals[$temp] = $row_st['status_val'];
    }
    unset($result_st);
    $type_vals = array();
    // build array of $status_vals
    $type_vals[''] = $type_vals['0'] = "TBD";
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_types` ORDER BY `id`";
    $result_ty = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_ty = stripslashes_deep(mysql_fetch_assoc($result_ty))) {
        $temp = $row_ty['id'];
        $type_vals[$temp] = $row_ty['name'];
    }
    unset($result_ty);
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}';";
    // 6/10/11
    $result = mysql_query($query);
    // 6/10/11
    $al_groups = array();
    while ($row_gp = stripslashes_deep(mysql_fetch_assoc($result))) {
        // 6/10/11
        $al_groups[] = $row_gp['group'];
    }
    if (isset($_SESSION['viewed_groups'])) {
        //	6/10/11
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    }
    if (!isset($curr_viewed)) {
        $x = 0;
        //	6/10/11
        $where2 = "WHERE (";
        //	6/10/11
        foreach ($al_groups as $grp) {
            //	6/10/11
            $where3 = count($al_groups) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    } else {
        $x = 0;
        //	6/10/11
        $where2 = "WHERE (";
        //	6/10/11
        foreach ($curr_viewed as $grp) {
            //	6/10/11
            $where3 = count($curr_viewed) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    }
    $where2 .= "AND `a`.`type` = 3";
    //	6/10/11
    unset($result);
    //	3/15/11, 6/10/11
    $query = "SELECT *,UNIX_TIMESTAMP(updated) AS updated, \n\t\t`f`.id AS id, \n\t\t`f`.status_id AS status_id,\n\t\t`f`.boundary AS boundary,\t\t\n\t\t`f`.description AS facility_description,\n\t\t`t`.name AS fac_type_name, \n\t\t`f`.name AS name,\n\t\t`f`.type AS type,\n\t\t`f`.street AS street,\n\t\t`f`.city AS city,\n\t\t`f`.state AS state \n\t\tFROM `{$GLOBALS['mysql_prefix']}facilities`  `f`\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON ( `f`.`id` = a.resource_id )\t\t\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}fac_types` `t` ON `f`.type = `t`.id \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}fac_status` `s` ON `f`.status_id = `s`.id \n\t\t{$where2} GROUP BY `f`.id ORDER BY `f`.type ASC";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $num_facilities = mysql_affected_rows();
    $i = 0;
    // counter
    // =============================================================================
    $utc = gmdate("U");
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // ==========  major while() for Facility ==========
        $boundary = $row['boundary'];
        //-----------------------FACILITY BOUNDARIES / CATCHMENT STUFF--------------------6/10/11
        ?>
	var thepoint;
	var points = new Array();
<?php 
        $query_bn = "SELECT * FROM `{$GLOBALS['mysql_prefix']}mmarkup` WHERE `id`='{$boundary}' AND `use_with_f`=1";
        $result_bn = mysql_query($query_bn) or do_error($query_bn, mysql_error(), basename(__FILE__), __LINE__);
        while ($row_bn = stripslashes_deep(mysql_fetch_assoc($result_bn))) {
            $the_type = $row_bn['line_type'];
            switch ($the_type) {
                case "p":
                    extract($row_bn);
                    $bn_name = $row_bn['line_name'];
                    $points = explode(";", $line_data);
                    for ($i = 0; $i < count($points); $i++) {
                        $coords = explode(",", $points[$i]);
                        ?>
					thepoint = new GLatLng(parseFloat(<?php 
                        print $coords[0];
                        ?>
), parseFloat(<?php 
                        print $coords[1];
                        ?>
));
					points.push(thepoint);
<?php 
                    }
                    // end for ($i = 0 ... )
                    if (intval($filled) == 1) {
                        //	6/10/11
                        ?>
					var polyline = new GPolygon(points, "<?php 
                        print $line_color;
                        ?>
", <?php 
                        print $line_width;
                        ?>
, <?php 
                        print $line_opacity;
                        ?>
, "<?php 
                        print $fill_color;
                        ?>
", <?php 
                        print $fill_opacity;
                        ?>
, {clickable:false});
					boundary.push(polyline);
					bound_names.push("<?php 
                        print $bn_name;
                        ?>
"); 			
<?php 
                    } else {
                        ?>
					var polyline = new GPolyline(points, "<?php 
                        print $line_color;
                        ?>
", <?php 
                        print $line_width;
                        ?>
, <?php 
                        print $line_opacity;
                        ?>
, , 0, {clickable:false});
					boundary.push(polyline);
					bound_names.push("<?php 
                        print $bn_name;
                        ?>
"); 			
<?php 
                    }
                    ?>
					map.addOverlay(polyline);
<?php 
                    break;
                case "c":
                    extract($row_bn);
                    $temp = explode(";", $line_data);
                    $radius = $temp[1];
                    $coords = explode(",", $temp[0]);
                    $lat = $coords[0];
                    $lng = $coords[1];
                    $fill_opacity = intval($filled) == 0 ? 0 : $fill_opacity;
                    echo "\n drawCircle({$lat}, {$lng}, {$radius}, add_hash('{$line_color}'), {$line_opacity}, {$line_width}, add_hash('{$fill_color}'), {$fill_opacity}); // 513\n";
                    break;
            }
            // end switch
        }
        //	End while
        //-------------------------END OF FACILITY BOUNDARIES STUFF-------------------------
        $fac_gps = get_allocates(3, $row['id']);
        //	6/10/11
        $grp_names = "Groups Assigned: ";
        //	6/10/11
        $y = 0;
        //	6/10/11
        foreach ($fac_gps as $value) {
            //	6/10/11
            $counter = count($fac_gps) > $y + 1 ? ", " : "";
            $grp_names .= get_groupname($value);
            $grp_names .= $counter;
            $y++;
        }
        $grp_names .= " / ";
        $the_bg_color = $GLOBALS['FACY_TYPES_BG'][$row['icon']];
        // 2/8/10
        $the_text_color = $GLOBALS['FACY_TYPES_TEXT'][$row['icon']];
        // 2/8/10
        $the_on_click = my_is_float($row['lat']) ? " onClick = myclick({$i}); " : " onClick = myclick_nm({$row['unit_id']}); ";
        //	3/15/11
        $got_point = FALSE;
        print "\n\t\tvar i={$i};\n";
        if (is_guest()) {
            $toedit = $tomail = $toroute = "";
        } else {
            $toedit = "&nbsp;&nbsp;&nbsp;&nbsp;<A HREF='{$_SESSION['facilitiesfile']}?func=responder&edit=true&id=" . $row['id'] . "'><U>Edit</U></A>";
            $tomail = "&nbsp;&nbsp;&nbsp;&nbsp;<SPAN onClick = 'do_mail_in_win({$row['id']})'><U><B>Email</B></U></SPAN>";
            $toroute = "&nbsp;<A HREF='{$_SESSION['facroutesfile']}?fac_id=" . $row['id'] . "'><U>Route To Facility</U></A>";
        }
        $temp = $row['status_id'];
        $the_status = array_key_exists($temp, $status_vals) ? $status_vals[$temp] : "??";
        $temp_type = $row['type'];
        $the_type = array_key_exists($temp_type, $type_vals) ? $type_vals[$temp_type] : "??";
        if (!$got_point && my_is_float($row['lat'])) {
            if ($row['lat'] == 0.999999 && $row['lng'] == 0.999999) {
                echo "\t\tvar point = new GLatLng(" . get_variable('def_lat') . ", " . get_variable('def_lng') . ");\n";
            } else {
                echo "\t\tvar point = new GLatLng(" . $row['lat'] . ", " . $row['lng'] . ");\n";
            }
            $got_point = TRUE;
        }
        $update_error = strtotime('now - 6 hours');
        // set the time for silent setting
        $index = $row['icon_str'];
        // name
        $display_name = $name = htmlentities($row['name'], ENT_QUOTES);
        $handle = htmlentities($row['handle'], ENT_QUOTES);
        // 7/7/11
        $sidebar_line = "&nbsp;&nbsp;<TD WIDTH='15%' TITLE = '{$row['handle']}' {$the_on_click}><U><SPAN STYLE='background-color:{$the_bg_color};  opacity: .7; color:{$the_text_color};'>" . addslashes(shorten($handle, 15)) . "</SPAN></U></TD>";
        //	6/10/11
        $sidebar_line .= "<TD WIDTH='40%' TITLE = '" . addslashes($name) . "' {$the_on_click}><U><SPAN STYLE='background-color:{$the_bg_color};  opacity: .7; color:{$the_text_color};'><NOBR>" . addslashes(shorten($name, 24)) . "</NOBR></SPAN></U></TD><TD WIDTH='15%'>{$the_type}</TD>";
        $sidebar_line .= "<TD WIDTH='20%' CLASS='td_data' TITLE = '" . addslashes($the_status) . "'> " . get_status_sel($row['id'], $row['status_id'], 'f') . "</TD>";
        //	3/15/11
        // as of
        $strike = $strike_end = "";
        $the_time = $row['updated'];
        $the_class = "";
        $strike = $strike_end = "";
        $sidebar_line .= "<TD WIDTH='20%' CLASS='{$the_class}'> {$strike} <NOBR>" . format_sb_date($the_time) . "</NOBR> {$strike_end}</TD>";
        // tab 1
        if (my_is_float($row['lat'])) {
            // position data?
            $temptype = $u_types[$row['type']];
            $the_type = $temptype[0];
            $tab_1 = "<TABLE CLASS='infowin' width='{$iw_width}'>";
            $tab_1 .= "<TR CLASS='even'><TD COLSPAN=2 ALIGN='center'><B>" . addslashes(shorten($display_name, 48)) . "</B> - " . $the_type . "</TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD ALIGN='right'>Description:&nbsp;</TD><TD ALIGN='left'>" . addslashes(shorten(str_replace($eols, " ", $row['description']), 32)) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='even'><TD ALIGN='right'>Status:&nbsp;</TD><TD ALIGN='left'>" . $the_status . " </TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD ALIGN='right'>Contact:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row['contact_name']) . " Via: " . addslashes($row['contact_email']) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='even'><TD ALIGN='right'>As of:&nbsp;</TD><TD ALIGN='left'>" . format_date($row['updated']) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'>" . $toedit . $tomail . "&nbsp;&nbsp;<A HREF='{$_SESSION['facilitiesfile']}?func=responder&view=true&id=" . $row['id'] . "'><U>View</U></A></TD></TR>";
            // 08/8/02
            $tab_1 .= "</TABLE>";
            $tab_2 = "<TABLE CLASS='infowin' width='{$iw_width}' ALIGN = 'center' >";
            $tab_2 .= "<TR CLASS='odd'><TD ALIGN='right' STYLE= 'width:50%'>Security contact:&nbsp;</TD><TD ALIGN='left' STYLE= 'width:50%'>" . addslashes($row['security_contact']) . " </TD></TR>";
            $tab_2 .= "<TR CLASS='even'><TD ALIGN='right'>Security email:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row['security_email']) . " </TD></TR>";
            $tab_2 .= "<TR CLASS='odd'><TD ALIGN='right'>Security phone:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row['security_phone']) . " </TD></TR>";
            $tab_2 .= "<TR CLASS='even'><TD ALIGN='right'>" . get_text("Access rules") . ":&nbsp;</TD><TD ALIGN='left'>" . addslashes(str_replace($eols, " ", $row['access_rules'])) . "</TD></TR>";
            $tab_2 .= "<TR CLASS='odd'><TD ALIGN='right'>Security reqs:&nbsp;</TD><TD ALIGN='left'>" . addslashes(str_replace($eols, " ", $row['security_reqs'])) . "</TD></TR>";
            $tab_2 .= "<TR CLASS='even'><TD ALIGN='right'>Opening hours:&nbsp;</TD><TD ALIGN='left'>" . addslashes(str_replace($eols, " ", $row['opening_hours'])) . "</TD></TR>";
            $tab_2 .= "<TR CLASS='odd'><TD ALIGN='right'>Prim pager:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row['pager_p']) . " </TD></TR>";
            $tab_2 .= "<TR CLASS='even'><TD ALIGN='right'>Sec pager:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row['pager_s']) . " </TD></TR>";
            $tab_2 .= "</TABLE>";
            // tab 2
            $tabs_done = FALSE;
            // default
            if (!$tabs_done) {
                //
                ?>
			var myinfoTabs = [
				new GInfoWindowTab("<?php 
                print nl2brr(addslashes(shorten($row['name'], 10)));
                ?>
", "<?php 
                print $tab_1;
                ?>
"),
				new GInfoWindowTab("More ...", "<?php 
                print str_replace($eols, " ", $tab_2);
                ?>
"),
				new GInfoWindowTab("Zoom", "<div id='detailmap' class='detailmap'></div>")
				];

<?php 
            }
            // end if/else
            $name = $row['name'];
            // 10/8/09		 4/28/11
            if ($row['lat'] == 0.999999 && $row['lng'] == 0.999999) {
                // check for facilities added in no mpas mode 7/28/10
                ?>
		var fac_id = "<?php 
                print $index;
                ?>
";	//	10/8/09
		var the_class = ((map_is_fixed) && (!(mapBounds.containsLatLng(point))))? "emph" : "td_label";

		do_sidebar ("<?php 
                print $sidebar_line;
                ?>
", i, the_class, fac_id);
		var dummymarker = createdummyMarker(point, myinfoTabs,<?php 
                print $row['type'];
                ?>
, i, fac_id);	// 771 (point,tabs, color, id)
		map.addOverlay(dummymarker);
<?php 
            } else {
                ?>
		var fac_id = "<?php 
                print $index;
                ?>
";	//	10/8/09
		var the_class = ((map_is_fixed) && (!(mapBounds.containsLatLng(point))))? "emph" : "td_label";

		do_sidebar ("<?php 
                print $sidebar_line;
                ?>
", i, the_class, fac_id);
		var marker = createMarker(point, myinfoTabs,<?php 
                print $row['type'];
                ?>
, i, fac_id);	// 771 (point,tabs, color, id)
		map.addOverlay(marker);
<?php 
            }
            // End of check for facilities added in no maps mode 7/28/10
        } else {
            // end position data available
            $name = $row['name'];
            // 11/11/09
            $temp = explode("/", $name);
            $index = substr($temp[count($temp) - 1], -6, strlen($temp[count($temp) - 1]));
            // 3/19/11
            ?>
			var fac_id = "<?php 
            print $index;
            ?>
";	//	11/11/09
<?php 
            print "\tdo_sidebar_nm (\" {$sidebar_line} \" , i, {$row['id']}, fac_id);\n";
            // sidebar only - no map
        }
        $i++;
        // zero-based
    }
    // end  ==========  while() for Facility ==========
    ?>
	if (!(map_is_fixed)) {
		if (!points) {		// any?
			map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
			}
		else {
			center = bounds.getCenter();
			zoom = map.getBoundsZoomLevel(bounds);
			map.setCenter(center,zoom);
			}
		}

var buttons_html = "";
<?php 
    if (!empty($addon)) {
        print "\n\tbuttons_html +=\"" . $addon . "\"\n";
    }
    ?>
	side_bar_html +="</TABLE>\n";
	$("side_bar").innerHTML += side_bar_html;	// append the assembled side_bar_html contents to the side_bar div
	$("buttons").innerHTML = buttons_html;	// append the assembled side_bar_html contents to the side_bar div
	$("num_facilities").innerHTML = <?php 
    print $num_facilities;
    ?>
;

<?php 
    do_kml();
    ?>


</SCRIPT>
<?php 
}
function list_tickets($sort_by_field = '', $sort_value = '', $my_offset = 0)
{
    // list tickets ===================================================
    global $istest, $iw_width, $units_side_bar_height, $do_blink, $nature, $disposition, $patient, $incident, $incidents, $gt_status;
    // 12/3/10
    $time = microtime(true);
    // Gets microseconds
    @session_start();
    //
    $captions = array(get_text("Current situation"), "{$incidents} closed today", "{$incidents} closed yesterday+", "{$incidents} closed this week", "{$incidents} closed last week", "{$incidents} closed last week+", "{$incidents} closed this month", "{$incidents} closed last month", "{$incidents} closed this year", "{$incidents} closed last year", "Scheduled");
    $by_severity = array(0, 0, 0);
    // counters // 5/2/10
    if (!array_key_exists('func', $_GET)) {
        //	3/15/11
        $func = 0;
    } else {
        extract($_GET);
    }
    if (array_key_exists('func', $_GET) && $_GET['func'] == 10) {
        //	3/15/11
        $func = 10;
    }
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}' ORDER BY `id` ASC;";
    //	6/10/11
    $result = mysql_query($query);
    //	6/10/11
    $al_groups = array();
    $al_names = "";
    $a_gp_bounds = array();
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        //	6/10/11
        $al_groups[] = $row['group'];
        $query2 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}region` WHERE `id`= '{$row['group']}';";
        //	6/10/11
        $result2 = mysql_query($query2);
        // 4/18/11
        while ($row2 = stripslashes_deep(mysql_fetch_assoc($result2))) {
            //	//	6/10/11
            $al_names .= $row2['group_name'] . ", ";
        }
    }
    if (is_super()) {
        //	6/10/11
        $al_names .= "Superadmin Level";
    }
    if (isset($_SESSION['list_type'])) {
        $func = $_SESSION['list_type'];
    }
    // 12/02/10	 persistance for the tickets list
    $cwi = get_variable('closed_interval');
    // closed window interval in hours
    $get_sortby = empty($_GET) || !empty($_GET) && empty($_GET['sortby']) ? "" : $_GET['sortby'];
    $get_offset = empty($_GET) || !empty($_GET) && empty($_GET['offset']) ? "" : $_GET['offset'];
    if (!isset($_GET['status'])) {
        $open = "Open";
    } else {
        $open = isset($_GET['status']) && $_GET['status'] == $GLOBALS['STATUS_OPEN'] ? "Open" : "";
        $open = isset($_GET['status']) && $_GET['status'] == $GLOBALS['STATUS_SCHEDULED'] ? "Scheduled" : "";
        //	11/29/10
    }
    if (isset($_SESSION['viewed_groups'])) {
        //	6/10/11
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    } else {
        $curr_viewed = $al_groups;
    }
    $curr_names = "";
    //	6/10/11
    $z = 0;
    //	6/10/11
    foreach ($curr_viewed as $grp_id) {
        //	6/10/11
        $counter = count($curr_viewed) > $z + 1 ? ", " : "";
        $curr_names .= get_groupname($grp_id);
        $curr_names .= $counter;
        $z++;
    }
    $heading = $captions[$func] . " - " . get_variable('map_caption');
    $regs_string = "<FONT SIZE='-1'>Allocated " . get_text("Regions") . ":&nbsp;&nbsp;" . $al_names . "&nbsp;&nbsp;|&nbsp;&nbsp;Currently Viewing " . get_text("Regions") . ":&nbsp;&nbsp;" . $curr_names . "</FONT>";
    //	6/10/11
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    @session_start();
    $query = "SELECT `id` FROM `{$GLOBALS['mysql_prefix']}responder`";
    // 5/12/10
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), __FILE__, __LINE__);
    unset($result);
    $required = 48 + mysql_affected_rows() * 22;
    // derived by trial and error - emphasis the latter = 7/18/10
    $the_height = (int) min(round($units_side_bar_height * $_SESSION['scr_height']), $required);
    // see main for $units_side_bar_height value
    $buttons_width = (int) get_variable('map_width') - 50;
    $show_controls = isset($_SESSION['hide_controls']) && $_SESSION['hide_controls'] == "s" ? "" : "none";
    //	3/15/11
    $col_butt = isset($_SESSION['hide_controls']) && $_SESSION['hide_controls'] == "s" ? "" : "none";
    //	3/15/11
    $exp_butt = isset($_SESSION['hide_controls']) && $_SESSION['hide_controls'] == "h" ? "" : "none";
    //	3/15/11
    $show_resp = isset($_SESSION['resp_list']) && $_SESSION['resp_list'] == "s" ? "" : "none";
    //	3/15/11
    $resp_col_butt = isset($_SESSION['resp_list']) && $_SESSION['resp_list'] == "s" ? "" : "none";
    //	3/15/11
    $resp_exp_butt = isset($_SESSION['resp_list']) && $_SESSION['resp_list'] == "h" ? "" : "none";
    //	3/15/11
    $show_facs = isset($_SESSION['facs_list']) && $_SESSION['facs_list'] == "s" ? "" : "none";
    //	3/15/11
    $facs_col_butt = isset($_SESSION['facs_list']) && $_SESSION['facs_list'] == "s" ? "" : "none";
    //	3/15/11
    $facs_exp_butt = isset($_SESSION['facs_list']) && $_SESSION['facs_list'] == "h" ? "" : "none";
    //	3/15/11
    $user_level = is_super() ? 9999 : $_SESSION['user_id'];
    $regions_inuse = get_regions_inuse($user_level);
    $group = get_regions_inuse_numbers($user_level);
    //	dump($group);
    //	dump(get_tickets_allocated($group));
    $test_size = 1200;
    // scale map down if monitor width LT test value - 6/28/11
    $map_factor = $_SESSION['scr_width'] < $test_size ? $_SESSION['scr_width'] / $test_size : 1.0;
    // a float
    $col_width = max(320, intval($_SESSION['scr_width'] * 0.45));
    $ctrls_width = $col_width * 0.75;
    ?>
<DIV style='z-index: 1;'>
<TABLE BORDER=0>
	<A NAME='top'></a>
	<TR CLASS='header'><TD COLSPAN='99' ALIGN='center'><FONT CLASS='header' STYLE='background-color: inherit;'><?php 
    print $heading;
    ?>
</FONT>
		<SPAN ID='sev_counts' CLASS='sev_counts'></SPAN>
	</TD></TR>
	<TR CLASS='header'><TD COLSPAN='99' ALIGN='center'>
		<SPAN ID='region_flags' style='background: #00FFFF; font-weight: bold;'></SPAN>
	</TD></TR>
	<TR CLASS='spacer'><TD CLASS='spacer' COLSPAN='99' ALIGN='center'>&nbsp;
	</TD></TR>
	<TR><TD align = 'left' VALIGN='TOP'  >
		<TABLE>
			<TR class = 'heading'><TH width = <?php 
    print $col_width;
    ?>
 ALIGN='center' COLSPAN='99'>Incidents <SPAN ID='sched_flag'></SPAN>
				<SPAN id='collapse_incs' onClick="hideDiv('incs_list_sh', 'collapse_incs', 'expand_incs')" style = 'display: "";'><IMG SRC = './markers/collapse.png' ALIGN='right'></SPAN>
			<SPAN id='expand_incs' onClick="showDiv('incs_list_sh', 'collapse_incs', 'expand_incs')" style = 'display: none;'><IMG SRC = './markers/expand.png' ALIGN='right'></SPAN>
			</TH></TR>
			<TR><TD>	
				<DIV ID='incs_list_sh'>
					<DIV ID = 'side_bar'></DIV>
				</DIV>
			</TD></TR>
		</TABLE>
		<TABLE>
			<TR class = 'heading'><TH width = <?php 
    print $col_width;
    ?>
 ALIGN='center' COLSPAN='99'>Responders 
				<SPAN id='collapse_resp' onClick="hideDiv('resp_list_sh', 'collapse_resp', 'expand_resp')" style = "display: <?php 
    print $resp_col_butt;
    ?>
;"><IMG SRC = './markers/collapse.png' ALIGN='right'></SPAN>
				<SPAN id='expand_resp' onClick="showDiv('resp_list_sh', 'collapse_resp', 'expand_resp')" style = "display: <?php 
    print $resp_exp_butt;
    ?>
;"><IMG SRC = './markers/expand.png' ALIGN='right'></SPAN>
			</TH></TR>
			<TR><TD>		
				<DIV ID='resp_list_sh' style='display: <?php 
    print $show_resp;
    ?>
'>
					<DIV ID = 'side_bar_r' style='min-height: 100px; max-height: <?php 
    print $the_height;
    ?>
px; overflow-y: scroll; overflow-x: hidden;'></DIV>
					<DIV ID = 'side_bar_rl'></DIV>
					<DIV STYLE = "height:12px;">&nbsp;</DIV>
					<DIV ID = 'units_legend'></DIV>
				</DIV>
			</TD></TR>
		</TABLE>
		<TABLE>
			<TR class = 'heading'><TH width = <?php 
    print $col_width;
    ?>
 ALIGN='center' COLSPAN='99'>Facilities 
				<SPAN id='collapse_facs' onClick="hideDiv('facs_list_sh', 'collapse_facs', 'expand_facs')" style = "display: <?php 
    print $facs_col_butt;
    ?>
;"><IMG SRC = './markers/collapse.png' ALIGN='right'></SPAN>
				<SPAN id='expand_facs' onClick="showDiv('facs_list_sh', 'collapse_facs', 'expand_facs')" style = "display: <?php 
    print $facs_exp_butt;
    ?>
;"><IMG SRC = './markers/expand.png' ALIGN='right'></SPAN>
			</TH></TR>
			<TR><TD>			
				<DIV ID='facs_list_sh' style='display: <?php 
    print $show_facs;
    ?>
'>
					<DIV ID = 'side_bar_f' style="min-height: 100px; max-height: <?php 
    print $the_height;
    ?>
px; overflow-y: scroll; overflow-x: hidden;"></DIV>
					<DIV STYLE = "height:12px">&nbsp;</DIV>
					<DIV ID = 'facs_legend'></DIV>
				</DIV>
			</TD></TR>
		</TABLE>	
	</TD>
	<TD></TD>
	<TD CLASS='td_label'>
	<TABLE>
		<TR><TD ALIGN='center' padding="0">
			<DIV ID='map' STYLE='WIDTH: <?php 
    print round($map_factor * get_variable('map_width'));
    ?>
PX; HEIGHT: <?php 
    print round($map_factor * get_variable('map_height'));
    ?>
PX; z-index: 999;'></DIV>
		</TD></TR>
		<TR><TD ALIGN='center' style='padding: 0'>
			<BR /><CENTER><A HREF='#' onClick='doGrid()'><u>Grid</U></A>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF='#' onClick='doTraffic()'><U>Traffic</U></A></CENTER>
		</TD></TR>
		<TR><TD>&nbsp;</TD></TR>				<!-- 3/15/11 -->
		<TR><TD>
			<TABLE ALIGN='center' WIDTH='<?php 
    print $ctrls_width;
    ?>
'>
				<TR class='heading'><TH ALIGN='center' COLSPAN=99>Show / Hide
					<SPAN id='collapse_buttons' onClick="hideDiv('buttons_sh', 'collapse_buttons', 'expand_buttons')" style = "display: <?php 
    print $col_butt;
    ?>
;"><IMG SRC = './markers/collapse.png' ALIGN='right'></SPAN>
					<SPAN id='expand_buttons' onClick="showDiv('buttons_sh', 'collapse_buttons', 'expand_buttons')" style = "display: <?php 
    print $exp_butt;
    ?>
;"><IMG SRC = './markers/expand.png' ALIGN='right'></SPAN>
				</TH></TR>
				<TR class='even'><TD>
					<CENTER>
						<TABLE ID='buttons_sh' style='display: <?php 
    print $show_controls;
    ?>
;'>
							<TR CLASS='odd'><TD>
								<TABLE>
									<TR class='heading_2'><TH ALIGN='center' WIDTH='<?php 
    print $ctrls_width;
    ?>
'>Incidents</TH></TR>
									<TR><TD>				<!-- 3/15/11 -->
										<DIV class='pri_button' onClick="set_pri_chkbox('normal'); hideGroup(1, 'Incident');"><IMG SRC = './our_icons/sm_blue.png' STYLE = 'vertical-align: middle'BORDER=0>&nbsp;&nbsp;Normal: <input type=checkbox id='normal'  onClick="set_pri_chkbox('normal')"/>&nbsp;&nbsp;</DIV>
										<DIV class='pri_button' onClick="set_pri_chkbox('medium'); hideGroup(2, 'Incident');"><IMG SRC = './our_icons/sm_green.png' BORDER=0 STYLE = 'vertical-align: middle'>&nbsp;&nbsp;Medium: <input type=checkbox id='medium'  onClick="set_pri_chkbox('medium')"/>&nbsp;&nbsp;</DIV>
										<DIV class='pri_button' onClick="set_pri_chkbox('high'); hideGroup(3, 'Incident');"><IMG SRC = './our_icons/sm_red.png' BORDER=0 STYLE = 'vertical-align: middle'>&nbsp;&nbsp;High: <input type=checkbox id='high'  onClick="set_pri_chkbox('high')"/>&nbsp;&nbsp;</DIV>
										<DIV class='pri_button' ID = 'pri_all' class='pri_button' STYLE = 'display: none; width: 70px;' onClick="set_pri_chkbox('all'); hideGroup(4, 'Incident');"><IMG SRC = './our_icons/sm_blue.png' BORDER=0 STYLE = 'vertical-align: middle'><IMG SRC = './our_icons/sm_green.png' BORDER=0 STYLE = 'vertical-align: middle'><IMG SRC = './our_icons/sm_red.png' BORDER=0 STYLE = 'vertical-align: middle'>&nbsp;&nbsp;All <input type=checkbox id='all'  STYLE = 'display:none;' onClick="set_pri_chkbox('all')"/>&nbsp;&nbsp;</DIV>
										<DIV class='pri_button' ID = 'pri_none' class='pri_button' STYLE = 'width: 60px;' onClick="set_pri_chkbox('none'); hideGroup(5, 'Incident');"><IMG SRC = './our_icons/sm_white.png' BORDER=0 STYLE = 'vertical-align: middle'>&nbsp;&nbsp;None <input type=checkbox id='none' STYLE = 'display:none;' onClick="set_pri_chkbox('none')"/>&nbsp;&nbsp;</DIV>
									</TD></TR>
								</TABLE>
							</TD></TR>
							<TR CLASS='odd'><TD>
								<DIV ID = 'boxes' ALIGN='center' VALIGN='middle' style='text-align: center; vertical-align: middle;'></DIV>
							</TD></TR>		<!-- 12/03/10, 3/15/11 -->
							<TR CLASS='odd'><TD>
								<DIV ID = 'fac_boxes' ALIGN='center' VALIGN='middle' style='text-align: center; vertical-align: middle;'></DIV>
							</TD></TR>		<!-- 12/03/10, 3/15/11 -->
							<TR CLASS='odd'><TD>
								<DIV ID = 'poly_boxes' ALIGN='center' VALIGN='middle' style='text-align: center; vertical-align: middle;'></DIV>
							</TD></TR>	
						</TABLE>
					</CENTER>
				</TD></TR>
			</TABLE>
		</TD></TR>
		<TR><TD CLASS='td_label' COLSPAN=99 ALIGN='CENTER'>
			&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="mailto:info@TicketsCAD.org?subject=Question/Comment on Tickets Dispatch System"><u>Contact us</u>&nbsp;&nbsp;&nbsp;&nbsp;<IMG SRC="mail.png" BORDER="0" STYLE="vertical-align: text-bottom"></A>
		</TD></TR>
	</TABLE>
	</TD></TR>
</TABLE>
</DIV>
<FORM NAME='unit_form' METHOD='get' ACTION="<?php 
    print $_SESSION['unitsfile'];
    ?>
">				<!-- 7/28/10 -->
<INPUT TYPE='hidden' NAME='func' VALUE='responder'>
<INPUT TYPE='hidden' NAME='view' VALUE=''>
<INPUT TYPE='hidden' NAME='edit' VALUE=''>
<INPUT TYPE='hidden' NAME='id' VALUE=''>
</FORM>

<FORM NAME='tick_form' METHOD='get' ACTION='<?php 
    print $_SESSION['editfile'];
    ?>
'>				<!-- 11/27/09 7/28/10 -->
<INPUT TYPE='hidden' NAME='id' VALUE=''>
</FORM>

<FORM NAME='sort_form' METHOD='post' ACTION='main.php'>				<!-- 6/11/10 -->
<INPUT TYPE='hidden' NAME='order' VALUE=''>
</FORM>

<FORM NAME='fac_sort_form' METHOD='post' ACTION='main.php'>				<!-- 3/15/11 -->
<INPUT TYPE='hidden' NAME='forder' VALUE=''>
</FORM>	

<FORM NAME='facy_form_ed' METHOD='get' ACTION='<?php 
    print $_SESSION['facilitiesfile'];
    ?>
'>		<!-- 8/3/10 -->
<INPUT TYPE='hidden' NAME='id' VALUE=''>
<INPUT TYPE='hidden' NAME='edit' VALUE='true'>
</FORM>

<SCRIPT>
//================================= 7/18/10
	$('region_flags').innerHTML = "<?php 
    print $regs_string;
    ?>
";			// 5/2/10
<?php 
    function get_buttons($user_id)
    {
        //	5/3/11
        $regs_viewed = "";
        if (isset($_SESSION['viewed_groups'])) {
            $regs_viewed = explode(",", $_SESSION['viewed_groups']);
        }
        $query2 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$user_id}' ORDER BY `group`";
        //	5/3/11
        $result2 = mysql_query($query2) or do_error($query2, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        $al_buttons = "";
        while ($row2 = stripslashes_deep(mysql_fetch_assoc($result2))) {
            //	5/3/11
            if (!empty($regs_viewed)) {
                if (in_array($row2['group'], $regs_viewed)) {
                    $al_buttons .= "<DIV style='display: block;'><INPUT TYPE='checkbox' CHECKED name='frm_group[]' VALUE='{$row2['group']}'></INPUT>" . get_groupname($row2['group']) . "&nbsp;&nbsp;</DIV>";
                } else {
                    $al_buttons .= "<DIV style='display: block;'><INPUT TYPE='checkbox' name='frm_group[]' VALUE='{$row2['group']}'></INPUT>" . get_groupname($row2['group']) . "&nbsp;&nbsp;</DIV>";
                }
            } else {
                $al_buttons .= "<DIV style='display: block;'><INPUT TYPE='checkbox' CHECKED name='frm_group[]' VALUE='{$row2['group']}'></INPUT>" . get_groupname($row2['group']) . "&nbsp;&nbsp;</DIV>";
            }
        }
        //		dump($al_buttons);
        return $al_buttons;
    }
    if (get_num_groups() && COUNT(get_allocates(4, $_SESSION['user_id'])) > 1) {
        //	6/10/11
        ?>
	side_bar_html= "";
	side_bar_html+="<TABLE><TR class='even'><TD COLSPAN=99 CLASS='td_label' ><form name='region_form' METHOD='post' action='main.php'><DIV>";
	side_bar_html += "<?php 
        print get_buttons($_SESSION['user_id']);
        ?>
";
	side_bar_html+="</DIV></form></TD></TR><TR><TD>&nbsp;</TD></TR><TR><TD ALIGN='center'><INPUT TYPE='button' VALUE='Update' onClick='form_validate(document.region_form);'></TD></TR></TABLE>";
	$("region_boxes").innerHTML = side_bar_html;		
<?php 
    }
    ?>
	var boundary = new Array();	
	var bound_names = new Array();
	
	function add_hash(in_str) { // prepend # if absent
		return (in_str.substr(0,1)=="#")? in_str : "#" + in_str;
		}

	function do_landb() {				// JS function - 8/1/11
		var points = new Array();
<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}mmarkup` WHERE `line_status` = 0 AND `use_with_bm` = 1";
    $result = mysql_query($query) or do_error($query, $query, mysql_error(), basename(__FILE__), __LINE__);
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        $empty = FALSE;
        extract($row);
        $name = $row['line_name'];
        switch ($row['line_type']) {
            case "p":
                // poly
                $points = explode(";", $line_data);
                echo "\n\tvar points = new Array();\n";
                for ($i = 0; $i < count($points); $i++) {
                    $coords = explode(",", $points[$i]);
                    ?>
						var thepoint = new GLatLng(<?php 
                    print $coords[0];
                    ?>
, <?php 
                    print $coords[1];
                    ?>
);
						bounds.extend(thepoint);
						points.push(thepoint);
<?php 
                }
                // end for ($i = 0 ... )
                if (intval($filled) == 1 && count($points) > 2) {
                    ?>
						var polyline = new GPolygon(points,add_hash("<?php 
                    print $line_color;
                    ?>
"), <?php 
                    print $line_width;
                    ?>
, <?php 
                    print $line_opacity;
                    ?>
,add_hash("<?php 
                    print $fill_color;
                    ?>
"), <?php 
                    print $fill_opacity;
                    ?>
);
<?php 
                } else {
                    ?>
				        var polyline = new GPolyline(points, add_hash("<?php 
                    print $line_color;
                    ?>
"), <?php 
                    print $line_width;
                    ?>
, <?php 
                    print $line_opacity;
                    ?>
);
<?php 
                }
                ?>
				        
						map.addOverlay(polyline);
<?php 
                break;
            case "c":
                // circle
                $temp = explode(";", $line_data);
                $radius = $temp[1];
                $coords = explode(",", $temp[0]);
                $lat = $coords[0];
                $lng = $coords[1];
                $fill_opacity = intval($filled) == 0 ? 0 : $fill_opacity;
                echo "\n drawCircle({$lat}, {$lng}, {$radius}, add_hash('{$line_color}'), {$line_width}, {$line_opacity}, add_hash('{$fill_color}'), {$fill_opacity}, {$name}); // 513\n";
                break;
            case "t":
                // text banner
                $temp = explode(";", $line_data);
                $banner = $temp[1];
                $coords = explode(",", $temp[0]);
                echo "\n var point = new GLatLng(parseFloat({$coords[0]}) , parseFloat({$coords[1]}));\n";
                $the_banner = htmlentities($banner, ENT_QUOTES);
                $the_width = intval(trim($line_width), 10);
                // font size
                echo "\n drawBanner( point, '{$the_banner}', '{$the_banner}', {$the_width});\n";
                break;
        }
        // end switch
    }
    // end while ()
    unset($query, $result);
    ?>
		}		// end function do_landb()
/*
	try {
		do_landb();				// 7/3/11 - show lines
		}
	catch (e) {	}
*/


//================================= 7/18/10
	var spe=500;
	var NameOfYourTags="mi";
	var swi=1;
	var na=document.getElementsByName(NameOfYourTags);
	var sho;
	
	doBlink();
	
	function doBlink() {
		if (swi == 1) {
			sho="visible";
			swi=0;
			}
		else {
			sho="hidden";
			swi=1;
			}
	
		for(i=0;i<na.length;i++) {
			na[i].style.visibility=sho;
			}
		setTimeout("doBlink()", spe);
		}
		
	Array.prototype.contains = function (element) {
		for (var i = 0; i < this.length; i++) {
		if (this[i] == element) {
		return true;
		}
		}
		return false;
		}	
	
	function writeConsole(content) {
		top.consoleRef=window.open('','myconsole',
			'width=800,height=250' +',menubar=0' +',toolbar=0' +',status=0' +',scrollbars=1' +',resizable=1')
	 	top.consoleRef.document.writeln('<html><head><title>Console</title></head>'
			+'<body bgcolor=white onLoad="self.focus()">' +content +'</body></html>'
			)				// end top.consoleRef.document.writeln()
	 	top.consoleRef.document.close();
		}				// end function writeConsole(content)
	

	function isNull(val) {								// checks var stuff = null;
		return val === null;
		}

	function to_session(the_name, the_value) {									// generic session variable writer - 3/8/10, 4/4/10
		function local_handleResult(req) {			// the called-back function
			}			// end function local handleResult

		var params = "f_n=" + the_name;				// 1/20/09
		params += "&f_v=" + the_value;				// 4/4/10
		sendRequest ('do_session_get.php',local_handleResult, params);			// does the work via POST
		}


	function to_server(the_unit, the_status) {									// write unit status data via ajax xfer
		var querystr = "frm_responder_id=" + the_unit;
		querystr += "&frm_status_id=" + the_status;
	
		var url = "as_up_un_status.php?" + querystr;			// 
		var payload = syncAjax(url);						// 
		if (payload.substring(0,1)=="-") {	
			alert ("<?php 
    print __LINE__;
    ?>
: msg failed ");
			return false;
			}
		else {
			parent.frames['upper'].show_msg ('Unit status update applied!')
			return true;
			}				// end if/else (payload.substring(... )
		}		// end function to_server()

	function to_server_fac(the_unit, the_status) {		//	3/15/11							// 3/15/11
		var querystr = "frm_responder_id=" + the_unit;
		querystr += "&frm_status_id=" + the_status;
	
		var url = "as_up_fac_status.php?" + querystr;
		var payload = syncAjax(url); 
		if (payload.substring(0,1)=="-") {	
			alert ("<?php 
    print __LINE__;
    ?>
: msg failed ");
			return false;
			}
		else {
			parent.frames['upper'].show_msg ('Facility status update applied!')
			return true;
			}				// end if/else (payload.substring(... )
		}		// end function to_server_fac()
	
	function syncAjax(strURL) {							// synchronous ajax function
		if (window.XMLHttpRequest) {						 
			AJAX=new XMLHttpRequest();						 
			} 
		else {																 
			AJAX=new ActiveXObject("Microsoft.XMLHTTP");
			}
		if (AJAX) {
			AJAX.open("GET", strURL, false);														 
			AJAX.send(null);							// e
			return AJAX.responseText;																				 
			} 
		else {
			alert ("<?php 
    print __LINE__;
    ?>
: failed");
			return false;
			}																						 
		}		// end function sync Ajax(strURL)

	var starting = false;
	
	function do_mail_win(the_id) {	

		if(starting) {return;}					// dbl-click catcher
		starting=true;
		var url = "do_unit_mail.php?name=" + escape(the_id);	//
		newwindow_mail=window.open(url, "mail_edit",  "titlebar, location=0, resizable=1, scrollbars, height=320,width=720,status=0,toolbar=0,menubar=0,location=0, left=100,top=300,screenX=100,screenY=300");
		if (isNull(newwindow_mail)) {
			alert ("Email edit operation requires popups to be enabled -- please adjust your browser options.");
			return;
			}
		newwindow_mail.focus();
		starting = false;
		}		// end function do mail_win()

	function do_fac_mail_win(the_name, the_addrs) {			// 3/8/10
		if(starting) {return;}					// dbl-click catcher
		starting=true;
		var url = (isNull(the_name))? "do_fac_mail.php?" : "do_fac_mail.php?name=" + escape(the_name) + "&addrs=" + escape(the_addrs);	//
		newwindow_mail=window.open(url, "mail_edit",  "titlebar, location=0, resizable=1, scrollbars, height=320,width=720,status=0,toolbar=0,menubar=0,location=0, left=100,top=300,screenX=100,screenY=300");
		if (isNull(newwindow_mail)) {
			alert ("Email edit operation requires popups to be enabled -- please adjust your browser options.");
			return;
			}
		newwindow_mail.focus();
		starting = false;
		}		// end function do mail_win()


	function do_close_tick(the_id) {	//	3/15/11
		if(starting) {return;}					// dbl-click catcher
		starting=true;
		var url = "close_in.php?ticket_id=" + escape(the_id);	//
		newwindow_close = window.open(url, "close_ticket", "titlebar, location=0, resizable=1, scrollbars, height=300, width=700, status=0, toolbar=0, menubar=0, left=100,top=100,screenX=100,screenY=100");
		if (isNull(newwindow_close)) {
			alert ("Close Ticket operation requires popups to be enabled -- please adjust your browser options.");
			return;
			}
		newwindow_close.focus();
		starting = false;
		}		// end function do mail_win()

	function to_str(instr) {			// 0-based conversion - 2/13/09
		function ord( string ) {
		    return (string+'').charCodeAt(0);
			}

		function chr( ascii ) {
		    return String.fromCharCode(ascii);
			}
		function to_char(val) {
			return(chr(ord("A")+val));
			}

		var lop = (instr % 26);													// low-order portion, a number
		var hop = ((instr - lop)==0)? "" : to_char(((instr - lop)/26)-1) ;		// high-order portion, a string
		return hop+to_char(lop);
		}

	function sendRequest(url,callback,postData) {								// 2/14/09
		var req = createXMLHTTPObject();
		if (!req) return;
		var method = (postData) ? "POST" : "GET";
		req.open(method,url,true);
		req.setRequestHeader('User-Agent','XMLHTTP/1.0');
		if (postData)
			req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		req.onreadystatechange = function () {
			if (req.readyState != 4) return;
			if (req.status != 200 && req.status != 304) {
<?php 
    if ($istest) {
        print "\t\t\talert('HTTP error ' + req.status + '" . __LINE__ . "');\n";
    }
    ?>
				return;
				}
			callback(req);
			}
		if (req.readyState == 4) return;
		req.send(postData);
		}

	var XMLHttpFactories = [
		function () {return new XMLHttpRequest()	},
		function () {return new ActiveXObject("Msxml2.XMLHTTP")	},
		function () {return new ActiveXObject("Msxml3.XMLHTTP")	},
		function () {return new ActiveXObject("Microsoft.XMLHTTP")	}
		];

	function createXMLHTTPObject() {
		var xmlhttp = false;
		for (var i=0;i<XMLHttpFactories.length;i++) {
			try {
				xmlhttp = XMLHttpFactories[i]();
				}
			catch (e) {
//				continue;
				}
			break;
			}
		return xmlhttp;
		}

	function get_chg_disp_tr() {								// 5/5/11
		var chg_disp_tr ="<TR><TD COLSPAN=99 ALIGN='center'>\n";
		chg_disp_tr +="\t\t<FORM NAME = 'frm_interval_sel' STYLE = 'display:inline' >\n";
		chg_disp_tr +="\t\t<SELECT NAME = 'frm_interval' onChange = 'do_listtype(this.value);'>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='99' SELECTED><?php 
    print get_text("Change display");
    ?>
</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='0'><?php 
    print get_text("Current situation");
    ?>
</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='1'><?php 
    print $incidents;
    ?>
 closed today</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='2'><?php 
    print $incidents;
    ?>
 closed yesterday+</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='3'><?php 
    print $incidents;
    ?>
 closed this week</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='4'><?php 
    print $incidents;
    ?>
 closed last week</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='5'><?php 
    print $incidents;
    ?>
 closed last week+</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='6'><?php 
    print $incidents;
    ?>
 closed this month</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='7'><?php 
    print $incidents;
    ?>
 closed last month</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='8'><?php 
    print $incidents;
    ?>
 closed this year</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='9'><?php 
    print $incidents;
    ?>
 closed last year</OPTION>\n";
		chg_disp_tr +="\t\t</SELECT>\n</FORM>\n";
		chg_disp_tr +="\t\t<SPAN ID = 'btn_go' onClick='document.to_listtype.submit()' CLASS='conf_button' STYLE = 'margin-left: 10px; display:none'><U>Next</U></SPAN>";
		chg_disp_tr +="\t\t<SPAN ID = 'btn_can'  onClick='hide_btns_closed(); hide_btns_scheduled(); ' CLASS='conf_button' STYLE = 'margin-left: 10px; display:none'><U>Cancel</U></SPAN>";
		chg_disp_tr +="<br /><br /></TD></TR>\n";

		return chg_disp_tr;
		} 					// end function get chg_disp_tr()

<?php 
    $quick = (is_super() || is_administrator()) && intval(get_variable('quick') == 1);
    // 8/3/10
    print $quick ? "var quick = true;\n" : "var quick = false;\n";
    ?>
var tr_id_fixed_part = "tr_id_";		// 3/2/10

if (GBrowserIsCompatible()) {

//	$("map").style.backgroundImage = "url(./markers/loading.jpg)";
	$("map").style.backgroundImage = "url('http://maps.google.com/staticmap?center=<?php 
    echo get_variable('def_lat');
    ?>
,<?php 
    echo get_variable('def_lng');
    ?>
&zoom=<?php 
    echo get_variable('def_zoom');
    ?>
&size=<?php 
    echo round($map_factor * get_variable('map_width'));
    ?>
x<?php 
    echo round($map_factor * get_variable('map_height'));
    ?>
&key=<?php 
    echo get_variable('gmaps_api_key');
    ?>
 ')";

	var colors = new Array ('odd', 'even');

	function drawCircle(lat, lng, radius, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity, name) {		// 8/19/09
	
//		drawCircle(53.479874, -2.246704, 10.0, "#000080", 1, 0.75, "#0000FF", .5);

		var d2r = Math.PI/180;
		var r2d = 180/Math.PI;
		var Clat = radius * 0.014483;
		var Clng = Clat/Math.cos(lat * d2r);
		var Cpoints = [];
		for (var i=0; i < 33; i++) {
			var theta = Math.PI * (i/16);
			Cy = lat + (Clat * Math.sin(theta));
			Cx = lng + (Clng * Math.cos(theta));
			var P = new GPoint(Cx,Cy);
			Cpoints.push(P);
			}
		var polygon = new GPolygon(Cpoints, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity);
		map.addOverlay(polygon);
		}
		
	function drawBanner(point, html, text, font_size, color, name) {        // Create the banner
	//	alert("<?php 
    echo __LINE__;
    ?>
 " + color);
		var invisibleIcon = new GIcon(G_DEFAULT_ICON, "./markers/markerTransparent.png");      // Custom icon is identical to the default icon, except invisible

		map.setCenter(point, 8);
//		map.addControl(new GLargeMapControl());
//		map.addControl(new GMapTypeControl());
		var the_color = (typeof color == 'undefined')? "#000000" : color ;	// default to black

		var style_str = 'background-color:transparent;font-weight:bold;border:0px black solid;white-space:nowrap; font-size:' + font_size + 'px; font-family:arial; opacity: 0.9; color:' + add_hash(the_color) + ';';

		var contents = '<div><div style= "' + style_str + '">'+text+'<\/div><\/div>';
		var label=new ELabel(point, contents, null, new GSize(-8,4), 75, 1);
		map.addOverlay(label);
		
		var marker = new GMarker(point,invisibleIcon);	        // Create an invisible GMarker
	//	map.addOverlay(marker);
		
		}				// end function draw Banner()		
		
	function URLEncode(plaintext ) {					// 3/15/11 The Javascript escape and unescape functions do,
														// NOT correspond with what browsers actually do...
		var SAFECHARS = "0123456789" +					// Numeric
						"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
						"abcdefghijklmnopqrstuvwxyz" +	// guess
						"-_.!*'()";					// RFC2396 Mark characters
		var HEX = "0123456789ABCDEF";
	
		var encoded = "";
		for (var i = 0; i < plaintext.length; i++ ) {
			var ch = plaintext.charAt(i);
			if (ch == " ") {
				encoded += "+";				// x-www-urlencoded, rather than %20
			} else if (SAFECHARS.indexOf(ch) != -1) {
				encoded += ch;
			} else {
				var charCode = ch.charCodeAt(0);
				if (charCode > 255) {
					alert( "Unicode Character '"
							+ ch
							+ "' cannot be encoded using standard URL encoding.\n" +
							  "(URL encoding only supports 8-bit characters.)\n" +
							  "A space (+) will be substituted." );
					encoded += "+";
				} else {
					encoded += "%";
					encoded += HEX.charAt((charCode >> 4) & 0xF);
					encoded += HEX.charAt(charCode & 0xF);
					}
				}
			} 			// end for(...)
		return encoded;
		};			// end function		

//	Tickets show / hide by Priority functions

	function set_initial_pri_disp() {
		$('normal').checked = true;
		$('medium').checked = true;
		$('high').checked = true;
		$('all').checked = true;
		$('none').checked = false;
	}

	function hideGroup(color, category) {			// 8/7/09 Revised function to correct incorrect display, revised 12/03/10 completely revised
		var priority = color;
		var priority_name="";
		if(priority == 1) {
			priority_name="normal";
		}
		if(priority == 2) {
			priority_name="medium";
		}
		if(priority == 3) {
			priority_name="high";
		}
		if(priority == 4) {
			priority_name="all";
		}

		if(priority == 5) {
			priority_name="none";
		}

		if(priority == 1) {
			for (var i = 0; i < gmarkers.length; i++) {
				if (gmarkers[i]) {
					if ((gmarkers[i].id == priority) && (gmarkers[i].category == category)) {
						gmarkers[i].show();
						}
					if ((gmarkers[i].id != priority) && (gmarkers[i].category == category)) {
						gmarkers[i].hide();
						}

					}		// end if (gmarkers[i])
				} 	// end for ()
			$('normal').checked = true;
			$('medium').checked = false;
			$('high').checked = false;
			$('all').checked = false;
			$('none').checked = false;
			$('pri_all').style.display = '';
			$('pri_none').style.display = '';
			}	//	end if priority == 1
		if(priority == 2) {
			for (var i = 0; i < gmarkers.length; i++) {
				if (gmarkers[i]) {
					if ((gmarkers[i].id == priority) && (gmarkers[i].category == category)) {
						gmarkers[i].show();
						}
					if ((gmarkers[i].id != priority) && (gmarkers[i].category == category)) {
						gmarkers[i].hide();
						}

					}		// end if (gmarkers[i])
				} 	// end for ()
			$('normal').checked = false;
			$('medium').checked = true;
			$('high').checked = false;
			$('all').checked = false;
			$('none').checked = false;
			$('pri_all').style.display = '';
			$('pri_none').style.display = '';
			}	//	end if priority == 2
		if(priority == 3) {
			for (var i = 0; i < gmarkers.length; i++) {
				if (gmarkers[i]) {
					if ((gmarkers[i].id == priority) && (gmarkers[i].category == category)) {
						gmarkers[i].show();
						}
					if ((gmarkers[i].id != priority) && (gmarkers[i].category == category)) {
						gmarkers[i].hide();
						}

					}		// end if (gmarkers[i])
				} 	// end for ()
			$('normal').checked = false;
			$('medium').checked = false;
			$('high').checked = true;
			$('all').checked = false;
			$('none').checked = false;
			$('pri_all').style.display = '';
			$('pri_none').style.display = '';
			}	//	end if priority == 3
		if(priority == 4) {		//	show All
			for (var i = 0; i < gmarkers.length; i++) {
				if (gmarkers[i]) {
					if (gmarkers[i].category == category) {
						gmarkers[i].show();
						}
					}		// end if (gmarkers[i])
				} 	// end for ()
			$('normal').checked = true;
			$('medium').checked = true;
			$('high').checked = true;
			$('all').checked = true;
			$('none').checked = false;
			$('pri_all').style.display = 'none';
			$('pri_none').style.display = '';
			}	//	end if priority == 4
		if(priority == 5) {		// hide all
			for (var i = 0; i < gmarkers.length; i++) {
				if (gmarkers[i]) {
					if (gmarkers[i].category == category) {
						gmarkers[i].hide();
						}
					}		// end if (gmarkers[i])
				} 	// end for ()
			$('normal').checked = false;
			$('medium').checked = false;
			$('high').checked = false;
			$('all').checked = false;
			$('none').checked = true;
			$('pri_all').style.display = '';
			$('pri_none').style.display = 'none';
			}	//	end if priority == 5
		}			// end function hideGroup(color, category)

	function set_pri_chkbox(control) {
		var pri_control = control;
		if($(pri_control).checked == true) {
			$(pri_control).checked = false;
			} else {
			$(pri_control).checked = true;
			}
		}

//	End of Tickets show / hide by Priority functions		

// 	Units show / hide functions				
		
	function set_categories() {			//	12/03/10 - checks current session values and sets checkboxes and view states for hide and show.
		var curr_cats = <?php 
    echo json_encode(get_category_butts());
    ?>
;
		var cat_sess_stat = <?php 
    echo json_encode(get_session_status());
    ?>
;
		var hidden = <?php 
    print find_hidden();
    ?>
;
		var shown = <?php 
    print find_showing();
    ?>
;
		var number_of_units = <?php 
    print get_no_units();
    ?>
;
		if(hidden!=0) {
			$('ALL').style.display = '';
			$('ALL_BUTTON').style.display = '';
			$('ALL').checked = false;	
		} else {			
			$('ALL').style.display = 'none';
			$('ALL_BUTTON').style.display = 'none';
			$('ALL').checked = false;
		}
		if((shown!=0) && (number_of_units > 0)) {
			$('NONE').style.display = '';
			$('NONE_BUTTON').style.display = '';
			$('NONE').checked = false;	
		} else {
			$('NONE').style.display = 'none';
			$('NONE_BUTTON').style.display = 'none';
			$('NONE').checked = false;

		}
		for (var i = 0; i < curr_cats.length; i++) {
			var catname = curr_cats[i];
			if(cat_sess_stat[i]=="s") {
				for (var j = 0; j < gmarkers.length; j++) {
					if ((gmarkers[j]) && (gmarkers[j].category) && (gmarkers[j].category == catname)) {
						gmarkers[j].show();
						var catid = catname + j;
						if($(catid)) {
							$(catid).style.display = "";
							}
						}
					}
				$(catname).checked = true;
			} else {
				for (var j = 0; j < gmarkers.length; j++) {
					if ((gmarkers[j]) && (gmarkers[j].category) && (gmarkers[j].category == catname)) {
						gmarkers[j].hide();
						var catid = catname + j;
						if($(catid)) {
							$(catid).style.display = "none";
							}
						}
					}
				$(catname).checked = false;
				}				
			}
		}
		

	function do_view_cats() {							// 12/03/10	Show Hide categories, Showing and setting onClick attribute for Next button for category show / hide.
		$('go_can').style.display = 'inline';
		$('can_button').style.display = 'inline';
		$('go_button').style.display = 'inline';
		}

	function cancel_buttons() {							// 12/03/10	Show Hide categories, Showing and setting onClick attribute for Next button for category show / hide.
		$('go_can').style.display = 'none';
		$('can_button').style.display = 'none';
		$('go_button').style.display = 'none';
		$('ALL').checked = false;
		$('NONE').checked = false;
		}

	function set_chkbox(control) {
		var units_control = control;
		if($(units_control).checked == true) {
			$(units_control).checked = false;
			} else {
			$(units_control).checked = true;
			}
		do_view_cats();
		}

	function do_go_button() {							// 12/03/10	Show Hide categories
		var curr_cats = <?php 
    echo json_encode(get_category_butts());
    ?>
;
		if ($('ALL').checked == true) {
			for (var i = 0; i < curr_cats.length; i++) {
				var category = curr_cats[i];
				var params = "f_n=show_hide_" +URLEncode(category)+ "&v_n=s&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
				var url = "persist2.php";	//	3/15/11
				sendRequest (url, gb_handleResult, params);
				$(category).checked = true;				
				for (var j = 0; j < gmarkers.length; j++) {
					var catid = category + j;
					if($(catid)) {
						$(catid).style.display = "";
					}
					if((gmarkers[j]) && (gmarkers[j].category!="Incident")) {				
					gmarkers[j].show();
					}
					}
				}
				$('ALL').checked = false;
				$('ALL').style.display = 'none';
				$('ALL_BUTTON').style.display = 'none';				
				$('NONE').style.display = '';
				$('NONE_BUTTON').style.display = '';				
				$('go_button').style.display = 'none';
				$('can_button').style.display = 'none';				

		} else if ($('NONE').checked == true) {
			for (var i = 0; i < curr_cats.length; i++) {
				var category = curr_cats[i];
				var params = "f_n=show_hide_" +URLEncode(category)+ "&v_n=h&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
				var url = "persist2.php";	//	3/15/11
				sendRequest (url, gb_handleResult, params);	
				$(category).checked = false;				
				for (var j = 0; j < gmarkers.length; j++) {
					var catid = category + j;
					if($(catid)) {
						$(catid).style.display = "none";
					}
					if((gmarkers[j]) && (gmarkers[j].category!="Incident")) {
						gmarkers[j].hide();
					}
					}
				}
				$('NONE').checked = false;
				$('ALL').style.display = '';
				$('ALL_BUTTON').style.display = '';				
				$('NONE').style.display = 'none';
				$('NONE_BUTTON').style.display = 'none';					
				$('go_button').style.display = 'none';
				$('can_button').style.display = 'none';
		} else {
			var x = 0;
			var y = 0;
			for (var i = 0; i < curr_cats.length; i++) {

				var category = curr_cats[i];
				if ($(category).checked == true) {
					x++;
					var params = "f_n=show_hide_" +URLEncode(category)+ "&v_n=s&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
					var url = "persist2.php";	//	3/15/11
					sendRequest (url, gb_handleResult, params);
					$(category).checked = true;			
					for (var j = 0; j < gmarkers.length; j++) {
						var catid = category + j;
						if($(catid)) {
							$(catid).style.display = "";
							}
						if ((gmarkers[j]) && (gmarkers[j].category) && (gmarkers[j].category == category)) {			
							gmarkers[j].show();
							}
						}
					}
				}
			for (var i = 0; i < curr_cats.length; i++) {
				var category = curr_cats[i];				
				if ($(category).checked == false) {
					y++;
					var params = "f_n=show_hide_" +URLEncode(category)+ "&v_n=h&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
					var url = "persist2.php";	//	3/15/11
					sendRequest (url, gb_handleResult, params);
					$(category).checked = false;
					var y=0;
					for (var j = 0; j < gmarkers.length; j++) {
						var catid = category + j;
						if($(catid)) {
							$(catid).style.display = "none";
							}
						if ((gmarkers[j]) && (gmarkers[j].category) && (gmarkers[j].category == category)) {			
							gmarkers[j].hide();
							}
						}
					}	
				}
			}



		$('go_button').style.display = 'none';
		$('can_button').style.display = 'none';

		if((x > 0) && (x < curr_cats.length)) {
			$('ALL').style.display = '';
			$('ALL_BUTTON').style.display = '';
			$('NONE').style.display = '';
			$('NONE_BUTTON').style.display = '';
		}
		if(x == 0) {
			$('ALL').style.display = '';
			$('ALL_BUTTON').style.display = '';
			$('NONE').style.display = 'none';
			$('NONE_BUTTON').style.display = 'none';
		}
		if(x == curr_cats.length) {
			$('ALL').style.display = 'none';
			$('ALL_BUTTON').style.display = 'none';
			$('NONE').style.display = '';
			$('NONE_BUTTON').style.display = '';
		}


	}	// end function do_go_button()

	function gb_handleResult(req) {							// 12/03/10	The persist callback function
		}

// Facilities show / hide functions		

	function set_fac_categories() {			//	12/03/10 - checks current session values and sets checkboxes and view states for hide and show, revised 3/15/11.
		var fac_curr_cats = <?php 
    echo json_encode(get_fac_category_butts());
    ?>
;
		var fac_cat_sess_stat = <?php 
    echo json_encode(get_fac_session_status());
    ?>
;
		var fac_hidden = <?php 
    print find_fac_hidden();
    ?>
;
		var fac_shown = <?php 
    print find_fac_showing();
    ?>
;
		if(fac_hidden!=0) {
			$('fac_ALL').style.display = '';
			$('fac_ALL_BUTTON').style.display = '';
			$('fac_ALL').checked = false;	
		} else {			
			$('fac_ALL').style.display = 'none';
			$('fac_ALL_BUTTON').style.display = 'none';
			$('fac_ALL').checked = false;
		}
		if(fac_shown!=0) {
			$('fac_NONE').style.display = '';
			$('fac_NONE_BUTTON').style.display = '';
			$('fac_NONE').checked = false;
		} else {
			$('fac_NONE').style.display = 'none';
			$('fac_NONE_BUTTON').style.display = 'none';
			$('fac_NONE').checked = false;
		}
		for (var i = 0; i < fac_curr_cats.length; i++) {
			var fac_catname = fac_curr_cats[i];
			if(fac_cat_sess_stat[i]=="s") {
				for (var j = 0; j < fmarkers.length; j++) {
					if (fmarkers[j].category == fac_catname) {
						fmarkers[j].show();
						var fac_catid = fac_catname + j;
						if($(fac_catid)) {
							$(fac_catid).style.display = "";
							}
						}
					}
				$(fac_catname).checked = true;
			} else {
				for (var j = 0; j < fmarkers.length; j++) {
					if (fmarkers[j].category == fac_catname) {
						fmarkers[j].hide();
						var fac_catid = fac_catname + j;
						if($(fac_catid)) {
							$(fac_catid).style.display = "none";
							}
						}
					}
				$(fac_catname).checked = false;
				}				
			}
		}

	function do_view_fac_cats() {							// 12/03/10	Show Hide categories, Showing and setting onClick attribute for Next button for category show / hide.
		$('fac_go_can').style.display = 'inline';
		$('fac_can_button').style.display = 'inline';
		$('fac_go_button').style.display = 'inline';
		}

	function fac_cancel_buttons() {							// 12/03/10	Show Hide categories, Showing and setting onClick attribute for Next button for category show / hide.
		$('fac_go_can').style.display = 'none';
		$('fac_can_button').style.display = 'none';
		$('fac_go_button').style.display = 'none';
		$('fac_ALL').checked = false;
		$('fac_NONE').checked = false;
		}

	function set_fac_chkbox(control) {
		var fac_control = control;
		if($(fac_control).checked == true) {
			$(fac_control).checked = false;
			} else {
			$(fac_control).checked = true;
			}
		do_view_fac_cats();
		}

	function do_go_facilities_button() {							// 12/03/10	Show Hide categories
		var fac_curr_cats = <?php 
    echo json_encode(get_fac_category_butts());
    ?>
;
		if ($('fac_ALL').checked == true) {
			for (var i = 0; i < fac_curr_cats.length; i++) {
				var fac_category = fac_curr_cats[i];
				var params = "f_n=show_hide_fac_" +URLEncode(fac_category)+ "&v_n=s&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
				var url = "persist2.php";	//	3/15/11
				sendRequest (url, gb_handleResult, params);
				$(fac_category).checked = true;				
				for (var j = 0; j < fmarkers.length; j++) {
					var fac_catid = fac_category + j;
					if($(fac_catid)) {
						$(fac_catid).style.display = "";
					}
					if(fmarkers[j].category != "Incident") {				
					fmarkers[j].show();
					}
					}
				}
				$('fac_ALL').checked = false;
				$('fac_ALL').style.display = 'none';
				$('fac_ALL_BUTTON').style.display = 'none';				
				$('fac_NONE').style.display = '';
				$('fac_NONE_BUTTON').style.display = '';				
				$('fac_go_button').style.display = 'none';
				$('fac_can_button').style.display = 'none';

		} else if ($('fac_NONE').checked == true) {
			for (var i = 0; i < fac_curr_cats.length; i++) {
				var fac_category = fac_curr_cats[i];
				var params = "f_n=show_hide_fac_" +URLEncode(fac_category)+ "&v_n=h&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
				var url = "persist2.php";	//	3/15/11
				sendRequest (url, gb_handleResult, params);	
				$(fac_category).checked = false;				
				for (var j = 0; j < fmarkers.length; j++) {
					var fac_catid = fac_category + j;
					if($(fac_catid)) {
						$(fac_catid).style.display = "none";
					}
					if(fmarkers[j].category != "Incident") {
						fmarkers[j].hide();
					}
					}
				}
				$('fac_NONE').checked = false;
				$('fac_ALL').style.display = '';
				$('fac_ALL_BUTTON').style.display = '';				
				$('fac_NONE').style.display = 'none';
				$('fac_NONE_BUTTON').style.display = 'none';					
				$('fac_go_button').style.display = 'none';
				$('fac_can_button').style.display = 'none';
		} else {
			var x = 0;
			var y = 0;
			for (var i = 0; i < fac_curr_cats.length; i++) {

				var fac_category = fac_curr_cats[i];
				if ($(fac_category).checked == true) {
					if($('fac_table').style.display == 'none') {
						$('fac_table').style.display = 'inline-block';
						$('side_bar_f').style.display = 'inline-block';
						}
					x++;
					var params = "f_n=show_hide_fac_" +URLEncode(fac_category)+ "&v_n=s&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
					var url = "persist2.php";	//	3/15/11
					sendRequest (url, gb_handleResult, params);
					$(fac_category).checked = true;			
					for (var j = 0; j < fmarkers.length; j++) {
						var fac_catid = fac_category + j;
						if($(fac_catid)) {
							$(fac_catid).style.display = "";
							}
						if(fmarkers[j].category == fac_category) {			
							fmarkers[j].show();
							}
						}
					}
				}
			for (var i = 0; i < fac_curr_cats.length; i++) {
				var fac_category = fac_curr_cats[i];				
				if ($(fac_category).checked == false) {
					y++;
					var params = "f_n=show_hide_fac_" +URLEncode(fac_category)+ "&v_n=h&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
					var url = "persist2.php";	//	3/15/11
					sendRequest (url, gb_handleResult, params);
					$(fac_category).checked = false;
					var y=0;
					for (var j = 0; j < fmarkers.length; j++) {
						var fac_catid = fac_category + j;

						if($(fac_catid)) {
							$(fac_catid).style.display = "none";
							}
						if(fmarkers[j].category == fac_category) {			
							fmarkers[j].hide();
							}
						}
					}	
				}
			}

		var hidden = <?php 
    print find_hidden();
    ?>
;
		var shown = <?php 
    print find_showing();
    ?>
;
		$('fac_go_button').style.display = 'none';
		$('fac_can_button').style.display = 'none';

		if((x > 0) && (x < fac_curr_cats.length)) {
			$('fac_ALL').style.display = '';
			$('fac_ALL_BUTTON').style.display = '';
			$('fac_NONE').style.display = '';
			$('fac_NONE_BUTTON').style.display = '';
		}
		if(x == 0) {
			$('fac_ALL').style.display = '';
			$('fac_ALL_BUTTON').style.display = '';
			$('fac_NONE').style.display = 'none';
			$('fac_NONE_BUTTON').style.display = 'none';
		}
		if(x == fac_curr_cats.length) {
			$('fac_ALL').style.display = 'none';
			$('fac_ALL_BUTTON').style.display = 'none';
			$('fac_NONE').style.display = '';
			$('fac_NONE_BUTTON').style.display = '';
		}


	}	// end function do_go_button()

	function gfb_handleResult(req) {							// 12/03/10	The persist callback function
		}

// end of facilities show / hide functions

// show hide polygons
	function do_view_bnd() {							// 12/03/10	Show Hide categories, Showing and setting onClick attribute for Next button for category show / hide.
		$('bnd_go_can').style.display = 'inline';
		$('bnd_can_button').style.display = 'inline';
		$('bnd_go_button').style.display = 'inline';
		}

	function bnd_cancel_buttons() {							// 12/03/10	Show Hide categories, Showing and setting onClick attribute for Next button for category show / hide.
		$('bnd_go_can').style.display = 'none';
		$('bnd_can_button').style.display = 'none';
		$('bnd_go_button').style.display = 'none';
		$('BND_ALL').checked = false;
		$('BND_NONE').checked = false;
		}

	function set_bnd_chkbox(control) {
		var bnd_control = control;
		if($(bnd_control).checked == true) {
			$(bnd_control).checked = false;
			} else {
			$(bnd_control).checked = true;
			}
		do_view_bnd();
		}

	function do_go_bnd_button() {							// 12/03/10	Show Hide categories
		var bnd_curr = bound_names;
		if ($('BND_ALL').checked == true) {
			for (var i = 0; i < bnd_curr.length; i++) {
				var bnds = bnd_curr[i];
				var params = "f_n=show_hide_bnds_" +URLEncode(bnds)+ "&v_n=s&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
				var url = "persist2.php";	//	3/15/11
				sendRequest (url, gbb_handleResult, params);
				$(bnds).checked = true;				
				if(boundary[i]) {				
					boundary[i].show();
					}
				}
				$('BND_ALL').checked = false;
				$('BND_ALL').style.display = 'none';
				$('BND_ALL_BUTTON').style.display = 'none';				
				$('BND_NONE').style.display = '';
				$('BND_NONE_BUTTON').style.display = '';				
				$('bnd_go_button').style.display = 'none';
				$('bnd_can_button').style.display = 'none';

		} else if ($('BND_NONE').checked == true) {
			for (var i = 0; i < bnd_curr.length; i++) {
				var bnds = bnd_curr[i];
				var params = "f_n=show_hide_bnds_" +URLEncode(bnds)+ "&v_n=h&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
				var url = "persist2.php";	//	3/15/11
				sendRequest (url, gbb_handleResult, params);	
				$(bnds).checked = false;				
				if(boundary[i]) {				
					boundary[i].hide();
					}
				}
				$('BND_NONE').checked = false;
				$('BND_ALL').style.display = '';
				$('BND_ALL_BUTTON').style.display = '';				
				$('BND_NONE').style.display = 'none';
				$('BND_NONE_BUTTON').style.display = 'none';					
				$('bnd_go_button').style.display = 'none';
				$('bnd_can_button').style.display = 'none';
		} else {
			var x = 0;
			var y = 0;
			for (var i = 0; i < bnd_curr.length; i++) {
				var bnds = bnd_curr[i];
				if ($(bnds) && ($(bnds).checked == true)) {
					x++;
					var params = "f_n=show_hide_bnds_" +URLEncode(bnds)+ "&v_n=s&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
					var url = "persist2.php";	//	3/15/11
					sendRequest (url, gbb_handleResult, params);
					$(bnds).checked = true;		
					if((boundary[i]) && (bound_names.contains(bnds))) {			
						boundary[i].show();
						}
					}
				}
			for (var i = 0; i < bnd_curr.length; i++) {
				var bnds = bnd_curr[i];	
				if ($(bnds) && ($(bnds).checked == false)) {
					y++;
					var params = "f_n=show_hide_bnds_" +URLEncode(bnds)+ "&v_n=h&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
					var url = "persist2.php";	//	3/15/11
					sendRequest (url, gbb_handleResult, params);
					$(bnds).checked = false;
					if((boundary[i]) && (bound_names.contains(bnds))) {			
						boundary[i].hide();
						}
					}
				}	
			}

		var hidden = <?php 
    print find_bnd_hidden();
    ?>
;
		var shown = <?php 
    print find_bnd_showing();
    ?>
;
		$('bnd_go_button').style.display = 'none';
		$('bnd_can_button').style.display = 'none';

		if((x > 0) && (x < bnd_curr.length)) {
			$('BND_ALL').style.display = '';
			$('BND_ALL_BUTTON').style.display = '';
			$('BND_NONE').style.display = '';
			$('BND_NONE_BUTTON').style.display = '';
		}
		if(x == 0) {
			$('BND_ALL').style.display = '';
			$('BND_ALL_BUTTON').style.display = '';
			$('BND_NONE').style.display = 'none';
			$('BND_NONE_BUTTON').style.display = 'none';
		}
		if(x == bnd_curr.length) {
			$('BND_ALL').style.display = 'none';
			$('BND_ALL_BUTTON').style.display = 'none';
			$('BND_NONE').style.display = '';
			$('BND_NONE_BUTTON').style.display = '';
		}

	}	// end function do_go_bnd_button()

	function set_bnds() {			//	12/03/10 - checks current session values and sets checkboxes and view states for hide and show, revised 3/15/11.
		var bnd_curr = <?php 
    echo json_encode(get_bnd_session());
    ?>
;
		var bnd_names_curr = <?php 
    echo json_encode(get_bnd_session_names());
    ?>
;
		var fac_hidden = <?php 
    print find_bnd_hidden();
    ?>
;
		var fac_shown = <?php 
    print find_bnd_showing();
    ?>
;
		if(fac_hidden!=0) {
			if($('BND_ALL')) { $('BND_ALL').style.display = '';}
			if($('BND_ALL_BUTTON')) { $('BND_ALL_BUTTON').style.display = '';}
			if($('BND_ALL')) { $('BND_ALL').checked = false;}	
		} else {			
			if($('BND_ALL')) { $('BND_ALL').style.display = 'none';}
			if($('BND_ALL_BUTTON')) { $('BND_ALL_BUTTON').style.display = 'none';}
			if($('BND_ALL')) { $('BND_ALL').checked = false;}
		}
		if(fac_shown!=0) {
			if($('BND_NONE')) { $('BND_NONE').style.display = '';}
			if($('BND_NONE_BUTTON')) { $('BND_NONE_BUTTON').style.display = '';}
			if($('BND_NONE')) { $('BND_NONE').checked = false;}
		} else {
			if($('BND_NONE')) { $('BND_NONE').style.display = 'none';}
			if($('BND_NONE_BUTTON')) { $('BND_NONE_BUTTON').style.display = 'none';}
			if($('BND_NONE')) { $('BND_NONE').checked = false;}
		}
		for (var i = 0; i < bnd_curr.length; i++) {
			var bnds = bnd_curr[i];
			var bnd_nm = bnd_names_curr[i];
			if(bnds == "s") {
				boundary[i].show();
				$(bnd_nm).checked = true;
				} else {
				boundary[i].hide();
				$(bnd_nm).checked = false;
				}				
			}
		}
		
	function gbb_handleResult(req) {							// 12/03/10	The persist callback function
		}

// end of functions for showing and hiding boundaries
var show_cont;
var hide_cont;	
var divarea;	

	function hideDiv(div_area, hide_cont, show_cont) {	//	3/15/11
		if (div_area == "buttons_sh") {
			var controlarea = "hide_controls";
			}
		if (div_area == "resp_list_sh") {
			var controlarea = "resp_list";
			}
		if (div_area == "facs_list_sh") {
			var controlarea = "facs_list";
			}
		if (div_area == "incs_list_sh") {
			var controlarea = "incs_list";
			}
		if (div_area == "region_boxes") {
			var controlarea = "region_boxes";
			}			
		var divarea = div_area 
		var hide_cont = hide_cont 
		var show_cont = show_cont 
		if($(divarea)) {
			$(divarea).style.display = 'none';
			$(hide_cont).style.display = 'none';
			$(show_cont).style.display = '';
			} 
		var params = "f_n=" +controlarea+ "&v_n=h&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";
		var url = "persist2.php";
		sendRequest (url, gb_handleResult, params);			
		} 

	function showDiv(div_area, hide_cont, show_cont) {	//	3/15/11
		if (div_area == "buttons_sh") {
			var controlarea = "hide_controls";
			}
		if (div_area == "resp_list_sh") {
			var controlarea = "resp_list";
			}
		if (div_area == "facs_list_sh") {
			var controlarea = "facs_list";
			}
		if (div_area == "incs_list_sh") {
			var controlarea = "incs_list";
			}
		if (div_area == "region_boxes") {
			var controlarea = "region_boxes";
			}				
		var divarea = div_area
		var hide_cont = hide_cont 
		var show_cont = show_cont 
		if($(divarea)) {
			$(divarea).style.display = '';
			$(hide_cont).style.display = '';
			$(show_cont).style.display = 'none';
			}
		var params = "f_n=" +controlarea+ "&v_n=s&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";
		var url = "persist2.php";
		sendRequest (url, gb_handleResult, params);					
		} 

	function show_All() {						// 8/7/09 Revised function to correct incorrect display, 12/03/10, revised to remove units show and hide from this function
		for (var i = 0; i < gmarkers.length; i++) {
			if (gmarkers[i]) {
				if (gmarkers[i].category == "Incident") {
				gmarkers[i].show();
				}
				}
			} 	// end for ()
		$("show_all_icon").style.display = "none";
		$("incidents").style.display = "inline-block";
		}			// end function

	var starting = false;
	
	function checkArray(form, arrayName)	{	//	5/3/11
		var retval = new Array();
		for(var i=0; i < form.elements.length; i++) {
			var el = form.elements[i];
			if(el.type == "checkbox" && el.name == arrayName && el.checked) {
				retval.push(el.value);
			}
		}
	return retval;
	}
	
	function checkForm(form)	{	//	5/3/11
		var errmsg="";
		var itemsChecked = checkArray(form, "frm_group[]");
		if(itemsChecked.length > 0) {
			var params = "f_n=viewed_groups&v_n=" +itemsChecked+ "&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
			var url = "persist3.php";	//	3/15/11	
			sendRequest (url, fvg_handleResult, params);				
//			form.submit();
		} else {
			errmsg+= "\tYou cannot Hide all the regions\n";
			if (errmsg!="") {
				alert ("Please correct the following and re-submit:\n\n" + errmsg);
				return false;
			}
		}
	}
	
	function fvg_handleResult(req) {	// 6/10/11	The persist callback function for viewed groups.
		document.region_form.submit();
		}
		
	function form_validate(theForm) {	//	5/3/11
//		alert("Validating");
		checkForm(theForm);
		}				// end function validate(theForm)	

	function do_mail_fac_win(id) {			// Facility email 9/22/09
		if(starting) {return;}					
		starting=true;	
		var url = "do_fac_mail.php?fac_id=" + id;	
		newwindow_in=window.open (url, 'Email_Window',  'titlebar, resizable=1, scrollbars, height=300,width=600,status=0,toolbar=0,menubar=0,location=0, left=50,top=150,screenX=100,screenY=300');
		if (isNull(newwindow_in)) {
			alert ("This requires popups to be enabled. Please adjust your browser options.");
			return;
			}
		newwindow_in.focus();
		starting = false;
		}

	function do_sel_update (in_unit, in_val) {							// 12/17/09
		to_server(in_unit, in_val);
		}

	function do_sel_update_fac (in_unit, in_val) {							// 3/15/11
		to_server_fac(in_unit, in_val);
		}

	function do_sidebar_unit (instr, id, sym, myclass, tip_str, category) {		
							// sidebar_string, sidebar_index, row_class, icon_info, mouseover_str - 1/7/09
//		alert ("1196 id: " + id);							
//		alert ("1197 sym: " + sym);							
		var tr_id = category + id;
		if (isNull(tip_str)) {
			side_bar_html += "<TR ID = '" + tr_id + "' CLASS='" + colors[(id)%2] +"'><TD CLASS='" + myclass + "' onClick = myclick(" + id + "); ALIGN = 'left'>" + (sym) + "</TD>"+ instr +"</TR>\n";		// 2/6/10 moved onclick to TD
			}
		else {
			side_bar_html += "<TR ID =  '" + tr_id + "' onMouseover=\"Tip('" + tip_str + "');\" onmouseout=\"UnTip();\" CLASS='" + colors[(id)%2] +"'><TD CLASS='" + myclass + "' onClick = myclick(" + id + "); ALIGN = 'left'>" + (sym) + "</TD>"+ instr +"</TR>\n";		// 1/3/10 added tip param		
			}
		}		// end function do sidebar_unit ()

<?php 
    // 5/17/10
    $use_quick = (int) $func == 0 || (int) $func == 10 ? FALSE : TRUE;
    //	11/29/10
    if ($use_quick) {
        $js_func = "open_tick_window";
    } elseif ($quick && !is_guest()) {
        $js_func = "myclick_ed_tick";
    } else {
        $js_func = "myclick";
    }
    ?>
	
	function open_tick_window (id) {				// 5/2/10
		var url = "single.php?ticket_id="+ id;
		var tickWindow = window.open(url, 'mailWindow', 'resizable=1, scrollbars, height=600, width=600, left=100,top=100,screenX=100,screenY=100');
		tickWindow.focus();
		}	
		
	function do_patient(id) {			// patient edit 6/23/11
		if(starting) {return;}					
		starting=true;	
		var url = "patient_w.php?action=list&ticket_id=" + id;	
		newwindow=window.open (url, 'Patient_Window', 'titlebar, resizable=1, scrollbars, height=300,width=550,status=0,toolbar=0,menubar=0,location=0, left=50,top=150,screenX=50,screenY=150');
		if (isNull(newwindow)) {
			alert ("This requires popups to be enabled. Please adjust your browser options.");
			return;
			}
		newwindow.focus();
		starting = false;
		}

	function myclick(id) {					// Responds to sidebar click, then triggers listener above -  note [i]
		GEvent.trigger(gmarkers[id], "click");
		location.href = "#top";
		}

	function do_sidebar (instr, id, sym, myclass, tip_str) {		// sidebar_string, sidebar_index, row_class, icon_info, mouseover_str - 1/7/09
		var tr_id = tr_id_fixed_part + id;
		side_bar_html += "<TR onClick = 'myclick(" + id + ");' ID =  '" + tr_id + "' onMouseover=\"Tip('" + tip_str + "');\" onmouseout=\"UnTip();\" CLASS='" + colors[id%2] +"'>";
		side_bar_html += "<TD CLASS='" + myclass + "' ALIGN = 'left'>" + (sym) + "</TD>"+ instr +"</TR>\n";		// 1/3/10 added tip param		
		}		// end function do sidebar ()

	function do_sidebar_t_ed (instr, line_no, rcd_id, letter, tip_str) {		// ticket edit, tip str added 1/3/10
		side_bar_html += "<TR onMouseover=\"Tip('" + tip_str.replace("'", "") + "');\" onmouseout=\"UnTip();\" CLASS='" + colors[(line_no)%2] +"'>";		
		side_bar_html += "<TD CLASS='td_data'>" + letter + "</TD>" + instr +"</TR>\n";		// 2/13/09, 10/29/09 removed period
		}

	function do_sidebar_u_iw (instr, id, sym, myclass) {						// constructs unit incident sidebar row - 1/7/09
		var tr_id = tr_id_fixed_part + id;
		side_bar_html += "<TR ID = '" + tr_id + "' CLASS='" + colors[id%2] +"' onClick = myclick(" + id + ");><TD CLASS='" + myclass + "'>" + (sym) + "</TD>"+ instr +"</TR>\n";		// 10/30/09 removed period
		}		// end function do sidebar ()

	function myclick_ed_tick(id) {				// Responds to sidebar click - edit ticket data
<?php 
    $the_action = is_guest() ? "main.php" : $_SESSION['editfile'];
    2 / 27 / 10;
    ?>
	
		document.tick_form.id.value=id;			// 11/27/09
		document.tick_form.action='<?php 
    print $the_action;
    ?>
';			// 11/27/09
		document.tick_form.submit();
		}

	function do_sidebar_u_ed (sidebar, line_no, on_click, letter, tip, category) {					// unit edit - letter = icon str
//		alert ("1251 line_no: " + line_no);							
//		alert ("1252 letter: " + letter);							
		var tr_id = category + line_no;
		side_bar_html += "<TR ID = '" + tr_id + "'  CLASS='" + colors[(line_no+1)%2] +"'>";
		side_bar_html += "<TD onClick = '" + on_click+ "' CLASS='td_data'>" + letter + "</TD>" + sidebar +"</TR>\n";		// 2/13/09, 10/29/09 removed period
		}

	function myclick_nm(id) {				// Responds to sidebar click - view responder data
		document.unit_form.id.value=id;	// 11/27/09
		if (quick) {
			document.unit_form.edit.value="true";
			}
		else {
			document.unit_form.view.value="true";
			}
		document.unit_form.submit();
		}

	function do_sidebar_fac_ed (fac_instr, fac_id, fac_sym, myclass, fac_type) {					// constructs facilities sidebar row 9/22/09
		var fac_type_id = fac_type + fac_id;
		side_bar_html += "<TR ID = '" + fac_type_id + "' CLASS='" + colors[(fac_id+1)%2] +"'>";
		side_bar_html += "<TD width='5%' CLASS='" + myclass + "' onClick = fac_click_ed(" + fac_id + ");><B>" + (fac_sym) + "</B></TD>";
		side_bar_html += fac_instr +"</TR>\n";		// 10/30/09 removed period
		location.href = "#top";
		}		// end function do sidebar_fac_ed ()

	function do_sidebar_fac_iw (fac_instr, fac_id, fac_sym, myclass, fac_type) {					// constructs facilities sidebar row 9/22/09
		var fac_type_id = fac_type + fac_id;
		side_bar_html += "<TR ID = '" + fac_type_id + "' CLASS='" + colors[(fac_id+1)%2] +"' WIDTH = '100%';>"
		side_bar_html += "<TD width='5%' CLASS='" + myclass + "'><B>" + (fac_sym) + "</B></TD>";
		side_bar_html += fac_instr +"</TR>\n";		// 10/30/09 removed period
		location.href = "#top";
		}		// end function do sidebar_fac_iw ()

	function fac_click_iw(fac_id) {						// Responds to facilities sidebar click, triggers listener above 9/22/09
		GEvent.trigger(fmarkers[fac_id], "click");
		}

	function fac_click_ed(id) {							// Responds to facility sidebar click - edit data
		document.facy_form_ed.id.value=id;					// 11/27/09
		document.facy_form_ed.submit();
		}

	var curr_loc;	//	3/15/11
	var currzoom;	//	3/15/11
	var currbnds;	//	3/15/11
	
// Creates marker and sets up click event infowindow 10/21/09 added stat to hide unavailable units, 12/03/10 added category. 3/19/11 added tip param
	
	function createMarker(point, tabs, color, stat, id, sym, category, region, tip) {		// 3/19/11
//		alert(sym);
		var group = category || 0;			// if absent from call
		var region = region || 0;
		var tip_val = tip || "";		// if absent from call
		points = true;
		var myIcon = new GIcon(baseIcon);
		
		var origin = ((sym.length)>3)? (sym.length)-3: 0;			// pick low-order three chars 3/22/11
		var iconStr = sym.substring(origin);
		
		var icon_url = "./our_icons/gen_icon.php?blank=" + escape(icons[color]) + "&text=" + iconStr;				// 1/6/09
//		var icon_url = "./our_icons/gen_icon.php?blank=" + escape(icons[color]) + "&text=" + sym;				// 1/6/09
		myIcon.image = icon_url;

		var marker = new GMarker(point,{icon:myIcon, title: tip_val});										// 3/19/11
		marker.id = color;				// for hide/unhide
		marker.category = category;		// 12/03/10 for show / hide by status
		marker.region = region;		// 12/03/10 for show / hide by status		
		marker.stat = stat;				// 10/21/09

		GEvent.addListener(marker, "click", function() {					// here for both side bar and icon click
			map.closeInfoWindow();
			which = id;
			gmarkers[which].hide();
			marker.openInfoWindowTabsHtml(infoTabs[id]);
			curr_loc = point;	//	3/15/11
			currbnds = map.getBounds();	//	3/15/11
			currzoom = map.getBoundsZoomLevel(currbnds);	//	3/15/11
			setTimeout(function() {											// wait for rendering complete - 11/6/08
				if ($("detailmap")) {				// 10/9/08
					var dMapDiv = $("detailmap");
					var detailmap = new GMap2(dMapDiv);
					detailmap.addControl(new GSmallMapControl());
					detailmap.setCenter(point, 17);  						// larger # = closer
					detailmap.addOverlay(marker);
					}
				else {
//					alert($("detailmap"));
					}
				},3000);				// end setTimeout(...)

			});
		gmarkers[id] = marker;							// marker to array for side_bar click function
		gmarkers[id]['x'] = "y";							// ????
		infoTabs[id] = tabs;							// tabs to array
		if (!(map_is_fixed)){
			bounds.extend(point);
			}
		return marker;
		}				// end function create Marker()

	function test(location) { 	//	3/15/11
 		alert(location) 
		}


	function createdummyMarker(point, tabs, id) {					// Creates dummymarker and sets up click event infowindow for "no maps" added tickets and units. 7/28/10 
		points = true;
		var icon = new GIcon(baseIcon);
		var icon_url = "./our_icons/question1.png";				// 7/28/10
		icon.image = icon_url;

		var dummymarker = new GMarker(point, icon);

		GEvent.addListener(dummymarker, "click", function() {

			map.closeInfoWindow();
			which = id;
			gmarkers[which].hide();
			dummymarker.openInfoWindowTabsHtml(infoTabs[id]);

			setTimeout(function() {
				if ($("detailmap")) {
					var dMapDiv = $("detailmap");
					var detailmap = new GMap2(dMapDiv);
					detailmap.addControl(new GSmallMapControl());
					detailmap.setCenter(point, 17);
					detailmap.addOverlay(dummymarker);
					}
				else {
//					alert($("detailmap"));
					}
				},3000);				// end setTimeout(...)

			});
		gmarkers[id] = dummymarker;							// marker to array for side_bar click function
		infoTabs[id] = tabs;							// tabs to array
		if (!(map_is_fixed)){
			bounds.extend(point);
			}
		return dummymarker;
		}				// end function create dummyMarker()
		
	var the_grid;
	var grid = false;
	function doGrid() {
		if (grid) {
			map.removeOverlay(the_grid);
			}
		else {
			the_grid = new LatLonGraticule();
			map.addOverlay(the_grid);
			}
		grid = !grid;
		}			// end function doGrid

    var trafficInfo = new GTrafficOverlay();
    var toggleState = true;

	function doTraffic() {				// 10/16/08
		if (toggleState) {
	        map.removeOverlay(trafficInfo);
	     	}
		else {
	        map.addOverlay(trafficInfo);
	    	}
        toggleState = !toggleState;			// swap
	    }				// end function doTraffic()


	var icons=[];						// note globals
	icons[0] = 											 4;	// units white
	icons[<?php 
    print $GLOBALS['SEVERITY_NORMAL'];
    ?>
+1] = 1;	// blue
	icons[<?php 
    print $GLOBALS['SEVERITY_MEDIUM'];
    ?>
+1] = 2;	// yellow
	icons[<?php 
    print $GLOBALS['SEVERITY_HIGH'];
    ?>
+1] =  3;	// red
	icons[<?php 
    print $GLOBALS['SEVERITY_HIGH'];
    ?>
+2] =  0;	// black

	var map;
	var center;
	var zoom = <?php 
    echo get_variable('def_zoom');
    ?>
;
	
	var points = false;
<?php 
    $dzf = get_variable('def_zoom_fixed');
    print "\tvar map_is_fixed = ";
    print $dzf == 1 || $dzf == 3 ? "true;\n" : "false;\n";
    $kml_olays = array();
    $dir = "./kml_files";
    if ($dh = @opendir($dir)) {
        // 12/8/10
        $i = 1;
        $temp = explode("/", $_SERVER['REQUEST_URI']);
        $temp[count($temp) - 1] = "kml_files";
        //
        $server_str = "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . implode("/", $temp) . "/";
        while (false !== ($filename = @readdir($dh))) {
            // 12/8/10
            if (!is_dir($filename)) {
                echo "\tvar kml_" . $i . " = new GGeoXml(\"" . $server_str . $filename . "\");\n";
                $kml_olays[] = "map.addOverlay(kml_" . $i . ");";
                $i++;
            }
        }
        // end if ($dh = @opendir($dir))
    }
    ?>

function do_add_note (id) {				// 8/12/09
	var url = "add_note.php?ticket_id="+ id;
	var noteWindow = window.open(url, 'mailWindow', 'resizable=1, scrollbars, height=240, width=600, left=100,top=100,screenX=100,screenY=100');
	noteWindow.focus();
	}

function do_sort_sub(sort_by){				// 6/11/10
	document.sort_form.order.value = sort_by;
	document.sort_form.submit();
	}

function do_fac_sort_sub(sort_by){				// 3/15/11
	document.fac_sort_form.forder.value = sort_by;
	document.fac_sort_form.submit();
	}
	
function do_track(callsign) {		
	if (parent.frames["upper"].logged_in()) {
//		if(starting) {return;}					// 6/6/08
//		starting=true;
		map.closeInfoWindow();
		var width = <?php 
    print get_variable('map_width');
    ?>
+360;
		var spec ="titlebar, resizable=1, scrollbars, height=640,width=" + width + ",status=0,toolbar=0,menubar=0,location=0, left=100,top=300,screenX=100,screenY=300";
		var url = "track_u.php?source="+callsign;

		newwindow=window.open(url, callsign,  spec);
		if (isNull(newwindow)) {
			alert ("Track display requires popups to be enabled. Please adjust your browser options.");
			return;
			}
//		starting = false;
		newwindow.focus();
		}
	}				// end function do track()

function do_popup(id) {					// added 7/9/09
	if (parent.frames["upper"].logged_in()) {
		map.closeInfoWindow();
		var mapWidth = <?php 
    print get_variable('map_width');
    ?>
+32;
		var mapHeight = <?php 
    print get_variable('map_height');
    ?>
+150;		// 3/12/10
		var spec ="titlebar, resizable=1, scrollbars, height=" + mapHeight + ", width=" + mapWidth + ", status=no,toolbar=no,menubar=no,location=0, left=100,top=300,screenX=100,screenY=300";
		var url = "incident_popup.php?id="+id;

		newwindow=window.open(url, id, spec);
		if (isNull(newwindow)) {
			alert ("Popup Incident display requires popups to be enabled. Please adjust your browser options.");
			return;
			}
//		starting = false;
		newwindow.focus();
		}
	}				// end function do popup()

function do_sched_jobs(choice) {		// 11/29/10 - added Scheduled tickets to menu. 12/02/10 Added persistance for the list view
	var params = "f_n=list_type&v_n=" + choice + "&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";					// 3/15/11	flag 1, value h
	var url = "persist2.php";	//	3/15/11
	sendRequest (url, cs_handleResult, params);	// ($to_str, $text, $ticket_id)
	document.to_listtype.func.value=choice;
	}				// end function do_listtype()

function do_curr_jobs(choice) {		// 11/29/10 - added Scheduled tickets to menu. 12/02/10 Added persistance for the list view
	var params = "f_n=list_type&v_n=" + choice + "&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";					// 3/15/11 flag 1, value h
	var url = "persist2.php";	//	3/15/11
	sendRequest (url, cs_handleResult, params);	// ($to_str, $text, $ticket_id)
	document.to_listtype.func.value=choice;
	}				// end function do_listtype()

function do_listtype(choice) {		// 11/29/10 - added Scheduled tickets to menu. 12/02/10 Added persistance for the list view
	var params = "f_n=list_type&v_n=" + choice + "&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";					// 3/15/11 flag 1, value h
	var url = "persist2.php";	//	3/15/11
	sendRequest (url, l_handleResult, params);	// ($to_str, $text, $ticket_id)
	document.to_listtype.func.value=choice;
	show_btns_closed()
	}				// end function do_listtype()
	
function l_handleResult(req) {					// the 'called-back' persist function - nill content for the tickets list type persistance
	}

function cs_handleResult(req) {					// the 'called-back' function for show current or scheduled
	document.to_listtype.submit();	
	}

	var side_bar_html = "<TABLE border=0 CLASS='sidebar' WIDTH = <?php 
    print $col_width;
    ?>
 >";
	var sched_html = "";	//	3/15/11
<?php 
    $query_sched = "SELECT * FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE `status`='{$GLOBALS['STATUS_SCHEDULED']}' AND `booked_date` >= (NOW() + INTERVAL 2 DAY)";
    //	11/29/10
    $result_sched = mysql_query($query_sched) or do_error($query_sched, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    //	11/29/10
    $num_sched = mysql_num_rows($result_sched);
    //	11/29/10
    if ($num_sched != 0 && $func != 10) {
        //	11/29/10
        $scheduled_link = $num_sched >= 2 ? "Scheduled Jobs: " . $num_sched : "Scheduled Jobs: " . $num_sched;
        $order_by = !empty($get_sortby) ? $get_sortby : $_SESSION['sortorder'];
        // use default sort order?
        ?>
		sched_html +="\t\t<SPAN class='scheduled' TITLE='Click link to view a list of scheduled jobs that are not shown on the current situation screen. Scheduled jobs that are due in the next 2 days are shown on the current situation screen and have a * in front of the ID, the date is highlighted and is the scheduled date.' onClick='do_sched_jobs(10);'><u><?php 
        print $scheduled_link;
        ?>
</u></SPAN>\n";	//	3/15/11
<?php 
    }
    //	11/29/10
    if ($num_sched != 0 && $func == 10) {
        //	11/29/10
        ?>
		sched_html +="\t\t<SPAN class='scheduled' TITLE='Click link view current situation screen including scheduled jobs that are due in the next 2 days. Scheduled jobs are shown with a * in front of the ID, the date is highlighted and is the scheduled date.' onClick='do_curr_jobs(0);'>Click to view current situation</SPAN>\n";	//	3/15/11
<?php 
    }
    //	11/29/10
    ?>
	var incs_array = new Array();
	var incs_groups = new Array();		
	var gmarkers = [];
	var fmarkers = [];
	var rowIds = [];		// 3/8/10
	var infoTabs = [];
	var facinfoTabs = [];
	var which;
	var i = 0;			// sidebar/icon index

	map = new GMap2($("map"));		// create the map
	var geocoder = null;
	geocoder = new GClientGeocoder();

<?php 
    $maptype = get_variable('maptype');
    // 08/02/09
    switch ($maptype) {
        case "1":
            break;
        case "2":
            ?>
		map.setMapType(G_SATELLITE_MAP);<?php 
            break;
        case "3":
            ?>
		map.setMapType(G_PHYSICAL_MAP);<?php 
            break;
        case "4":
            ?>
		map.setMapType(G_HYBRID_MAP);<?php 
            break;
        default:
            print "ERROR in " . basename(__FILE__) . " " . __LINE__ . "<BR />";
    }
    ?>

//	map.addControl(new GSmallMapControl());					// 8/25/08
	map.addControl(new GLargeMapControl());
	map.setUIToDefault();										// 8/13/10
	map.addControl(new GMapTypeControl());

	map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);

	mapBounds=new GLatLngBounds(map.getBounds().getSouthWest(), map.getBounds().getNorthEast());		// 4/4/09

	var bounds = new GLatLngBounds();						// create  bounding box
<?php 
    if (get_variable('terrain') == 1) {
        ?>
	map.addMapType(G_PHYSICAL_MAP);
<?php 
    }
    ?>

	map.enableScrollWheelZoom();



// drawCircle(40.847060, -75.216801, 500, add_hash('FF0000'), 20, 0.5, add_hash('FF0000'), 0); //  472


	var baseIcon = new GIcon();
	var defzoom = <?php 
    print get_variable('def_zoom');
    ?>
;	//	3/15/11
	baseIcon.shadow = "./markers/sm_shadow.png";		// ./markers/sm_shadow.png

	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);
	GEvent.addListener(map, "infowindowclose", function() {		// re-center after  move/zoom
		var zoomfactor = -2;	//	3/15/11
		var newzoom = currzoom + zoomfactor;
		base_zoom = map.getZoom();
		if (currzoom > (base_zoom - zoomfactor)) {	//	3/15/11
			map.setCenter(curr_loc, newzoom);
		} else {
			map.setCenter(curr_loc, currzoom);
		}
		map.addOverlay(gmarkers[which]);
		});

	do_landb();				// 8/1/11 - show scribbles
<?php 
    //-----------------------BOUNDARIES STUFF--------------------6/10/11
    ?>
	var thepoint;
	var points = new Array();


	
	GEvent.addListener(map, "click", function(overlay,boundpoint) {
		for (var n = 0; n < boundary.length; n++) {
			if (boundary[n].Contains(boundpoint)) {
				map.openInfoWindowHtml(boundpoint,"This is " + bound_names[n]);
				}
			}
		});	

<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}' ORDER BY `id` ASC;";
    //	6/10/11
    $result = mysql_query($query);
    //	6/10/11
    $a_gp_bounds = array();
    $a_all_boundaries = array();
    $gp_bounds = array();
    $all_boundaries = array();
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        //	6/10/11
        $al_groups[] = $row['group'];
        $query2 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}region` WHERE `id`= '{$row['group']}';";
        //	6/10/11
        $result2 = mysql_query($query2);
        // 4/18/11
        while ($row2 = stripslashes_deep(mysql_fetch_assoc($result2))) {
            //	//	6/10/11
            if ($row2['boundary'] != 0) {
                $a_gp_bounds[] = $row2['boundary'];
                $a_all_boundaries[] = $row2['boundary'];
            }
        }
    }
    if (isset($_SESSION['viewed_groups'])) {
        //	6/10/11
        foreach (explode(",", $_SESSION['viewed_groups']) as $val_vg) {
            $query3 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}region` WHERE `id`= '{$val_vg}';";
            $result3 = mysql_query($query3);
            //	6/10/11
            while ($row3 = stripslashes_deep(mysql_fetch_assoc($result3))) {
                if ($row3['boundary'] != 0) {
                    $gp_bounds[] = $row3['boundary'];
                    $all_boundaries[] = $row3['boundary'];
                }
            }
        }
    } else {
        $gp_bounds = $a_gp_bounds;
        $all_boundaries = $a_all_boundaries;
    }
    foreach ($gp_bounds as $value) {
        //	6/10/11
        ?>
		var points = new Array();
<?php 
        if ($value != 0) {
            $query_bn = "SELECT * FROM `{$GLOBALS['mysql_prefix']}mmarkup` WHERE `id`='{$value}' LIMIT 1";
            $result_bn = mysql_query($query_bn) or do_error($query_bn, mysql_error(), basename(__FILE__), __LINE__);
            $row_bn = stripslashes_deep(mysql_fetch_assoc($result_bn));
            extract($row_bn);
            $bn_name = $row_bn['line_name'];
            $points = explode(";", $line_data);
            for ($i = 0; $i < count($points); $i++) {
                $coords = explode(",", $points[$i]);
                ?>
				thepoint = new GLatLng(parseFloat(<?php 
                print $coords[0];
                ?>
), parseFloat(<?php 
                print $coords[1];
                ?>
));
				points.push(thepoint);
<?php 
            }
            // end for ($i = 0 ... )
            ?>

<?php 
            if (intval($filled) == 1) {
                //	6/10/11
                ?>
			var polyline = new GPolygon(points, add_hash("<?php 
                print $line_color;
                ?>
"), <?php 
                print $line_width;
                ?>
, <?php 
                print $line_opacity;
                ?>
, add_hash("<?php 
                print $fill_color;
                ?>
"), <?php 
                print $fill_opacity;
                ?>
, {clickable:false, id:"region"});
			boundary.push(polyline);
			bound_names.push("<?php 
                print $bn_name;
                ?>
"); 
			<?php 
            } else {
                ?>
			var polyline = new GPolygon(points, add_hash("<?php 
                print $line_color;
                ?>
"), <?php 
                print $line_width;
                ?>
, <?php 
                print $line_opacity;
                ?>
, , 0, {clickable:false, id:region});
			boundary.push(polyline);
			bound_names.push("<?php 
                print $bn_name;
                ?>
"); 
<?php 
            }
            ?>
			map.addOverlay(polyline);
<?php 
        }
    }
    //-------------------------END OF BOUNDARIES STUFF-------------------------
    $order_by = !empty($get_sortby) ? $get_sortby : $_SESSION['sortorder'];
    // use default sort order?
    //fix limits according to setting "ticket_per_page"
    $limit = "";
    if ($_SESSION['ticket_per_page'] && check_for_rows("SELECT id FROM `{$GLOBALS['mysql_prefix']}ticket`") > $_SESSION['ticket_per_page']) {
        if ($_GET['offset']) {
            $limit = "LIMIT {$_GET['offset']},{$_SESSION['ticket_per_page']}";
        } else {
            $limit = "LIMIT 0,{$_SESSION['ticket_per_page']}";
        }
    }
    $restrict_ticket = get_variable('restrict_user_tickets') && !is_administrator() ? " AND owner={$_SESSION['user_id']}" : "";
    $time_back = mysql_format_date(time() - intval(get_variable('delta_mins')) * 60 - $cwi * 3600);
    if (isset($_SESSION['viewed_groups'])) {
        //	6/10/11
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    }
    if (!isset($curr_viewed)) {
        //	6/10/11
        $x = 0;
        $where2 = "AND (";
        foreach ($al_groups as $grp) {
            $where3 = count($al_groups) > $x + 1 ? " OR " : ")";
            $where2 .= "`{$GLOBALS['mysql_prefix']}allocates`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    } else {
        $x = 0;
        $where2 = "AND (";
        foreach ($curr_viewed as $grp) {
            $where3 = count($curr_viewed) > $x + 1 ? " OR " : ")";
            $where2 .= "`{$GLOBALS['mysql_prefix']}allocates`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    }
    $where2 .= "AND `{$GLOBALS['mysql_prefix']}allocates`.`type` = 1";
    switch ($func) {
        case 0:
            $where = "WHERE (`{$GLOBALS['mysql_prefix']}ticket`.`status`='{$GLOBALS['STATUS_OPEN']}' OR (`{$GLOBALS['mysql_prefix']}ticket`.`status`='{$GLOBALS['STATUS_SCHEDULED']}' AND `{$GLOBALS['mysql_prefix']}ticket`.`booked_date` <= (NOW() + INTERVAL 2 DAY)) OR \n\t\t\t\t(`{$GLOBALS['mysql_prefix']}ticket`.`status`='{$GLOBALS['STATUS_CLOSED']}'  AND `{$GLOBALS['mysql_prefix']}ticket`.`problemend` >= '{$time_back}')){$where2}";
            //	11/29/10, 4/18/11, 4/18/11
            break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
            $the_start = get_start($func);
            // mysql timestamp format
            $the_end = get_end($func);
            $where = " WHERE (`{$GLOBALS['mysql_prefix']}ticket`.`status`='{$GLOBALS['STATUS_CLOSED']}' AND `{$GLOBALS['mysql_prefix']}ticket`.`problemend` BETWEEN '{$the_start}' AND '{$the_end}') {$where2} ";
            //	4/18/11, 4/18/11
            break;
        case 10:
            $where = "WHERE (`{$GLOBALS['mysql_prefix']}ticket`.`status`='{$GLOBALS['STATUS_SCHEDULED']}' AND `{$GLOBALS['mysql_prefix']}ticket`.`booked_date` >= (NOW() + INTERVAL 2 DAY)) {$where2}";
            //	11/29/10, 4/18/11, 4/18/11
            break;
        default:
            print "error - error - error - error " . __LINE__;
    }
    // end switch($func)
    if ($sort_by_field && $sort_value) {
        //sort by field?
        $query = "SELECT *,UNIX_TIMESTAMP(problemstart) AS problemstart,UNIX_TIMESTAMP(problemend) AS problemend,\n\t\t\tUNIX_TIMESTAMP(date) AS date,UNIX_TIMESTAMP(updated) AS updated, in_types.type AS `type`, in_types.id AS `t_id` \n\t\t\tFROM `{$GLOBALS['mysql_prefix']}allocates`\n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` ON `{$GLOBALS['mysql_prefix']}allocates`.`resource_id`=`{$GLOBALS['mysql_prefix']}ticket`.`id` \t\t\t\n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}in_types` ON `{$GLOBALS['mysql_prefix']}ticket`.`in_types_id`=`{$GLOBALS['mysql_prefix']}in_types`.`in_types.id` \n\t\t\tWHERE {$sort_by_field}='{$sort_value}' {$restrict_ticket} AND `{$GLOBALS['mysql_prefix']}allocates`.`type` = 1 ORDER BY {$order_by}";
    } else {
        // 2/2/09, 8/12/09, updated 4/18/11 to support regional operation
        $query = "SELECT *,UNIX_TIMESTAMP(problemstart) AS problemstart,\n\t\t\tUNIX_TIMESTAMP(problemend) AS problemend,\n\t\t\tUNIX_TIMESTAMP(booked_date) AS booked_date,\t\n\t\t\tUNIX_TIMESTAMP(date) AS date, \n\t\t\t(`{$GLOBALS['mysql_prefix']}ticket`.`street`) AS ticket_street, \n\t\t\t(`{$GLOBALS['mysql_prefix']}ticket`.`state`) AS ticket_city, \n\t\t\t(`{$GLOBALS['mysql_prefix']}ticket`.`city`) AS ticket_state,\n\t\t\tUNIX_TIMESTAMP(`{$GLOBALS['mysql_prefix']}ticket`.updated) AS updated,\n\t\t\t`{$GLOBALS['mysql_prefix']}ticket`.`id` AS `tick_id`,\n\t\t\t`{$GLOBALS['mysql_prefix']}in_types`.type AS `type`, \n\t\t\t`{$GLOBALS['mysql_prefix']}in_types`.`id` AS `t_id`,\n\t\t\t`{$GLOBALS['mysql_prefix']}ticket`.`description` AS `tick_descr`, \n\t\t\t`{$GLOBALS['mysql_prefix']}ticket`.lat AS `lat`,\n\t\t\t`{$GLOBALS['mysql_prefix']}ticket`.lng AS `lng`, \n\t\t\t`{$GLOBALS['mysql_prefix']}facilities`.lat AS `fac_lat`,\n\t\t\t`{$GLOBALS['mysql_prefix']}facilities`.lng AS `fac_lng`, \n\t\t\t`{$GLOBALS['mysql_prefix']}facilities`.`name` AS `fac_name`,\n\t\t\t(SELECT  COUNT(*) as numfound FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\t\t\tWHERE `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id` = `{$GLOBALS['mysql_prefix']}ticket`.`id`  \n\t\t\t\tAND `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' ) \n\t\t\t\tAS `units_assigned`\t\t\t\n\t\t\tFROM `{$GLOBALS['mysql_prefix']}ticket` \n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` \n\t\t\t\tON `{$GLOBALS['mysql_prefix']}ticket`.id=`{$GLOBALS['mysql_prefix']}allocates`.`resource_id`\t\t\t\n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}in_types` \n\t\t\t\tON `{$GLOBALS['mysql_prefix']}ticket`.in_types_id=`{$GLOBALS['mysql_prefix']}in_types`.`id` \n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}facilities` \n\t\t\t\tON `{$GLOBALS['mysql_prefix']}ticket`.rec_facility=`{$GLOBALS['mysql_prefix']}facilities`.`id`\n\t\t\t{$where} {$restrict_ticket} \n\t\t\t GROUP BY tick_id ORDER BY `status` DESC, `severity` DESC, `{$GLOBALS['mysql_prefix']}ticket`.`id` ASC\n\t\t\tLIMIT 1000 OFFSET {$my_offset}";
        // 2/2/09, 10/28/09, 2/21/10
        //			print $query;
    }
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $the_offset = isset($_GET['frm_offset']) ? (int) $_GET['frm_offset'] : 0;
    $sb_indx = 0;
    // note zero base!
    $acts_ary = $pats_ary = array();
    // 6/2/10
    $query = "SELECT `ticket_id`, COUNT(*) AS `the_count` FROM `{$GLOBALS['mysql_prefix']}action` GROUP BY `ticket_id`";
    $result_temp = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row = stripslashes_deep(mysql_fetch_assoc($result_temp))) {
        $acts_ary[$row['ticket_id']] = $row['the_count'];
    }
    $query = "SELECT `ticket_id`, COUNT(*) AS `the_count` FROM `{$GLOBALS['mysql_prefix']}patient` GROUP BY `ticket_id`";
    $result_temp = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row = stripslashes_deep(mysql_fetch_assoc($result_temp))) {
        $pats_ary[$row['ticket_id']] = $row['the_count'];
    }
    $temp = (string) round(microtime(true) - $time, 3);
    //	snap (__LINE__, $temp );
    $line_limit = 25;
    // 5/5/11
    if (mysql_num_rows($result) > $line_limit) {
        ?>
	side_bar_html += get_chg_disp_tr();							// get 'Change display' select list row
<?php 
    }
    ?>
	
	side_bar_html += "<TR class='spacer'><TD CLASS='spacer' COLSPAN=99>&nbsp;</TD></TR>";	//	3/15/11
	side_bar_html += "<TR class='even'><TH colspan=99 align='center'>Click/Mouse-over for information</TH></TR>";	//	3/15/11
	side_bar_html += "<TR class='odd'><TD></TD><TD align='left' COLSPAN=2><B><?php 
    print $incident;
    ?>
</B></TD><TD align='left'><B><?php 
    print $nature;
    ?>
</B></TD><TD align='left'><B>&nbsp;Addr</B></TD><TD align='left'><B>P</B></TD><TD align='left'><B>A</B></TD><TD align='left'><B>U</B></TD><TD align='left'><B>&nbsp;&nbsp;As of</B></TD></TR>";

<?php 
    // ===========================  begin major while() for incidents ==========
    $temp = (string) round(microtime(true) - $time, 3);
    $use_quick = (int) $func == 0 || (int) $func == 10 ? FALSE : TRUE;
    //	11/29/10
    if ($use_quick) {
        $js_func = "open_tick_window";
    } elseif ($quick && !is_guest()) {
        $js_func = "myclick_ed_tick";
    } else {
        $js_func = "myclick";
    }
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // 7/7/10
        $tick_gps = get_allocates(1, $row['tick_id']);
        //	6/10/11
        //		dump($tick_gps);
        $grp_names = "Groups Assigned: ";
        //	6/10/11
        $y = 0;
        //	6/10/11
        foreach ($tick_gps as $value) {
            //	6/10/11
            $counter = count($tick_gps) > $y + 1 ? ", " : "";
            $grp_names .= get_groupname($value);
            $grp_names .= $counter;
            $y++;
        }
        $onclick_str = "onClick = '{$js_func}({$row['tick_id']});'";
        // onClick = to_wherever(999);  -6/23/11
        /*
        		dump(__LINE__);
        		dump($onclick_str);
        		dump($pat_onclick_str);
        */
        $by_severity[$row['severity']]++;
        // 5/2/10
        if ($func > 0) {
            // closed? - 5/16/10
            $onclick = " open_tick_window({$row['tick_id']})";
        } else {
            $onclick = $quick ? " myclick_ed_tick({$row['tick_id']}) " : "myclick({$sb_indx})";
            // 1/2/10
        }
        if ($do_blink && $row['units_assigned'] == 0 && $row['status'] == $GLOBALS['STATUS_OPEN']) {
            // 4/11/10
            $blinkst = "<blink>";
            $blinkend = "</blink>";
        } else {
            $blinkst = $blinkend = "";
        }
        $tip = str_replace("'", "`", $grp_names . " / " . $row['contact'] . "/" . $row['ticket_street'] . "/" . $row['ticket_city'] . "/" . $row['ticket_state'] . "/" . $row['phone'] . "/" . $row['scope']);
        // tooltip string - 1/3/10
        $sp = $row['status'] == $GLOBALS['STATUS_SCHEDULED'] && $func != 10 ? "*" : "";
        print "\t\tvar scheduled = '{$sp}';\n";
        ?>
		var sym = (<?php 
        print addslashes($sb_indx);
        ?>
+1).toString();						// for sidebar
		var sym2= scheduled + (<?php 
        print addslashes($sb_indx);
        ?>
+1).toString();						// for icon

<?php 
        $the_id = $row['tick_id'];
        // 11/27/09
        if ($row['tick_descr'] == '') {
            $row['tick_descr'] = '[no description]';
        }
        // 8/12/09
        if (get_variable('abbreviate_description')) {
            //do abbreviations on description, affected if neccesary
            if (strlen($row['tick_descr']) > get_variable('abbreviate_description')) {
                $row['tick_descr'] = substr($row['tick_descr'], 0, get_variable('abbreviate_description')) . '...';
            }
        }
        if (get_variable('abbreviate_affected')) {
            if (strlen($row['affected']) > get_variable('abbreviate_affected')) {
                $row['affected'] = substr($row['affected'], 0, get_variable('abbreviate_affected')) . '...';
            }
        }
        switch ($row['severity']) {
            //color tickets by severity
            case $GLOBALS['SEVERITY_MEDIUM']:
                $severityclass = 'severity_medium';
                break;
            case $GLOBALS['SEVERITY_HIGH']:
                $severityclass = 'severity_high';
                break;
            default:
                $severityclass = 'severity_normal';
                break;
        }
        $A = array_key_exists($the_id, $acts_ary) ? $acts_ary[$the_id] : 0;
        // 6/2/10
        $P = array_key_exists($the_id, $pats_ary) ? $pats_ary[$the_id] : 0;
        if ($row['status'] == $GLOBALS['STATUS_CLOSED']) {
            $strike = "<strike>";
            $strikend = "</strike>";
        } else {
            $strike = $strikend = "";
        }
        $address_street = replace_quotes($row['ticket_street']) . " " . replace_quotes($row['ticket_city']);
        $sidebar_line = "<TD ALIGN='left' CLASS='{$severityclass}' {$onclick_str} COLSPAN=2><NOBR>{$strike}" . $sp . replace_quotes(shorten($row['scope'], 20)) . " {$strikend}</NOBR></TD>";
        //10/27/09, 8/2/10
        $sidebar_line .= "<TD ALIGN='left' CLASS='{$severityclass}' {$onclick_str}><NOBR>{$strike}" . shorten($row['type'], 20) . " {$strikend}</NOBR></TD>";
        // 8/2/10
        $sidebar_line .= "<TD ALIGN='left' CLASS='{$severityclass}' {$onclick_str}><NOBR>{$strike}" . replace_quotes(shorten($row['ticket_street'] . ' ' . $row['ticket_city'], 20)) . " {$strikend}</NOBR></TD>";
        // 8/2/10
        if ($P == 0) {
            $sidebar_line .= "<TD></TD>";
        } else {
            $pat_onclick_str = "onClick = 'do_patient({$row['tick_id']});'";
            $sidebar_line .= "<TD CLASS='disp_stat' {$pat_onclick_str}><NOBR><B>{$P}</B></TD>";
        }
        $sidebar_line .= "<TD CLASS='td_data'> " . $A . " </NOBR></TD>";
        $sidebar_line .= "<TD CLASS='td_data'>{$blinkst}{$row['units_assigned']}{$blinkend}</TD>";
        $disp_date = $row['status'] == $GLOBALS['STATUS_SCHEDULED'] ? format_sb_date($row['booked_date']) : format_sb_date($row['updated']);
        // 01/06/11
        $date_hlite = $row['status'] == $GLOBALS['STATUS_SCHEDULED'] ? " class='scheduled'" : "";
        $sidebar_line .= "<TD {$date_hlite}><NOBR> " . $disp_date . "</NOBR></TD>";
        // 01/06/11
        if (my_is_float($row['lat'])) {
            // 6/21/10
            $street = empty($row['ticket_street']) ? "" : replace_quotes($row['ticket_street']) . "<BR/>" . replace_quotes($row['ticket_city']) . " " . replace_quotes($row['ticket_state']);
            $todisp = is_guest() || is_unit() ? "" : "&nbsp;<A HREF='{$_SESSION['routesfile']}?ticket_id={$the_id}'><U>Dispatch</U></A>";
            // 7/27/10
            $rand = $istest ? "&rand=" . chr(rand(65, 90)) : "";
            // 10/21/08
            $tab_1 = "<TABLE CLASS='infowin'  width='{$iw_width}' >";
            $tab_1 .= "<TR CLASS='even'><TD COLSPAN=2 ALIGN='center'><B>{$strike}" . replace_quotes(shorten($row['scope'], 48)) . "{$strikend}</B></TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD ALIGN='left'>As of:</TD><TD ALIGN='left'>" . format_date($row['updated']) . "</TD></TR>";
            if (is_int($row['booked_date'])) {
                $tab_1 .= "<TR CLASS='odd'><TD>Booked Date:</TD><TD ALIGN='left'>" . format_date($row['booked_date']) . "</TD></TR>";
                //10/27/09, 3/15/11
            }
            $tab_1 .= "<TR CLASS='even'><TD ALIGN='left'>Reported by:</TD><TD ALIGN='left'>" . replace_quotes(shorten($row['contact'], 32)) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD ALIGN='left'>Phone:</TD><TD ALIGN='left'>" . format_phone($row['phone']) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='even'><TD ALIGN='left'>Addr:</TD><TD ALIGN='left'>{$address_street}</TD></TR>";
            $end_date = intval($row['problemend']) > 1 ? $row['problemend'] : time() - intval(get_variable('delta_mins')) * 60;
            $elapsed = my_date_diff($row['problemstart'], $end_date);
            // 5/13/10
            $tab_1 .= "<TR CLASS='odd'><TD ALIGN='left'>Status:</TD><TD ALIGN='left'>" . get_status($row['status']) . "&nbsp;&nbsp;&nbsp;({$elapsed})</TD></TR>";
            // 3/27/10
            $tab_1 .= empty($row['fac_name']) ? "" : "<TR CLASS='even'><TD ALIGN='left'>Receiving Facility:</TD><TD ALIGN='left'>" . replace_quotes(shorten($row['fac_name'], 30)) . "</TD></TR>";
            //3/27/10, 3/15/11
            $utm = get_variable('UTM');
            if ($utm == 1) {
                $coords = $row['lat'] . "," . $row['lng'];
                // 8/12/09
                $tab_1 .= "<TR CLASS='even'><TD ALIGN='left'>UTM grid:</TD><TD ALIGN='left'>" . toUTM($coords) . "</TD></TR>";
            }
            $tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'><FONT SIZE='-1'>";
            $tab_1 .= $todisp . "&nbsp;&nbsp;&nbsp;&nbsp;<A HREF='main.php?id=" . $the_id . "'><U>Details</U></A>";
            // 08/8/02
            if (!is_guest()) {
                if (can_edit()) {
                    //8/27/10
                    $tab_1 .= "&nbsp;&nbsp;&nbsp;&nbsp;<A HREF='{$_SESSION['editfile']}?id=" . $the_id . $rand . "'><U>Edit</U></A>";
                }
                if (!is_closed($the_id) && !is_unit()) {
                    // 3/3/11
                    $tab_1 .= "&nbsp;&nbsp;&nbsp;&nbsp;<A HREF='#' onClick = do_close_tick('" . $the_id . "');><U>" . get_text("Close incident") . " </U></A><BR /><BR /> ";
                    // 3/3/11
                }
                $tab_1 .= "&nbsp;&nbsp;&nbsp;&nbsp;<SPAN onClick = do_popup('" . $the_id . "');><FONT COLOR='blue'><B><U>Popup</B></U></FONT></SPAN>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                // 7/7/09
                $tab_1 .= "<SPAN onClick = 'do_add_note (" . $the_id . ");'><FONT COLOR='blue'><B><U>Add note</B></U></FONT></SPAN><BR /><BR />";
                // 7/7/09
                if (can_edit()) {
                    //8/27/10
                    $tab_1 .= "<A HREF='patient.php?ticket_id=" . $the_id . $rand . "'><U>Add {$patient}</U></A>&nbsp;&nbsp;&nbsp;&nbsp;";
                    // 7/9/09
                    $tab_1 .= "<A HREF='action.php?ticket_id=" . $the_id . $rand . "'><U>Add Action</U></A>";
                }
            }
            $tab_1 .= "</FONT></TD></TR></TABLE>";
            // 11/6/08
            $tab_2 = "<TABLE CLASS='infowin'  width='{$iw_width}' >";
            // 8/12/09
            $tab_2 .= "<TR CLASS='even'>\t<TD ALIGN='left'>Description:</TD><TD ALIGN='left'>" . replace_quotes(shorten(str_replace($eols, " ", $row['tick_descr']), 48)) . "</TD></TR>";
            // str_replace("\r\n", " ", $my_string)
            $tab_2 .= "<TR CLASS='odd'>\t\t<TD ALIGN='left'>{$disposition}:</TD><TD ALIGN='left'>" . shorten(replace_quotes($row['comments']), 48) . "</TD></TR>";
            // 8/13/09, 3/15/11
            $tab_2 .= "<TR CLASS='even'>\t<TD ALIGN='left'>911 contact:</TD><TD ALIGN='left'>" . shorten($row['nine_one_one'], 48) . "</TD></TR>";
            // 6/26/10
            $locale = get_variable('locale');
            // 08/03/09
            switch ($locale) {
                case "0":
                    $tab_2 .= "<TR CLASS='odd'>\t<TD ALIGN='left'>USNG:</TD><TD ALIGN='left'>" . LLtoUSNG($row['lat'], $row['lng']) . "</TD></TR>";
                    // 8/23/08, 10/15/08, 8/3/09
                    break;
                case "1":
                    $tab_2 .= "<TR CLASS='odd'>\t<TD ALIGN='left'>OSGB:</TD><TD ALIGN='left'>" . LLtoOSGB($row['lat'], $row['lng']) . "</TD></TR>";
                    // 8/23/08, 10/15/08, 8/3/09
                    break;
                case "2":
                    $coords = $row['lat'] . "," . $row['lng'];
                    // 8/12/09
                    $tab_2 .= "<TR CLASS='odd'>\t<TD ALIGN='left'>UTM:</TD><TD ALIGN='left'>" . toUTM($coords) . "</TD></TR>";
                    // 8/23/08, 10/15/08, 8/3/09
                    break;
                default:
                    print "ERROR in " . basename(__FILE__) . " " . __LINE__ . "<BR />";
            }
            $tab_2 .= "<TR>\t\t\t\t\t<TD COLSPAN=2 ALIGN='left'>" . show_assigns(0, $the_id) . "</TD></TR>";
            $tab_2 .= "</TABLE>";
            // 11/6/08. 3/15/11
            ?>
			var myinfoTabs = [
				new GInfoWindowTab("<?php 
            print nl2brr(shorten($row['scope'], 12));
            ?>
", "<?php 
            print $tab_1;
            ?>
"),
				new GInfoWindowTab("More ..", "<?php 
            print str_replace($eols, " ", $tab_2);
            ?>
"),
				new GInfoWindowTab("Zoom", "<div id='detailmap' class='detailmap'></div>")
				];
		
<?php 
            if ($row['lat'] == "0.999999" && $row['lng'] == "0.999999") {
                // check for lat and lng values set in no maps state 7/28/10
                ?>
			
				var point = new GLatLng(<?php 
                print get_variable('def_lat');
                ?>
, <?php 
                print get_variable('def_lng');
                ?>
);	// for each ticket
				if (!(map_is_fixed)){																// 4/3/09
					bounds.extend(point);
					}
	
				var dummymarker = createdummyMarker(point, myinfoTabs, <?php 
                print $sb_indx;
                ?>
);	// (point,tabs, id) - plots dummy icon in default position for tickets added in no maps operation 7/28/10
				map.addOverlay(dummymarker);
				var the_class = ((map_is_fixed) && (!(mapBounds.containsLatLng(point))))? "emph" : "td_label";	
<?php 
            } else {
                ?>
			var point = new GLatLng(<?php 
                print $row['lat'];
                ?>
, <?php 
                print $row['lng'];
                ?>
);	// for each ticket
			if (!(map_is_fixed)){																// 4/3/09
				bounds.extend(point);
				}
			var category = "Incident";
			var region = "<?php 
                print get_first_group(1, $row['tick_id']);
                ?>
";
			var tip_str = "<?php 
                print $tip;
                ?>
";  				// 3/19/11
			var marker = createMarker(point, myinfoTabs,<?php 
                print $row['severity'] + 1;
                ?>
, 0, <?php 
                print $sb_indx;
                ?>
, sym2, category, region, tip_str);		// 3/19/11
			
										// (point,tabs, color, id, sym) - 1/6/09, 10/21/09 added 0 for stat display to avoid conflicts with unit marker hide by unavailable status
			map.addOverlay(marker);
			var the_class = ((map_is_fixed) && (!(mapBounds.containsLatLng(point))))? "emph" : "td_label";
			incs_array[i] = <?php 
                print $row['tick_id'];
                ?>
;
<?php 
                $allocated_groups = get_allocates(1, $row['tick_id']);
                //	4/18/11
                echo "var groups = [];\n";
                foreach ($allocated_groups as $key => $value) {
                    echo "groups[{$key}] = {$value};\n";
                }
                ?>
			incs_groups[i] = groups;	//	4/18/11	
			i++;	//	4/18/11	
<?php 
            }
            // end of check for no maps markes
        }
        // end if (my_is_float($row['lat']))
        $use_quick = (int) $func == 0 || (int) $func == 10 ? FALSE : TRUE;
        //	11/29/10
        if ($quick || $use_quick) {
            // 5/18/10, 11/29/10
            print "\t\t\tdo_sidebar_t_ed (\"{$sidebar_line}\", ({$the_offset} + {$sb_indx}), {$row['tick_id']}, sym, \"{$tip}\");\n";
        } else {
            print "\t\t do_sidebar (\"{$sidebar_line}\", {$sb_indx}, ({$the_offset} + {$sb_indx}+1), the_class, \"{$tip}\");\n";
        }
        if (intval($row['radius']) > 0) {
            $color = substr($row['color'], 0, 1) == "#" ? $row['color'] : "#000000";
            // black default
            ?>
	
//			drawCircle(				38.479874, 				-78.246704, 						50.0, 					"#000080",						 1, 		0.75,	 "#0000FF", 					.2);
			drawCircle(	<?php 
            print $row['lat'];
            ?>
, <?php 
            print $row['lng'];
            ?>
, <?php 
            print $row['radius'];
            ?>
, "<?php 
            print $color;
            ?>
", 1, 	0.75, "<?php 
            print $color;
            ?>
", .<?php 
            print $row['opacity'];
            ?>
);
<?php 
        }
        // end if (intval($row['radius'])
        $sb_indx++;
    }
    // end tickets while ($row = ...)
    //		$temp  = (string) ( round((microtime(true) - $time), 3));
    //		snap (__LINE__, $temp );
    $query_sched = "SELECT * FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE `status`='{$GLOBALS['STATUS_SCHEDULED']}'";
    //	11/29/10
    $result_sched = mysql_query($query_sched) or do_error($query_sched, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    //	11/29/10
    $num_sched = mysql_num_rows($result_sched);
    //	11/29/10
    if (mysql_num_rows($result) <= $line_limit) {
        ?>
	
	side_bar_html += get_chg_disp_tr();
<?php 
    }
    // end 	if (mysql_num_rows($result)<= $line_limit)
    ?>
		
		side_bar_html +="\t\t<SPAN ID = 'btn_go' onClick='document.to_listtype.submit()' CLASS='conf_button' STYLE = 'margin-left: 10px; display:none'><U>Next</U></SPAN>";
		side_bar_html +="\t\t<SPAN ID = 'btn_can'  onClick='hide_btns_closed(); hide_btns_scheduled(); ' CLASS='conf_button' STYLE = 'margin-left: 10px; display:none'><U>Cancel</U></SPAN>";
		side_bar_html +="<br /><br /></TD></TR>\n";

<?php 
    if ($sb_indx == 0) {
        $txt_str = $func > 0 ? "closed tickets this period!" : "current tickets!";
        print "\n\t\tside_bar_html += \"<TR CLASS='even'><TD COLSPAN='99' ALIGN='center'><I><B>No {$txt_str}</B></I></TD></TR>\";";
        print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TD COLSPAN='99' ><BR /><BR /></TD></TR>\";";
    }
    $limit = 1000;
    $link_str = "";
    $query = "SELECT `id` FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE `status` = '{$GLOBALS['STATUS_CLOSED']}'";
    $result_cl = mysql_query($query) or do_error($query, 'mysql_query', mysql_error(), basename(__FILE__), __LINE__);
    if (mysql_affected_rows() > $limit) {
        $sep = ", ";
        $rcds = mysql_affected_rows();
        for ($j = 0; $j < ceil($rcds / $limit); $j++) {
            $sep = $j == ceil($rcds / $limit) - 1 ? "" : ", ";
            $temp = (string) ($j * $limit);
            $link_str .= "<SPAN onClick = 'document.to_closed.frm_offset.value={$temp}; document.to_closed.submit();'><U>" . ($j + 1) . "K</U></SPAN>{$sep}";
        }
    }
    $sev_string = "" . get_text("Severities") . ": <SPAN CLASS='severity_normal'>" . get_text("Normal") . " ({$by_severity[$GLOBALS['SEVERITY_NORMAL']]})</SPAN>,&nbsp;&nbsp;<SPAN CLASS='severity_medium'>" . get_text("Medium") . " ({$by_severity[$GLOBALS['SEVERITY_MEDIUM']]})</SPAN>,&nbsp;&nbsp;<SPAN CLASS='severity_high'>" . get_text("High") . " ({$by_severity[$GLOBALS['SEVERITY_HIGH']]})</SPAN>";
    unset($acts_ary, $pats_ary, $result_temp, $result_cl);
    //		snap(__LINE__, round((microtime(true) - $time), 3));
    ?>
		
	side_bar_html +="<TR class='spacer'><TD class='spacer' COLSPAN='99' ALIGN='center'>&nbsp;</TD></TR>\n";	//	4/18/11
	side_bar_html +="</TABLE>\n";
	$("side_bar").innerHTML = side_bar_html;				// side_bar_html to incidents div 
	$("sched_flag").innerHTML = sched_html;				// side_bar_html to incidents div	
	$('sev_counts').innerHTML = "<?php 
    print $sev_string;
    ?>
";			// 5/2/10

//	for (var n = 0; n < incs_array.length; n++) {	//	4/18/11	
//		alert("Incident ID " + incs_array[n] + " Incident Groups " + incs_groups[n]);	//	4/18/11	
//			}	//	4/18/11	

// ==========================================      RESPONDER start    ================================================

	side_bar_html ="<TABLE border=0 CLASS='sidebar' WIDTH = <?php 
    print $col_width;
    ?>
 >\n";		// initialize units sidebar string
	side_bar_html += "<TR CLASS = 'spacer'><TD CLASS='spacer' COLSPAN=99>&nbsp;</TD></TR>";	//	3/15/11
	points = false;
	i++;
	var j=0;

<?php 
    $u_types = array();
    // 1/1/09
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}unit_types` ORDER BY `id`";
    // types in use
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        $u_types[$row['id']] = array($row['name'], $row['icon']);
        // name, index, aprs - 1/5/09, 1/21/09
    }
    unset($result);
    //	Categories for Unit status
    $categories = array();
    // 12/03/10
    $categories = get_category_butts();
    // 12/03/10
    $assigns = array();
    // 8/3/08
    $tickets = array();
    // ticket id's
    $query = "SELECT `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`, \n\t\t`{$GLOBALS['mysql_prefix']}assigns`.`responder_id`, \n\t\t`{$GLOBALS['mysql_prefix']}ticket`.`scope` AS `ticket` \n\t\tFROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` ON `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`=`{$GLOBALS['mysql_prefix']}ticket`.`id`";
    $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_as = stripslashes_deep(mysql_fetch_array($result_as))) {
        $assigns[$row_as['responder_id']] = $row_as['ticket'];
        $tickets[$row_as['responder_id']] = $row_as['ticket_id'];
    }
    unset($result_as);
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    $status_vals = array();
    // build array of $status_vals
    $status_vals[''] = $status_vals['0'] = "TBD";
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}un_status` ORDER BY `id`";
    $result_st = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_st = stripslashes_deep(mysql_fetch_array($result_st))) {
        $temp = $row_st['id'];
        $status_vals[$temp] = $row_st['status_val'];
        $status_hide[$temp] = $row_st['hide'];
    }
    unset($result_st);
    $assigns_ary = array();
    // construct array of responder_id's on active calls
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` WHERE ((`clear` IS  NULL) OR (DATE_FORMAT(`clear`,'%y') = '00')) ";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        $assigns_ary[$row['responder_id']] = TRUE;
    }
    $order_values = array(1 => "`nr_assigned` DESC,  `handle` ASC, `r`.`name` ASC", 2 => "`type_descr` ASC, `handle` ASC", 3 => "`stat_descr` ASC, `handle` ASC", 4 => "`handle` ASC");
    // 6/24/10
    if (array_key_exists('order', $_POST) && isset($_POST['order'])) {
        $_SESSION['unit_flag_2'] = $_POST['order'];
    } elseif (empty($_SESSION['unit_flag_2'])) {
        $_SESSION['unit_flag_2'] = 1;
    }
    $order_str = $order_values[$_SESSION['unit_flag_2']];
    // 6/11/10
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}';";
    // 4/18/11
    $result = mysql_query($query);
    // 4/18/11
    $al_groups = array();
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // 4/18/11
        $al_groups[] = $row['group'];
    }
    if (isset($_SESSION['viewed_groups'])) {
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    }
    if (!isset($curr_viewed)) {
        $x = 0;
        //	4/18/11
        $where2 = "WHERE (";
        //	4/18/11
        foreach ($al_groups as $grp) {
            //	4/18/11
            $where3 = count($al_groups) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    } else {
        $x = 0;
        //	4/18/11
        $where2 = "WHERE (";
        //	4/18/11
        foreach ($curr_viewed as $grp) {
            //	4/18/11
            $where3 = count($curr_viewed) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    }
    $where2 .= "AND `a`.`type` = 2";
    //-----------------------UNIT RING FENCE STUFF--------------------6/10/11
    ?>
	var thepoint;
	var points = new Array();
		
<?php 
    $query_bn = "SELECT * FROM `{$GLOBALS['mysql_prefix']}mmarkup` `l`\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}responder` `r` ON ( `l`.`id` = `r`.`ring_fence`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON ( `r`.`id` = `a`.`resource_id` )\t\n\t\t\t\t{$where2} AND `use_with_u_rf`=1 GROUP BY `l`.`id`";
    $result_bn = mysql_query($query_bn) or do_error($query_bn, mysql_error(), basename(__FILE__), __LINE__);
    while ($row_bn = stripslashes_deep(mysql_fetch_assoc($result_bn))) {
        extract($row_bn);
        $bn_name = $row_bn['line_name'];
        $all_boundaries[] = $row_bn['ring_fence'];
        $points = explode(";", $line_data);
        for ($i = 0; $i < count($points); $i++) {
            $coords = explode(",", $points[$i]);
            ?>
			thepoint = new GLatLng(parseFloat(<?php 
            print $coords[0];
            ?>
), parseFloat(<?php 
            print $coords[1];
            ?>
));
			points.push(thepoint);
<?php 
        }
        // end for ($i = 0 ... )
        if (intval($filled) == 1) {
            //	6/10/11
            ?>
			var polyline = new GPolygon(points, add_hash("<?php 
            print $line_color;
            ?>
"), <?php 
            print $line_width;
            ?>
, <?php 
            print $line_opacity;
            ?>
, add_hash("<?php 
            print $fill_color;
            ?>
"), <?php 
            print $fill_opacity;
            ?>
, {clickable:false, id:"ringfence"});
			boundary.push(polyline);
			bound_names.push("<?php 
            print $bn_name;
            ?>
"); 
<?php 
        } else {
            ?>
			var polyline = new GPolyline(points, add_hash("<?php 
            print $line_color;
            ?>
"), <?php 
            print $line_width;
            ?>
, <?php 
            print $line_opacity;
            ?>
, , 0, {clickable:false, id:"ringfence"});
			boundary.push(polyline);
			bound_names.push("<?php 
            print $bn_name;
            ?>
"); 
<?php 
        }
        ?>
			map.addOverlay(polyline);
<?php 
    }
    //	End while
    //-------------------------END OF UNIT RING FENCE STUFF-------------------------
    //-----------------------UNIT EXCLUSION ZONE STUFF--------------------6/10/11
    ?>
	var thepoint;
	var points = new Array();
		
<?php 
    $query_bn = "SELECT * FROM `{$GLOBALS['mysql_prefix']}mmarkup` `l`\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}responder` `r` ON ( `l`.`id` = `r`.`excl_zone`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON ( `r`.`id` = `a`.`resource_id` )\t\n\t\t\t\t{$where2} AND `use_with_u_ex`=1 GROUP BY `l`.`id`";
    $result_bn = mysql_query($query_bn) or do_error($query_bn, mysql_error(), basename(__FILE__), __LINE__);
    while ($row_bn = stripslashes_deep(mysql_fetch_assoc($result_bn))) {
        extract($row_bn);
        $bn_name = $row_bn['line_name'];
        $all_boundaries[] = $row_bn['excl_zone'];
        $points = explode(";", $line_data);
        for ($i = 0; $i < count($points); $i++) {
            $coords = explode(",", $points[$i]);
            ?>
			thepoint = new GLatLng(parseFloat(<?php 
            print $coords[0];
            ?>
), parseFloat(<?php 
            print $coords[1];
            ?>
));
			points.push(thepoint);
<?php 
        }
        // end for ($i = 0 ... )
        if (intval($filled) == 1) {
            //	6/10/11
            ?>
			var polyline = new GPolygon(points, add_hash("<?php 
            print $line_color;
            ?>
"), <?php 
            print $line_width;
            ?>
, <?php 
            print $line_opacity;
            ?>
, add_hash("<?php 
            print $fill_color;
            ?>
"), <?php 
            print $fill_opacity;
            ?>
, {clickable:false, id:"ringfence"});
			boundary.push(polyline);
			bound_names.push("<?php 
            print $bn_name;
            ?>
"); 
<?php 
        } else {
            ?>
			var polyline = new GPolyline(points, add_hash("<?php 
            print $line_color;
            ?>
"), <?php 
            print $line_width;
            ?>
, <?php 
            print $line_opacity;
            ?>
, , 0, {clickable:false, id:"ringfence"});
			boundary.push(polyline);
			bound_names.push("<?php 
            print $bn_name;
            ?>
"); 
<?php 
        }
        ?>
			map.addOverlay(polyline);
<?php 
    }
    //	End while
    //-------------------------END OF UNIT EXCLUSION ZONE STUFF-------------------------
    $query = "SELECT *, UNIX_TIMESTAMP(updated) AS `updated`, \n\t\t`t`.`id` AS `type_id`, \n\t\t`r`.`id` AS `unit_id`, \n\t\t`r`.`name` AS `name`,\n\t\t`r`.`ring_fence` AS `ring_fence`,\t\t\n\t\t`s`.`description` AS `stat_descr`,  \n\t\t`r`.`description` AS `unit_descr`, \n\t\t`t`.`description` AS `type_descr`,\n\t\t(SELECT  COUNT(*) as numfound FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\tWHERE `{$GLOBALS['mysql_prefix']}assigns`.`responder_id` = unit_id \tAND ( `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' )) AS `nr_assigned` \n\t\tFROM `{$GLOBALS['mysql_prefix']}responder` `r` \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON ( `r`.`id` = a.resource_id )\t\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}unit_types` `t` ON ( `r`.`type` = t.id )\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}un_status` `s` ON ( `r`.`un_status_id` = s.id ) \t\t\n\t\t{$where2}  GROUP BY unit_id ORDER BY {$order_str}";
    // 2/1/10, 3/8/10, 4/18/11, 6/11/10
    //	dump($query);
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $units_ct = mysql_affected_rows();
    // 1/4/10
    if ($units_ct == 0) {
        print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TH></TH><TH ALIGN='center' COLSPAN=99><I><B>No units!</I></B></TH></TR>\"\n";
    } else {
        $checked = array("", "", "", "");
        $checked[$_SESSION['unit_flag_2']] = " CHECKED";
        ?>
	
	side_bar_html += "<TR CLASS = 'even'><TD COLSPAN=99 ALIGN='center'>";
	side_bar_html += "<I><B>Sort</B>:&nbsp;&nbsp;&nbsp;&nbsp;";
	side_bar_html += "Unit &raquo; 	<input type = radio name = 'frm_order' value = 1 <?php 
        print $checked[1];
        ?>
 onClick = 'do_sort_sub(this.value);' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	side_bar_html += "Type &raquo; 	<input type = radio name = 'frm_order' value = 2 <?php 
        print $checked[2];
        ?>
 onClick = 'do_sort_sub(this.value);' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	side_bar_html += "Status &raquo; <input type = radio name = 'frm_order' value = 3 <?php 
        print $checked[3];
        ?>
 onClick = 'do_sort_sub(this.value);' />";
	side_bar_html += "</I></TD></TR>";
<?php 
        print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TD></TD><TD><B>Unit</B> ({$units_ct}) </TD>\t<TD onClick = 'do_mail_win(0); ' ALIGN = 'center'><IMG SRC='mail_red.png' /></TD><TD ALIGN='left' COLSPAN='2'><B>{$incident}</B></TD><TD>&nbsp; <B>Status</B></TD><TD><B>M</B></TD><TD><B>&nbsp;As of</B></TD></TR>\"\n";
        // 12/17/10
        //		print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TD></TD><TD><B>Unit</B> ({$units_ct}) </TD>	<TD onClick = 'do_mail_win(0); ' ALIGN = 'center'><IMG SRC='mail_red.png' /></TD><TD>&nbsp; <B>Status</B></TD><TD ALIGN='left' COLSPAN='2'><B>{$incident}</B></TD><TD><B>M</B></TD><TD><B>&nbsp;As of</B></TD></TR>\"\n" ;	// 12/17/10
        //		print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TD></TD><TD><B>Unit</B> ({$units_ct}) </TD>	<TD onClick = 'do_mail_win(null, null); ' ALIGN = 'center'><IMG SRC='mail_red.png' /></TD><TD>&nbsp; <B>Status</B></TD><TD ALIGN='left' COLSPAN='2'><B>{$incident}</B></TD><TD><B>M</B></TD><TD><B>&nbsp;As of</B></TD></TR>\"\n" ;
    }
    $aprs = $instam = $locatea = $gtrack = $glat = $t_tracker = $ogts = FALSE;
    //7/23/09
    $utc = gmdate("U");
    // 3/25/09
    // ===========================  begin major while() for RESPONDER ==========
    $chgd_unit = $_SESSION['unit_flag_1'];
    // possibly 0 - 4/8/10
    $_SESSION['unit_flag_1'] = 0;
    // one-time only - 4/11/10
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // 7/7/10
        $resp_gps = get_allocates(2, $row['unit_id']);
        //	6/10/11
        $grp_names = "Groups Assigned: ";
        //	6/10/11
        $y = 0;
        //	6/10/11
        foreach ($resp_gps as $value) {
            //	6/10/11
            $counter = count($resp_gps) > $y + 1 ? ", " : "";
            $grp_names .= get_groupname($value);
            $grp_names .= $counter;
            $y++;
        }
        $tip = str_replace("'", "`", $grp_names . " / " . htmlentities($row['name'], ENT_QUOTES));
        // tooltip string - 1/3/10
        $latitude = $row['lat'];
        // 7/18/10
        $longitude = $row['lng'];
        // 7/18/10
        $on_click = !my_is_float($row['lat']) || $quick ? " myclick_nm({$row['unit_id']}) " : "myclick({$sb_indx})";
        // 1/2/10
        $got_point = FALSE;
        $name = $row['name'];
        //	10/8/09
        $index = $row['icon_str'];
        // 4/27/11
        print "\t\tvar sym = \"{$index}\";\n";
        // for sidebar and icon 10/8/09	- 4/22/11
        // 2/13/09
        $todisp = is_guest() || is_unit() ? "" : "&nbsp;&nbsp;<A HREF='{$_SESSION['unitsfile']}?func=responder&view=true&disp=true&id=" . $row['unit_id'] . "'><U>Dispatch</U></A>&nbsp;&nbsp;";
        // 08/8/02
        $toedit = is_guest() || is_user() || is_unit() ? "" : "&nbsp;&nbsp;<A HREF='{$_SESSION['unitsfile']}?func=responder&edit=true&id=" . $row['unit_id'] . "'><U>Edit</U></A>&nbsp;&nbsp;";
        // 7/27/10
        $totrack = intval($row['mobile']) == 0 || empty($row['callsign']) ? "" : "&nbsp;&nbsp;<SPAN onClick = do_track('" . $row['callsign'] . "');><B><U>Tracks</B></U>&nbsp;&nbsp;</SPAN>";
        $tofac = is_guest() ? "" : "<A HREF='{$_SESSION['unitsfile']}?func=responder&view=true&dispfac=true&id=" . $row['unit_id'] . "'><U>To Facility</U></A>&nbsp;&nbsp;";
        // 08/8/02
        $hide_unit = $row['hide'] == "y" ? "1" : "0";
        // 3/8/10
        $track_type = get_remote_type($row);
        // 7/8/11
        //		print "Track Type = " . $track_type;
        $row_track = FALSE;
        if ($track_type > 0) {
            // get most recent mobile track data
            $do_legend = TRUE;
            $query = "SELECT *,UNIX_TIMESTAMP(packet_date) AS `packet_date`, UNIX_TIMESTAMP(updated) AS `updated` FROM `{$GLOBALS['mysql_prefix']}tracks`\n\t\t\t\tWHERE `source`= '{$row['callsign']}' ORDER BY `packet_date` DESC LIMIT 1";
            // newest
            $result_tr = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
            $row_track = mysql_affected_rows() > 0 ? stripslashes_deep(mysql_fetch_assoc($result_tr)) : FALSE;
            $aprs_updated = $row_track['updated'];
            $aprs_speed = $row_track['speed'];
            if ($row_track && my_is_float($row_track['latitude'])) {
                $latitude = $row_track['latitude'];
                $longitude = $row_track['longitude'];
                // 7/7/10
                echo "\t\tvar point = new GLatLng(" . $row_track['latitude'] . ", " . $row_track['longitude'] . "); // 677\n";
                $got_point = TRUE;
            }
            unset($result_tr);
        }
        if (my_is_float($row['lat'])) {
            echo "\t\tvar point = new GLatLng(" . $row['lat'] . ", " . $row['lng'] . ");\t// 753\n";
            $got_point = TRUE;
        }
        $the_bull = "";
        // define the bullet
        $update_error = strtotime('now - 6 hours');
        // set the time for silent setting
        // NAME
        $the_bg_color = $GLOBALS['UNIT_TYPES_BG'][$row['icon']];
        // 2/1/10
        $the_text_color = $GLOBALS['UNIT_TYPES_TEXT'][$row['icon']];
        $arrow = $chgd_unit == $row['unit_id'] ? "<IMG SRC='rtarrow.gif' />" : "";
        // 4/8/10
        $sidebar_line = "<TD ALIGN='left' onClick = '{$on_click}' TITLE = '" . htmlentities($row['name'], ENT_QUOTES) . "' >{$arrow}<SPAN STYLE='background-color:{$the_bg_color};  opacity: .7; color:{$the_text_color};'>" . htmlentities($row['handle'], ENT_QUOTES) . "</B></U></SPAN></TD>";
        // MAIL
        if (!is_guest() && is_email($row['contact_via'])) {
            // 2/1/10
            $mail_link = "\t<TD CLASS='mylink' ALIGN='center'>" . "&nbsp;<IMG SRC='mail.png' BORDER=0 TITLE = 'click to email unit {$row['handle']}'" . " onclick = 'do_mail_win(\\\"{$row['unit_id']}\\\");'> " . "&nbsp;</TD>";
            // 4/26/09, 12/17/10
            //				dump(__LINE__);
            //				dump($mail_link);
        } else {
            $mail_link = "\t<TD ALIGN='center'>na</TD>";
        }
        $sidebar_line .= $mail_link;
        // DISPATCHES 3/16/09
        $units_assigned = 0;
        if (array_key_exists($row['unit_id'], $assigns_ary)) {
            // this unit assigned? - 6/4/10
            $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns`  \n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` t ON ({$GLOBALS['mysql_prefix']}assigns.ticket_id = t.id)\n\t\t\t\tWHERE `responder_id` = '{$row['unit_id']}' AND ( `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' )";
            $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
            $units_assigned = mysql_num_rows($result_as);
        }
        // end if(array_key_exists ()
        switch ($units_assigned) {
            case 0:
                $ass_td = "<TD COLSPAN='2' onClick = '{$on_click}' > na </TD>";
                break;
            case 1:
                $row_assign = stripslashes_deep(mysql_fetch_assoc($result_as));
                $the_disp_stat = get_disp_status($row_assign) . "&nbsp;";
                $tip = htmlentities("{$row_assign['contact']}/{$row_assign['street']}/{$row_assign['city']}/{$row_assign['phone']}/{$row_assign['scope']}", ENT_QUOTES);
                switch ($row_assign['severity']) {
                    //color tickets by severity
                    case $GLOBALS['SEVERITY_MEDIUM']:
                        $severityclass = 'severity_medium';
                        break;
                    case $GLOBALS['SEVERITY_HIGH']:
                        $severityclass = 'severity_high';
                        break;
                    default:
                        $severityclass = 'severity_normal';
                        break;
                }
                // end switch()
                $ass_td = "<TD ALIGN='left' onMouseover=\\\"Tip('{$tip}')\\\" onmouseout=\\\"UnTip()\\\" onClick = '{$on_click}' COLSPAN=2 CLASS='{$severityclass}' >{$the_disp_stat}" . shorten($row_assign['scope'], 20) . "</TD>";
                break;
            default:
                // multiples
                $ass_td = "<TD COLSPAN=2 onClick = '{$on_click}' CLASS='disp_stat'>&nbsp;{$units_assigned}&nbsp;</TD>&nbsp;";
                break;
        }
        // end switch(($units_assigned))
        $sidebar_line .= $ass_td;
        // STATUS
        $sidebar_line .= "<TD>" . get_status_sel($row['unit_id'], $row['un_status_id'], "u") . "</TD>";
        // status
        //  MOBILITY
        $the_bull = "";
        //	dump($row_track);
        if ($row_track) {
            if ($row_track['speed'] > 50) {
                $the_bull = "<FONT COLOR = 'black'><B>" . $GLOBALS['TRACK_2L'][$track_type] . "</B></FONT>";
            }
            if ($row_track['speed'] < 50) {
                $the_bull = "<FONT COLOR = 'black'><B>" . $GLOBALS['TRACK_2L'][$track_type] . "</B></FONT>";
            }
            if ($row_track['speed'] == 0) {
                $the_bull = "<FONT COLOR = 'red'><B>" . $GLOBALS['TRACK_2L'][$track_type] . "</B></FONT>";
            }
        }
        $cstip = htmlentities($row['callsign'], ENT_QUOTES);
        $tip_str = "onMouseover=\\\"Tip('{$cstip}')\\\" onmouseout=\\\"UnTip();\\\" ";
        $sidebar_line .= "<TD {$tip_str} onClick = '{$on_click}'>{$the_bull}</TD>";
        // as of
        $the_time = $row['updated'];
        $the_class = "";
        $strike = $strike_end = "";
        $the_flag = $name . "_flag";
        if ($track_type > 0 && abs($utc - $the_time) > $GLOBALS['TOLERANCE']) {
            // attempt to identify  non-current values
            snap(__LINE__, abs($utc - $the_time));
            $strike = "<STRIKE>";
            $strike_end = "</STRIKE>";
        }
        $sidebar_line .= "<TD CLASS='{$the_class}'> {$strike} <SPAN id = '" . $name . "'>" . format_sb_date($the_time) . "</SPAN>{$strike_end}&nbsp;&nbsp;<SPAN ID = '" . $the_flag . "'></SPAN></TD>";
        // 6/17/08
        if (my_is_float($row['lat'])) {
            // 5/4/09
            // tab 1
            $temptype = $u_types[$row['type_id']];
            $the_type = $temptype[0];
            // 1/1/09
            $tab_1 = "<TABLE CLASS='infowin'  width='{$iw_width}' >";
            $tab_1 .= "<TR CLASS='even'><TD COLSPAN=2 ALIGN='center'><B>{$row['handle']}</B> - " . $the_type . "</TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD ALIGN='left'>Description:</TD><TD ALIGN='left'>" . shorten(str_replace($eols, " ", $row['unit_descr']), 32) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='even'><TD ALIGN='left'>{$gt_status}:</TD><TD ALIGN='left'> {$row['stat_descr']}</TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD ALIGN='left'>Contact:</TD><TD ALIGN='left'>" . $row['contact_name'] . " Via: " . $row['contact_via'] . "</TD></TR>";
            $tab_1 .= "<TR CLASS='even'><TD ALIGN='left'>As of:</TD><TD ALIGN='left'>" . format_date($row['updated']) . "</TD></TR>";
            if (array_key_exists($row['unit_id'], $assigns_ary)) {
                $tab_1 .= "<TR CLASS='even'><TD ALIGN='left' CLASS='emph'>Dispatched to:</TD><TD ALIGN='left' CLASS='emph'><A HREF='main.php?id=" . $tickets[$row['unit_id']] . "'>" . shorten($assigns[$row['unit_id']], 20) . "</A></TD></TR>";
            }
            $tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'>" . $tofac . $todisp . $totrack . $toedit . "&nbsp;&nbsp;<A HREF='{$_SESSION['unitsfile']}?func=responder&view=true&id=" . $row['unit_id'] . "'><U>View</U></A></TD></TR>";
            // 08/8/02
            $tab_1 .= "</TABLE>";
            // tab 2
            if ($row_track) {
                // three tabs if track data
                $tab_2 = "<TABLE CLASS='infowin'  width='{$iw_width}' >";
                $tab_2 .= "<TR CLASS='even'><TD COLSPAN=2 ALIGN='center'><B>" . $row_track['source'] . "</B></TD></TR>";
                $tab_2 .= "<TR CLASS='odd'><TD ALIGN='left'>Course: </TD><TD ALIGN='left'>" . $row_track['course'] . ", Speed:  " . $row_track['speed'] . ", Alt: " . $row_track['altitude'] . "</TD></TR>";
                $tab_2 .= "<TR CLASS='even'><TD ALIGN='left'>Closest city: </TD><TD ALIGN='left'>" . $row_track['closest_city'] . "</TD></TR>";
                $tab_2 .= "<TR CLASS='odd'><TD ALIGN='left'>{$gt_status}: </TD><TD ALIGN='left'>" . $row_track['status'] . "</TD></TR>";
                $tab_2 .= "<TR CLASS='even'><TD ALIGN='left'>As of: </TD><TD ALIGN='left'> {$strike} " . format_date($row_track['packet_date']) . " {$strike_end} (UTC)</TD></TR></TABLE>";
                ?>
			var myinfoTabs = [
				new GInfoWindowTab("<?php 
                print $row['handle'];
                ?>
", "<?php 
                print $tab_1;
                ?>
"),
				new GInfoWindowTab("<?php 
                print $GLOBALS['TRACK_2L'][$track_type];
                ?>
 <?php 
                print addslashes(substr($row_track['source'], -3));
                ?>
", "<?php 
                print $tab_2;
                ?>
"),
				new GInfoWindowTab("Zoom", "<div id='detailmap' class='detailmap'></div>")
				];
<?php 
            } else {
                // else two tabs
                ?>
			var myinfoTabs = [
				new GInfoWindowTab("<?php 
                print $row['handle'];
                ?>
", "<?php 
                print $tab_1;
                ?>
"),
				new GInfoWindowTab("Zoom", "<div id='detailmap' class='detailmap'></div>")
				];
<?php 
            }
            // end if(!($tabs_done))
        }
        // end position data available
        $tip = isset($tip) ? $tip : "No Tip String";
        if (!my_is_float($row['lat']) || $quick) {
            // 11/27/09
            $resp_cat = get_category($row['unit_id']);
            print "\t\tdo_sidebar_u_ed (\"{$sidebar_line}\",  {$sb_indx}, '{$on_click}', sym, \"{$tip}\", \"{$resp_cat}\");\n";
            // (sidebar, line_no, on_click, letter)
        } else {
            ?>
		var the_class = ((map_is_fixed) && (!(mapBounds.containsLatLng(point))))? "emph" : "td_label";
		do_sidebar_unit ("<?php 
            print $sidebar_line;
            ?>
",  <?php 
            print $sb_indx;
            ?>
, sym, the_class, "<?php 
            print $tip;
            ?>
", "<?php 
            print get_category($row['unit_id']);
            ?>
");		// (instr, id, sym, myclass, tip)  - 1/3/10
<?php 
        }
        if (my_is_float($latitude)) {
            // map position?
            $the_color = $row['mobile'] == "1" ? 0 : 4;
            // icon color black, white		-- 4/18/09
            $the_group = get_category($row['unit_id']);
            //	3/15/11
            if ($latitude == "0.999999" && $longitude == "0.999999") {
                // check for no maps added points 7/28/10
                $dummylat = get_variable('def_lat');
                $dummylng = get_variable('def_lng');
                echo "\t\tvar point = new GLatLng(" . $dummylat . ", " . $dummylng . "); // 677\n";
                ?>
			var dummymarker = createdummyMarker(point, myinfoTabs, <?php 
                print $sb_indx;
                ?>
);	// 859  - 7/28/10. Plots dummy icon in default position for units added in no maps operation
			map.addOverlay(dummymarker);
<?php 
            } else {
                ?>
			var the_group = '<?php 
                print $the_group;
                ?>
';	//	3/15/11
			var tip_str = "";
			var region = "<?php 
                print get_first_group(2, $row['unit_id']);
                ?>
";			
			var marker = createMarker(point, myinfoTabs, <?php 
                print $the_color;
                ?>
, <?php 
                print $hide_unit;
                ?>
,  <?php 
                print $sb_indx;
                ?>
, sym, the_group, region, tip_str); // 7/28/10, 3/15/11
			map.addOverlay(marker);
<?php 
            }
            // end check for no maps added points
        }
        // end if (my_is_float())
        ?>
		var rowId = <?php 
        print $sb_indx;
        ?>
;			// row index for row hide/show - 3/2/10
		rowIds.push(rowId);													// form is "tr_id_??" where ?? is the row no.
<?php 
        $sb_indx++;
        // zero-based
    }
    // end  ==========  while() for RESPONDER ==========
    //	$temp  = (string) ( round((microtime(true) - $time), 3));
    $source_legend = isset($do_legend) ? "<TD CLASS='emph' ALIGN='left'>Source time</TD>" : "<TD></TD>";
    // if any remote data/time 3/24/09
    print "\n\tside_bar_html+= \"<TR CLASS='\" + colors[i%2] +\"'><TD COLSPAN='7' ALIGN='right'>{$source_legend}</TD></TR>\";\n";
    ?>
	var legends = "<TR class='even'><TD ALIGN='center' COLSPAN='99'><TABLE ALIGN='center' WIDTH = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.4));
    ?>
 >";	//	3/15/11
	legends += "<TR CLASS='spacer'><TD CLASS='spacer' COLSPAN='99' ALIGN='center'>&nbsp;</TD></TR><TR class='even'><TD ALIGN='center' COLSPAN='99'><B>Responders Legend</B></TD></TR>";	//	3/15/11
	legends += "<TR CLASS='even'><TD COLSPAN='99' ALIGN='center'>&nbsp;&nbsp;<B>M</B>obility:&nbsp;&nbsp; stopped: <FONT COLOR='red'>&bull;</FONT>&nbsp;&nbsp;&nbsp;moving: <FONT COLOR='green'>&bull;</FONT>&nbsp;&nbsp;&nbsp;fast: <FONT COLOR='white'>&bull;</FONT>&nbsp;&nbsp;&nbsp;silent: <FONT COLOR='black'>&bull;</FONT>&nbsp;&nbsp;</TD></TR>";	//	3/15/11
	legends += "<TR CLASS='even'><TD COLSPAN='99' ALIGN='center'><?php 
    print get_units_legend();
    ?>
</TD></TR></TABLE>";	//	3/15/11

	$("side_bar_r").innerHTML = side_bar_html;		//	12/03/10
	$("side_bar_rl").innerHTML = legends + "</TABLE>";		//	12/03/10
	side_bar_html= "";		//	12/03/10
	side_bar_html+="<TABLE><TR class='heading_2'><TH width = <?php 
    print $ctrls_width;
    ?>
 ALIGN='center'>Responders</TH></TR><TR class='odd'><TD COLSPAN=99 CLASS='td_label' ><form action='#'>";			//	12/03/10, 3/15/11
<?php 
    if ($units_ct > 0) {
        //	3/15/11
        foreach ($categories as $key => $value) {
            //	12/03/10
            ?>
		side_bar_html += "<DIV class='cat_button' onClick='set_chkbox(\"<?php 
            print $value;
            ?>
\")'><?php 
            print $value;
            ?>
: <input type=checkbox id='<?php 
            print $value;
            ?>
' onClick='set_chkbox(\"<?php 
            print $value;
            ?>
\")'/>&nbsp;&nbsp;&nbsp;</DIV>";			<!-- 12/03/10 -->
<?php 
        }
        $all = "ALL";
        //	12/03/10
        $none = "NONE";
        //	12/03/10
        ?>
		side_bar_html += "<DIV ID = 'ALL_BUTTON' class='cat_button' onClick='set_chkbox(\"<?php 
        print $all;
        ?>
\")'><FONT COLOR = 'red'>ALL</FONT><input type=checkbox id='<?php 
        print $all;
        ?>
' onClick='set_chkbox(\"<?php 
        print $all;
        ?>
\")'/></FONT></DIV>";			<!-- 12/03/10 -->
		side_bar_html += "<DIV ID = 'NONE_BUTTON' class='cat_button'  onClick='set_chkbox(\"<?php 
        print $none;
        ?>
\")'><FONT COLOR = 'red'>NONE</FONT><input type=checkbox id='<?php 
        print $none;
        ?>
' onClick='set_chkbox(\"<?php 
        print $none;
        ?>
\")'/></FONT></DIV>";			<!-- 12/03/10 -->
		side_bar_html += "<DIV ID = 'go_can' style='float:right; padding:2px;'><SPAN ID = 'go_button' onClick='do_go_button()' class='conf_next_button' STYLE = 'display:none;'><U>Next</U></SPAN>";
		side_bar_html += "<SPAN ID = 'can_button'  onClick='cancel_buttons()' class='conf_can_button' STYLE = 'display:none;'><U>Cancel</U></SPAN></DIV>";
		side_bar_html+="</form></TD></TR></TABLE>";			<!-- 12/03/10 -->
<?php 
    } else {
        foreach ($categories as $key => $value) {
            //	12/03/10
            ?>
		side_bar_html += "<DIV class='cat_button' STYLE='display: none;' onClick='set_chkbox(\"<?php 
            print $value;
            ?>
\")'><?php 
            print $value;
            ?>
: <input type=checkbox id='<?php 
            print $value;
            ?>
' onClick='set_chkbox(\"<?php 
            print $value;
            ?>
\")'/>&nbsp;&nbsp;&nbsp;</DIV>";			<!-- 12/03/10 -->
<?php 
        }
        $all = "ALL";
        //	12/03/10
        $none = "NONE";
        //	12/03/10
        ?>
		side_bar_html += "<DIV class='cat_button' style='color: red;'>None Defined ! </DIV>";			<!-- 12/03/10 -->
		side_bar_html += "<DIV ID = 'ALL_BUTTON' class='cat_button' STYLE='display: none;' onClick='set_chkbox(\"<?php 
        print $all;
        ?>
\")'><FONT COLOR = 'red'>ALL</FONT><input type=checkbox id='<?php 
        print $all;
        ?>
' onClick='set_chkbox(\"<?php 
        print $all;
        ?>
\")'/></FONT></DIV>";			<!-- 12/03/10 -->
		side_bar_html += "<DIV ID = 'NONE_BUTTON' class='cat_button' STYLE='display: none;' onClick='set_chkbox(\"<?php 
        print $none;
        ?>
\")'><FONT COLOR = 'red'>NONE</FONT><input type=checkbox id='<?php 
        print $none;
        ?>
' onClick='set_chkbox(\"<?php 
        print $none;
        ?>
\")'/></FONT></DIV>";			<!-- 12/03/10 -->
		side_bar_html +="</form></TD></TR></TABLE></DIV>";			<!-- 12/03/10 -->
<?php 
    }
    ?>


	$("boxes").innerHTML = side_bar_html;										// 12/03/10 side_bar_html to responders div			

<?php 
    //	snap(__LINE__, round((microtime(true) - $time), 3));
    $fac_categories = array();
    // 12/03/10
    $fac_categories = get_fac_category_butts();
    // 12/03/10
    ?>
// ==================================== Add Facilities to Map 8/1/09 ================================================
	side_bar_html ="<TABLE border=0 CLASS='sidebar' >\n";

	var icons=[];	
	var g=0;

	var fmarkers = [];

	var baseIcon = new GIcon();
	baseIcon.shadow = "./markers/sm_shadow.png";

	baseIcon.iconSize = new GSize(30, 30);
	baseIcon.iconAnchor = new GPoint(15, 30);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);

	var fac_icon = new GIcon(baseIcon);
	fac_icon.image = icons[1];

function createfacMarker(fac_point, fac_name, id, fac_icon, type, region) {
	var region = region || 0;
	var fac_marker = new GMarker(fac_point, fac_icon);
	// Show this markers index in the info window when it is clicked
	var fac_html = fac_name;
	fac_marker.category = type;
	fac_marker.region = region;	
	fmarkers[id] = fac_marker;
	GEvent.addListener(fac_marker, "click", function() {fac_marker.openInfoWindowHtml(fac_html);});
	return fac_marker;
	}

<?php 
    $fac_order_values = array(1 => "`handle`,`fac_type_name` ASC", 2 => "`fac_type_name`,`handle` ASC", 3 => "`fac_status_val`,`fac_type_name` ASC");
    // 3/15/11
    if (array_key_exists('forder', $_POST)) {
        $_SESSION['fac_flag_2'] = $_POST['forder'];
    } elseif (empty($_SESSION['fac_flag_2'])) {
        $_SESSION['fac_flag_2'] = 2;
    }
    // 3/15/11
    $fac_order_str = $fac_order_values[$_SESSION['fac_flag_2']];
    // 3/15/11
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}';";
    //	6/10/11
    $result = mysql_query($query);
    //	6/10/11
    $al_groups = array();
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        //	6/10/11
        $al_groups[] = $row['group'];
    }
    if (isset($_SESSION['viewed_groups'])) {
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    }
    if (!isset($curr_viewed)) {
        $x = 0;
        //	6/10/11
        $where2 = "WHERE (";
        //	6/10/11
        foreach ($al_groups as $grp) {
            //	6/10/11
            $where3 = count($al_groups) > $x + 1 ? " OR " : ")";
            $where2 .= "`{$GLOBALS['mysql_prefix']}allocates`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    } else {
        $x = 0;
        //	6/10/11
        $where2 = "WHERE (";
        //	6/10/11
        foreach ($curr_viewed as $grp) {
            //	6/10/11
            $where3 = count($curr_viewed) > $x + 1 ? " OR " : ")";
            $where2 .= "`{$GLOBALS['mysql_prefix']}allocates`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    }
    $where2 .= "AND `{$GLOBALS['mysql_prefix']}allocates`.`type` = 3";
    //	6/10/11
    //-----------------------FACILITY BOUNDARY / CATCHMENT FENCE STUFF--------------------6/10/11
    ?>
	var thepoint;
	var points = new Array();
	
<?php 
    $query_bn = "SELECT * FROM `{$GLOBALS['mysql_prefix']}mmarkup` `l`\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}facilities` `f` ON ( `l`.`id` = `f`.`boundary`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` ON ( `f`.`id` = `{$GLOBALS['mysql_prefix']}allocates`.`resource_id` )\t\n\t\t\t\t{$where2} AND `use_with_f`=1 GROUP BY `l`.`id`";
    $result_bn = mysql_query($query_bn) or do_error($query_bn, mysql_error(), basename(__FILE__), __LINE__);
    while ($row_bn = stripslashes_deep(mysql_fetch_assoc($result_bn))) {
        extract($row_bn);
        $bn_name = $row_bn['line_name'];
        $all_boundaries[] = $row_bn['boundary'];
        $points = explode(";", $line_data);
        for ($i = 0; $i < count($points); $i++) {
            $coords = explode(",", $points[$i]);
            ?>
			thepoint = new GLatLng(parseFloat(<?php 
            print $coords[0];
            ?>
), parseFloat(<?php 
            print $coords[1];
            ?>
));
			points.push(thepoint);
<?php 
        }
        // end for ($i = 0 ... )
        if (intval($filled) == 1) {
            //	6/10/11
            ?>
			var polyline = new GPolygon(points, "<?php 
            print $line_color;
            ?>
", <?php 
            print $line_width;
            ?>
, <?php 
            print $line_opacity;
            ?>
, "<?php 
            print $fill_color;
            ?>
", <?php 
            print $fill_opacity;
            ?>
, {clickable:false, id: "catchment"});
			boundary.push(polyline);
			bound_names.push("<?php 
            print $bn_name;
            ?>
"); 	
<?php 
        } else {
            ?>
			var polyline = new GPolyline(points, "<?php 
            print $line_color;
            ?>
", <?php 
            print $line_width;
            ?>
, <?php 
            print $line_opacity;
            ?>
, , 0, {clickable:false, id: "catchment"});
			boundary.push(polyline);
			bound_names.push("<?php 
            print $bn_name;
            ?>
"); 
<?php 
        }
        ?>
			map.addOverlay(polyline);
<?php 
    }
    //	End while
    //-------------------------END OF FACILITY BOUNDARY / CATCHMENT STUFF-------------------------
    $query_fac = "SELECT *,UNIX_TIMESTAMP(updated) AS updated, `{$GLOBALS['mysql_prefix']}facilities`.id AS fac_id, \n\t\t`{$GLOBALS['mysql_prefix']}facilities`.description AS facility_description,\n\t\t`{$GLOBALS['mysql_prefix']}facilities`.boundary AS boundary,\t\t\n\t\t`{$GLOBALS['mysql_prefix']}fac_types`.name AS fac_type_name, \n\t\t`{$GLOBALS['mysql_prefix']}facilities`.name AS facility_name, \n\t\t`{$GLOBALS['mysql_prefix']}fac_status`.status_val AS fac_status_val, \n\t\t`{$GLOBALS['mysql_prefix']}facilities`.status_id AS fac_status_id\n\t\tFROM `{$GLOBALS['mysql_prefix']}facilities`\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` ON ( `{$GLOBALS['mysql_prefix']}facilities`.`id` = `{$GLOBALS['mysql_prefix']}allocates`.resource_id )\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}fac_types` ON `{$GLOBALS['mysql_prefix']}facilities`.type = `{$GLOBALS['mysql_prefix']}fac_types`.id \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}fac_status` ON `{$GLOBALS['mysql_prefix']}facilities`.status_id = `{$GLOBALS['mysql_prefix']}fac_status`.id \n\t\t{$where2} \n\t\tGROUP BY fac_id ORDER BY {$fac_order_str}";
    // 3/15/11, 6/10/11
    $result_fac = mysql_query($query_fac) or do_error($query_fac, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $temp = $col_width;
    $mail_str = may_email() ? "do_fac_mail_win();" : "";
    // 7/2/10
    print "\n\t\tside_bar_html += \"<TR CLASS='even' colspan='99'><TABLE ID='fac_table' STYLE='display: inline-block; width: 100%'>\"\n";
    $facs_ct = mysql_affected_rows();
    // 1/4/10
    if ($facs_ct == 0) {
        print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TH COLSPAN=99 ALIGN='center'><I><B>No Facilities!</I></B></TH></TR>\"\n";
        //	3/15/11
    } else {
        $fs_checked = array("", "", "", "");
        $fs_checked[$_SESSION['fac_flag_2']] = " CHECKED";
        ?>
		side_bar_html += "<TR CLASS = 'even'><TD COLSPAN=99 ALIGN='center'>";	//	3/15/11
		side_bar_html += "<I><B>Sort</B>:&nbsp;&nbsp;&nbsp;&nbsp;";
		side_bar_html += "Handle&raquo; 	<input type = radio name = 'frm_order' value = 1 <?php 
        print $fs_checked[1];
        ?>
 onClick = 'do_fac_sort_sub(this.value);' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";	//	3/15/11, 5/3/11
		side_bar_html += "Type &raquo; 	<input type = radio name = 'frm_order' value = 2 <?php 
        print $fs_checked[2];
        ?>
 onClick = 'do_fac_sort_sub(this.value);' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";	//	3/15/11, 5/3/11
		side_bar_html += "Status &raquo; <input type = radio name = 'frm_order' value = 3 <?php 
        print $fs_checked[3];
        ?>
 onClick = 'do_fac_sort_sub(this.value);' />";	//	3/15/11, 5/3/11
		side_bar_html += "</I></TD></TR>";	//	3/15/11
<?php 
        print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TD>&nbsp;&nbsp;</TD><TD ALIGN='left'><B>Facility</B> ({$facs_ct}) </TD><TD ALIGN='left'><IMG SRC='mail_red.png' BORDER=0 onClick = '{$mail_str}'/></TD><TD>&nbsp;<B>Status</B></TD><TD ALIGN='left'><B>Type</B></TD><TD ALIGN='left'><B>&nbsp;As of</B></TD></TR>\"\n";
        // 7/2/10, 3/15/11
    }
    // ===========================  begin major while() for FACILITIES ==========
    $quick = !is_guest() && intval(get_variable('quick') == 1);
    // 11/27/09
    $sb_indx = 0;
    // for fac's only 8/5/10
    while ($row_fac = mysql_fetch_assoc($result_fac)) {
        // 7/7/10
        $fac_gps = get_allocates(3, $row_fac['fac_id']);
        //	6/10/11
        $grp_names = "Groups Assigned: ";
        //	6/10/11
        $y = 0;
        //	6/10/11
        foreach ($fac_gps as $value) {
            //	6/10/11
            $counter = count($fac_gps) > $y + 1 ? ", " : "";
            $grp_names .= get_groupname($value);
            $grp_names .= $counter;
            $y++;
        }
        $grp_names .= " / ";
        $fac_id = $row_fac['fac_id'];
        $fac_type = $row_fac['icon'];
        $fac_type_name = $row_fac['fac_type_name'];
        $fac_region = get_first_group(3, $fac_id);
        $fac_index = $row_fac['icon_str'];
        $fac_name = $row_fac['handle'];
        //		10/8/09
        $on_click = $quick ? "fac_click_ed({$fac_id})" : ($clickevent = "fac_click_iw({$sb_indx})");
        // 8/5/10
        print "\t\tvar fac_sym = '" . addslashes($fac_index) . "';\n";
        //	 for sidebar and icon 10/8/09 - 4/27/11
        $toroute = is_guest() || is_unit() ? "" : "&nbsp;<A HREF='{$_SESSION['routesfile']}?ticket_id=" . $fac_id . "'><U>Dispatch</U></A>";
        // 11/10/09, 7/27/10
        if (is_guest() || is_unit()) {
            // 7/27/10
            $facedit = $toroute = $facmail = "";
        } else {
            $facedit = "&nbsp;&nbsp;&nbsp;&nbsp;<A HREF='{$_SESSION['facilitiesfile']}?func=responder&edit=true&id=" . $row_fac['fac_id'] . "'><U>Edit</U></A>";
            $facmail = "&nbsp;&nbsp;&nbsp;&nbsp;<SPAN onClick = do_mail_fac_win('" . $row_fac['fac_id'] . "');><U><B>Email</B></U></SPAN>";
            $toroute = "&nbsp;<A HREF='{$_SESSION['facroutesfile']}?fac_id=" . $fac_id . "'><U>Route To Facility</U></A>";
            //	 8/2/08
        }
        if (my_is_float($row_fac['lat']) && my_is_float($row_fac['lng'])) {
            //			$f_disp_name = $row_fac['handle'];	//		10/8/09
            $facility_display_name = $f_disp_name = $row_fac['handle'];
            $the_bg_color = $GLOBALS['FACY_TYPES_BG'][$row_fac['icon']];
            // 2/8/10
            $the_text_color = $GLOBALS['FACY_TYPES_TEXT'][$row_fac['icon']];
            // 2/8/10
            $sidebar_fac_line = "<TD width='20%' onClick = '{$on_click}' TITLE = '" . $grp_names . addslashes($facility_display_name) . "' ALIGN='left'><SPAN STYLE='background-color:{$the_bg_color};  opacity: .7; color:{$the_text_color};' >" . addslashes(shorten($facility_display_name, 24)) . "</SPAN></TD>";
            //11/29/10, 3/15/11
            // MAIL
            if (may_email() && (is_email($row_fac['contact_email']) || is_email($row_fac['security_email']))) {
                // 7/2/10
                /*				$mail_link = "\t<TD width='5%' CLASS='mylink' ALIGN='left'>"
                					. "<IMG SRC='mail.png' width='10' height='10' BORDER=0 TITLE = 'click to email facility {$f_disp_temp[0]}'"
                					. " onclick = 'do_mail_win(\\\"{$f_disp_temp[0]},{$row_fac['contact_email']}\\\");'> "
                					. "</TD>";		// 4/26/09
                */
                // 5/19/11
                $mail_link = "\t<TD width='5%' CLASS='mylink' ALIGN='left'>" . "<IMG SRC='mail.png' width='10' height='10' BORDER=0 TITLE = 'click to email facility {$f_disp_name[0]}'" . " onclick = 'do_mail_win(\\\"{$f_disp_name[0]},{$row_fac['contact_email']}\\\");'> " . "</TD>";
                // 4/26/09
            } else {
                $mail_link = "\t<TD ALIGN='left'>na</TD>";
            }
            $sidebar_fac_line .= $mail_link;
            // STATUS
            $sidebar_fac_line .= "<TD width='20%'>" . get_status_sel($row_fac['fac_id'], $row_fac['fac_status_id'], "f") . "</TD>";
            // status, 3/15/11
            $sidebar_fac_line .= "<TD width='25%' ALIGN='left'  onClick = '{$on_click};' >&nbsp;&nbsp;&nbsp;" . addslashes(shorten($row_fac['fac_type_name'], 16)) . "</TD>";
            //			$sidebar_fac_line .= "<TD width='15%' ALIGN='left'  onClick = '{$on_click};' >" . addslashes($row_fac['status_val']) ."</TD>";
            $sidebar_fac_line .= "<TD width='20%' onClick = '{$on_click};' >&nbsp;" . format_sb_date($row_fac['updated']) . "</TD>";
            $fac_tab_1 = "<TABLE CLASS='infowin'  width='{$iw_width}' >";
            $fac_tab_1 .= "<TR CLASS='even'><TD COLSPAN=2 ALIGN='center'><B>" . addslashes(shorten($facility_display_name, 48)) . "</B></TD></TR>";
            $fac_tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'><B>" . addslashes(shorten($row_fac['fac_type_name'], 48)) . "</B></TD></TR>";
            $fac_tab_1 .= "<TR CLASS='even'><TD ALIGN='left'>Description:&nbsp;</TD><TD ALIGN='left'>" . replace_quotes(addslashes(str_replace($eols, " ", $row_fac['facility_description']))) . "</TD></TR>";
            $fac_tab_1 .= "<TR CLASS='odd'><TD ALIGN='left'>Status:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row_fac['status_val']) . " </TD></TR>";
            $fac_tab_1 .= "<TR CLASS='even'><TD ALIGN='left'>Contact:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row_fac['contact_name']) . "&nbsp;&nbsp;&nbsp;Email: " . addslashes($row_fac['contact_email']) . "</TD></TR>";
            $fac_tab_1 .= "<TR CLASS='odd'><TD ALIGN='left'>Phone:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row_fac['contact_phone']) . " </TD></TR>";
            $fac_tab_1 .= "<TR CLASS='even'><TD ALIGN='left'>As of:&nbsp;</TD><TD ALIGN='left'> " . format_date($row_fac['updated']) . "</TD></TR>";
            $fac_tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'>" . $facedit . $facmail . "&nbsp;&nbsp;&nbsp;&nbsp;<A HREF='{$_SESSION['facilitiesfile']}?func=responder&view=true&id=" . $row_fac['fac_id'] . "'><U>View</U></A></TD></TR>";
            //			$fac_tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'>" . $toroute . $facedit ."&nbsp;&nbsp;&nbsp;&nbsp;<A HREF='{$_SESSION['facilitiesfile']}?func=responder&view=true&id=" . $row_fac['fac_id'] . "'><U>View</U></A></TD></TR>";
            $fac_tab_1 .= "</TABLE>";
            $fac_tab_2 = "<TABLE CLASS='infowin'  width='{$iw_width}' >";
            $fac_tab_2 .= "<TR CLASS='odd'><TD ALIGN='left'>Security contact:&nbsp;</TD><TD ALIGN='left'>" . replace_quotes(addslashes($row_fac['security_contact'])) . " </TD></TR>";
            $fac_tab_2 .= "<TR CLASS='even'><TD ALIGN='left'>Security email:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row_fac['security_email']) . " </TD></TR>";
            $fac_tab_2 .= "<TR CLASS='odd'><TD ALIGN='left'>Security phone:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row_fac['security_phone']) . " </TD></TR>";
            $fac_tab_2 .= "<TR CLASS='even'><TD ALIGN='left'>Access rules:&nbsp;</TD><TD ALIGN='left'>" . replace_quotes(addslashes(str_replace($eols, " ", $row_fac['access_rules']))) . "</TD></TR>";
            $fac_tab_2 .= "<TR CLASS='odd'><TD ALIGN='left'>Security reqs:&nbsp;</TD><TD ALIGN='left'>" . replace_quotes(addslashes(str_replace($eols, " ", $row_fac['security_reqs']))) . "</TD></TR>";
            $fac_tab_2 .= "<TR CLASS='even'><TD ALIGN='left'>Opening hours:&nbsp;</TD><TD ALIGN='left'>" . replace_quotes(addslashes(str_replace($eols, " ", $row_fac['opening_hours']))) . "</TD></TR>";
            $fac_tab_2 .= "<TR CLASS='odd'><TD ALIGN='left'>Prim pager:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row_fac['pager_p']) . " </TD></TR>";
            $fac_tab_2 .= "<TR CLASS='even'><TD ALIGN='left'>Sec pager:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row_fac['pager_s']) . " </TD></TR>";
            $fac_tab_2 .= "</TABLE>";
            ?>
			var myfacinfoTabs = [
				new GInfoWindowTab("<?php 
            print replace_quotes(nl2brr(addslashes(shorten($row_fac['facility_name'], 10))));
            ?>
", "<?php 
            print $fac_tab_1;
            ?>
"),
				new GInfoWindowTab("More ...", "<?php 
            print str_replace($eols, " ", $fac_tab_2);
            ?>
")
				];
<?php 
            if ($row_fac['lat'] == 0.999999 && $row_fac['lng'] == 0.999999) {
                // check for facilities entered in no maps mode 7/28/10
                echo "var fac_icon = new GIcon(baseIcon);\n";
                echo "var fac_type = {$fac_type};\n";
                echo "var fac_type_name = \"{$fac_type_name}\";\n";
                echo "var region = \"{$fac_region}\";\n";
                echo "var fac_icon_url = \"./our_icons/question1.png\";\n";
                echo "fac_icon.image = fac_icon_url;\n";
                echo "var fac_point = new GLatLng(" . get_variable('def_lat') . "," . get_variable('def_lng') . ");\n";
                echo "var fac_marker = createfacMarker(fac_point, myfacinfoTabs, g, fac_icon, fac_type_name, region);\n";
                echo "map.addOverlay(fac_marker);\n";
                echo "\n";
            } else {
                echo "var fac_icon = new GIcon(baseIcon);\n";
                echo "var fac_type = {$fac_type};\n";
                echo "var fac_type_name = \"{$fac_type_name}\";\n";
                echo "var region = \"{$fac_region}\";\n";
                ?>
		var origin = ((fac_sym.length)>3)? (fac_sym.length)-3: 0;					// pick low-order three chars 3/22/11
		var iconStr = fac_sym.substring(origin);
<?php 
                echo "var fac_icon_url = \"./our_icons/gen_fac_icon.php?blank={$fac_type}&text=\" + (iconStr) + \"\";\n";
                echo "fac_icon.image = fac_icon_url;\n";
                echo "var fac_point = new GLatLng(" . $row_fac['lat'] . "," . $row_fac['lng'] . ");\n";
                echo "var fac_marker = createfacMarker(fac_point, myfacinfoTabs, g, fac_icon, fac_type_name, region);\n";
                echo "map.addOverlay(fac_marker);\n";
                echo "\n";
            }
            ?>
				if (fac_marker.isHidden()) {
					fac_marker.show();
				} else {
					fac_marker.hide();
				}
<?php 
        }
        //	 end if my_is_float
        ?>
			if(quick) {					//	 set up for facility edit - 11/27/09
				do_sidebar_fac_ed ("<?php 
        print $sidebar_fac_line;
        ?>
", g, fac_sym, fac_icon, fac_type_name);		
				}
			else {				//	 set up for facility infowindow
				do_sidebar_fac_iw ("<?php 
        print $sidebar_fac_line;
        ?>
", g, fac_sym, fac_icon, fac_type_name);
				}
			g++;
<?php 
        $sb_indx++;
        // zero-based - 6/30/10
    }
    // end while()
    //	$temp  = (string) ( round((microtime(true) - $time), 3));
    //	snap (__LINE__, $temp );
    ?>
	side_bar_html += "</TD></TR>\n";	//	11/29/10, 12/03/10

<?php 
    // =====================================End of functions to show facilities========================================================================
    ?>
	if (!(map_is_fixed)){
		if (!points) {		// any?
			map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
			}
		else {
			center = bounds.getCenter();
			zoom = map.getBoundsZoomLevel(bounds);
			map.setCenter(center,zoom);
			}			// end if/else (!points)
	}				// end if (!(map_is_fixed))
	
	side_bar_html +="</TABLE></TD></TR>\n";		//	3/15/11
	$("side_bar_f").innerHTML = side_bar_html;	//side_bar_html to facilities div
	
	side_bar_html ="<TABLE border='0' VALIGN='top' ALIGN='center' CLASS='sidebar' WIDTH = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.4));
    ?>
 >";	//	11/29/10, 3/15/11
	side_bar_html +="<TR CLASS='spacer'><TD CLASS='spacer' COLSPAN='99' ALIGN='center'>&nbsp;</TD></TR>";	//	11/29/10, 3/15/11
	side_bar_html +="<TR class='even'><TD ALIGN='center' COLSPAN=99><B>Facilities Legend</B></TD></TR>";		// legend row, 11/29/10, 3/15/11
	side_bar_html +="<TR class='even'><TD ALIGN='center' COLSPAN=99><?php 
    print get_facilities_legend();
    ?>
</TD></TR></TABLE>\n";	//	3/15/11
	$("facs_legend").innerHTML = side_bar_html + "</TABLE>";	//side_bar_html to facilities legend div

	side_bar_html = "";
	side_bar_html+="<TABLE><TR class='heading_2'><TH width = <?php 
    print $ctrls_width;
    ?>
 ALIGN='center'>Facilities</TH></TR><TR class='odd'><TD COLSPAN=99 CLASS='td_label' ><form action='#'>";			//	12/03/10, 3/15/11
<?php 
    if (!empty($fac_categories)) {
        function get_fac_icon($fac_cat)
        {
            // returns legend string
            $icons = $GLOBALS['fac_icons'];
            $sm_fac_icons = $GLOBALS['sm_fac_icons'];
            $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_types` WHERE `name` = \"{$fac_cat}\"";
            // types in use
            $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
            $print = "";
            while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
                $fac_icon = $row['icon'];
                $print .= "<IMG SRC = './our_icons/" . $sm_fac_icons[$fac_icon] . "' STYLE = 'vertical-align: middle'>";
            }
            unset($result);
            return $print;
        }
        foreach ($fac_categories as $key => $value) {
            //	12/03/10
            $curr_icon = get_fac_icon($value);
            ?>
			side_bar_html += "<DIV class='cat_button' onClick='set_fac_chkbox(\"<?php 
            print $value;
            ?>
\")'><?php 
            print get_fac_icon($value);
            ?>
&nbsp;&nbsp;<?php 
            print $value;
            ?>
: <input type=checkbox id='<?php 
            print $value;
            ?>
'  onClick='set_fac_chkbox(\"<?php 
            print $value;
            ?>
\")'/>&nbsp;&nbsp;&nbsp;</DIV>";			<!-- 12/03/10 -->
<?php 
        }
        $all = "fac_ALL";
        //	12/03/10
        $none = "fac_NONE";
        //	12/03/10
        ?>
	side_bar_html += "<DIV ID = 'fac_ALL_BUTTON'  class='cat_button' onClick='set_fac_chkbox(\"<?php 
        print $all;
        ?>
\")'><FONT COLOR = 'red'>ALL</FONT><input type=checkbox id='<?php 
        print $all;
        ?>
' onClick='set_fac_chkbox(\"<?php 
        print $all;
        ?>
\")'/></FONT></DIV>";			<!-- 12/03/10 -->
	side_bar_html += "<DIV ID = 'fac_NONE_BUTTON'  class='cat_button' onClick='set_fac_chkbox(\"<?php 
        print $none;
        ?>
\")'><FONT COLOR = 'red'>NONE</FONT><input type=checkbox id='<?php 
        print $none;
        ?>
' onClick='set_fac_chkbox(\"<?php 
        print $none;
        ?>
\")'/></FONT></DIV>";			<!-- 12/03/10 -->
	side_bar_html += "<DIV ID = 'fac_go_can' style='float:right; padding:2px;'><SPAN ID = 'fac_go_button' onClick='do_go_facilities_button()' class='conf_next_button' STYLE = 'display:none;'><U>Next</U></SPAN>";
	side_bar_html += "<SPAN ID = 'fac_can_button'  onClick='fac_cancel_buttons()' class='conf_can_button' STYLE = 'display:none;'><U>Cancel</U></SPAN></DIV>";
	side_bar_html+="</DIV></form></TD></TR></TABLE>";			<!-- 12/03/10, 3/15/11 -->
	$("fac_boxes").innerHTML = side_bar_html;										// 12/03/10 side_bar_html to responders div			

<?php 
    } else {
        function get_fac_icon($fac_cat)
        {
            // returns legend string
            $icons = $GLOBALS['fac_icons'];
            $sm_fac_icons = $GLOBALS['sm_fac_icons'];
            $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_types` WHERE `name` = \"{$fac_cat}\"";
            // types in use
            $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
            $print = "";
            while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
                $fac_icon = $row['icon'];
                $print .= "<IMG SRC = './our_icons/" . $sm_fac_icons[$fac_icon] . "' STYLE = 'vertical-align: middle'>";
            }
            unset($result);
            return $print;
        }
        foreach ($fac_categories as $key => $value) {
            //	12/03/10
            $curr_icon = get_fac_icon($value);
            ?>
			side_bar_html += "<DIV class='cat_button' STYLE='display: none;' onClick='set_fac_chkbox(\"<?php 
            print $value;
            ?>
\")'><?php 
            print get_fac_icon($value);
            ?>
&nbsp;&nbsp;<?php 
            print $value;
            ?>
: <input type=checkbox id='<?php 
            print $value;
            ?>
'  onClick='set_fac_chkbox(\"<?php 
            print $value;
            ?>
\")'/>&nbsp;&nbsp;&nbsp;</DIV>";			<!-- 12/03/10 -->
<?php 
        }
        $all = "fac_ALL";
        //	12/03/10
        $none = "fac_NONE";
        //	12/03/10
        ?>
	
	side_bar_html= "";		//	12/03/10
	side_bar_html+="<TABLE><TR class='heading_2'><TH width = <?php 
        print $ctrls_width;
        ?>
 ALIGN='center' COLSPAN='99'>Facilities</TH></TR><TR class='odd'><TD COLSPAN=99 CLASS='td_label'><form action='#'>";			//	12/03/10, 3/15/11
	side_bar_html += "<DIV class='cat_button' style='color: red;'>None Defined ! </DIV>";			<!-- 12/03/10, 3/15/11 -->
<?php 
        $all = "fac_ALL";
        //	12/03/10
        $none = "fac_NONE";
        //	12/03/10
        ?>
	side_bar_html += "<DIV ID = 'fac_ALL_BUTTON' class='cat_button' STYLE='display: none;'><input type=checkbox id='<?php 
        print $all;
        ?>
'/></DIV>";			<!-- 12/03/10 -->
	side_bar_html += "<DIV ID = 'fac_NONE_BUTTON' class='cat_button' STYLE='display: none;'><input type=checkbox id='<?php 
        print $none;
        ?>
'/></DIV>";			<!-- 12/03/10 -->
	side_bar_html += "</form></TD></TR></TABLE></DIV>";			<!-- 12/03/10 -->	
	$("fac_boxes").innerHTML = side_bar_html;										// 12/03/10 side_bar_html to responders div			

<?php 
    }
    //	------------------------------Buttons for boundaries show and hide
    $boundary_names = array();
    $bn = 0;
    // $query = "SELECT * FROM `$GLOBALS[mysql_prefix]mmarkup`";
    // $result = mysql_query($query)or do_error($query, mysql_error(), basename(__FILE__), __LINE__);
    // while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {;
    // $boundary_names[$bn] = $row['line_name'];
    // $bn++;
    // }
    foreach ($all_boundaries as $key => $value) {
        $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}mmarkup` WHERE `id`='{$value}'";
        $result = mysql_query($query) or do_error($query, mysql_error(), basename(__FILE__), __LINE__);
        while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
            $boundary_names[$bn] = $row['line_name'];
            $bn++;
        }
    }
    ?>
	side_bar_html= "";		//	6/10/11
	side_bar_html+="<TABLE><TR class='heading_2'><TH width = <?php 
    print $ctrls_width;
    ?>
 ALIGN='center'>Boundaries and Fences</TH></TR><TR class='odd'><TD COLSPAN=99 CLASS='td_label' ><form action='#'>";			//		6/10/11

<?php 
    $counter = count($boundary_names);
    if ($counter == 0) {
        ?>
		side_bar_html += "<DIV class='cat_button' STYLE='display: none;'>No Boundaries</DIV>";			<!-- 6/10/11 -->
		side_bar_html += "<DIV class='cat_button' style='color: red;'>None Defined ! </DIV>";			<!-- 6/10/11 -->
		side_bar_html +="</form></TD></TR></TABLE></DIV>";			<!-- 6/10/11 -->
<?php 
    } else {
        foreach ($boundary_names as $key => $value) {
            // 6/10/11
            ?>
		side_bar_html += "<DIV class='cat_button' onClick='set_bnd_chkbox(\"<?php 
            print $value;
            ?>
\")'><?php 
            print $value;
            ?>
: <input type=checkbox id='<?php 
            print $value;
            ?>
' onClick='set_bnd_chkbox(\"<?php 
            print $value;
            ?>
\")'/>&nbsp;&nbsp;&nbsp;</DIV>";			<!--6/10/11 -->
<?php 
        }
        $all = "BND_ALL";
        //	6/10/11
        $none = "BND_NONE";
        //	6/10/11
        ?>
		side_bar_html += "<DIV ID = 'BND_ALL_BUTTON' class='cat_button' onClick='set_bnd_chkbox(\"<?php 
        print $all;
        ?>
\")'><FONT COLOR = 'red'>ALL</FONT><input type=checkbox id='<?php 
        print $all;
        ?>
' onClick='set_bnd_chkbox(\"<?php 
        print $all;
        ?>
\")'/></FONT></DIV>";			<!-- 6/10/11 -->
		side_bar_html += "<DIV ID = 'BND_NONE_BUTTON' class='cat_button'  onClick='set_bnd_chkbox(\"<?php 
        print $none;
        ?>
\")'><FONT COLOR = 'red'>NONE</FONT><input type=checkbox id='<?php 
        print $none;
        ?>
' onClick='set_bnd_chkbox(\"<?php 
        print $none;
        ?>
\")'/></FONT></DIV>";			<!-- 6/10/11 -->
		side_bar_html += "<DIV ID = 'bnd_go_can' style='float:right; padding:2px;'><SPAN ID = 'bnd_go_button' onClick='do_go_bnd_button()' class='conf_next_button' STYLE = 'display:none;'><U>Next</U></SPAN>";
		side_bar_html += "<SPAN ID = 'bnd_can_button'  onClick='bnd_cancel_buttons()' class='conf_can_button' STYLE = 'display:none;'><U>Cancel</U></SPAN></DIV>";
		side_bar_html+="</form></TD></TR></TABLE>";			<!-- 6/10/11 -->
<?php 
    }
    ?>
	$("poly_boxes").innerHTML = side_bar_html;										// 12/03/10 side_bar_html to responders div	
<?php 
    //	---------------------------end of Buttons for boundaries show and hide
    // code below revised 11/29/10 to remove scheduled / current buttons and repair faulty display of facilities
    //	$query = "SELECT * FROM `$GLOBALS[mysql_prefix]ticket` WHERE `problemend` IS NOT NULL ";		// 10/21/09
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE `status` = 1 ";
    // 10/21/09
    $result_ct = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $num_closed = mysql_num_rows($result_ct);
    unset($result_ct);
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE `status` = 3 ";
    // 10/21/09
    $result_scheduled = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $num_scheduled = mysql_num_rows($result_scheduled);
    unset($result_scheduled);
    if (!empty($addon)) {
        print "\n\tside_bar_html +=\"" . $addon . "\"\n";
    }
    do_kml();
    // kml display - 6/28/11
    ?>
// =============================================================================================================
	}		// end if (GBrowserIsCompatible())
else {
	alert("Sorry, browser compatibility problem. Contact your tech support group.");
	}
	
function tester() {
	alert("2093 " + gmarkers.length);
	for (i=0; i<gmarkers.length; i++) {
		alert("2095 " + i + " " + gmarkers[i]['x']);
		}
	}
</SCRIPT>

<?php 
    //	snap(__LINE__, round((microtime(true) - $time), 3));
    echo "Elapsed: " . round(microtime(true) - $time, 3) . "s";
}
function do_list($unit_id = "", $capabilities = "", $searchtype)
{
    // 12/18/10
    global $unav_id_str, $row_ticket, $dispatches_disp, $dispatches_act, $from_top, $eol, $sidebar_width, $sortby_distance;
    $conversion = get_dist_factor();
    // KM vs mi - 11/23/10
    switch ($row_ticket['severity']) {
        //color tickets by severity
        case $GLOBALS['SEVERITY_MEDIUM']:
            $severityclass = 'severity_medium';
            break;
        case $GLOBALS['SEVERITY_HIGH']:
            $severityclass = 'severity_high';
            break;
        case $GLOBALS['SEVERITY_NORMAL']:
            $severityclass = 'severity_normal';
            break;
        default:
            dump(basename(__FILE__) . "/" . __LINE__);
            break;
    }
    $query = "SELECT *,UNIX_TIMESTAMP(problemstart) AS problemstart,UNIX_TIMESTAMP(problemend) AS problemend,\n\t\t\tUNIX_TIMESTAMP(booked_date) AS booked_date,\n\t\t\tUNIX_TIMESTAMP(date) AS date,UNIX_TIMESTAMP(`{$GLOBALS['mysql_prefix']}ticket`.`updated`) AS updated,\n\t\t\t`{$GLOBALS['mysql_prefix']}ticket`.`description` AS `tick_descr` \n\t\t\tFROM `{$GLOBALS['mysql_prefix']}ticket`  \n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}in_types` `ty` ON (`{$GLOBALS['mysql_prefix']}ticket`.`in_types_id` = `ty`.`id`)\t\t\n\t\t\tWHERE `{$GLOBALS['mysql_prefix']}ticket`.`id`=" . get_ticket_id() . " LIMIT 1";
    // 7/24/09 10/16/08 Incident location 09/25/09 Pre Booking
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $row_ticket = stripslashes_deep(mysql_fetch_array($result));
    $facility = $row_ticket['facility'];
    $rec_fac = $row_ticket['rec_facility'];
    if ($row_ticket['lat'] == 0.999999 && $row_ticket['lng'] == 0.999999) {
        // check for tickets created in no-maps mode 8/4/10
        $lat = get_variable('def_lat');
        $lng = get_variable('def_lng');
    } else {
        $lat = $row_ticket['lat'];
        $lng = $row_ticket['lng'];
    }
    // end check for tickets created in no-maps mode
    //	print "var thelat = " . $lat . ";\nvar thelng = " . $lng . ";\n";		// set js-accessible location data
    unset($result);
    if ($rec_fac > 0) {
        $query_rfc = "SELECT * FROM `{$GLOBALS['mysql_prefix']}facilities` WHERE `id`= {$rec_fac} ";
        // 7/24/09 10/16/08 Incident location 10/06/09 Multi point routing
        $result_rfc = mysql_query($query_rfc) or do_error($query_rfc, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        $row_rec_fac = stripslashes_deep(mysql_fetch_array($result_rfc));
        $rf_lat = $row_rec_fac['lat'];
        $rf_lng = $row_rec_fac['lng'];
        $rf_name = $row_rec_fac['name'];
        //		print "var thereclat = " . $rf_lat . ";\nvar thereclng = " . $rf_lng . ";\n";		// set js-accessible location data for receiving facility
    } else {
        //		print "var thereclat;\nvar thereclng;\n";		// set js-accessible location data for receiving facility
    }
    ?>
	<SCRIPT>
		var color=0;
		var last_from;
		var last_to;
		var rec_fac;
		var current_id;			// 10/25/08
		var output_direcs = "";	//10/6/09
		var have_direcs = 0;	//10/6/09
		var tick_name = "<?php 
    print $row_ticket['scope'];
    ?>
";	// 3/15/11
	
		if (GBrowserIsCompatible()) {
			var colors = new Array ('odd', 'even');
			
			var Direcs = null;			// global
			var Now;
			var mystart;
			var myend;
		    function setDirections(fromAddress, toAddress, recfacAddress, locale, unit_id) {	//10/6/09

				if (document.routes_Form.frm_allow_dirs.value==='false') {return false;}		// 11/21/09
				
				$("mail_button").style.display = "none";			//10/6/09
				$("loading").style.display = "inline-block";		// 10/28/09
	
				$("directions_ok_no").style.display = "none";
				$("loading_2").style.display = "inline-block";
				
			    last_from = fromAddress;
			    last_to = toAddress;
				rec_fac = recfacAddress;
				f_unit = unit_id;	//10/6/09
				G_START_ICON.image = "./our_icons/sm_white.png";
				G_START_ICON.iconSize = new GSize(12,20); 
				G_END_ICON.image = "./our_icons/sm_white.png";
				G_END_ICON.iconSize = new GSize(12,20);         	
	
				Now = new Date();      				// Grab the current date.
				mystart = Now.getTime(); 		// Initialize variable Start
		
				if (rec_fac != "") {	//10/6/09
				    	var Direcs = gdir.load("from: " + fromAddress + " to: " + toAddress + " to: " + recfacAddress, { "locale": locale, preserveViewport : true  });
						}
					else{
				    	var Direcs = gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale, preserveViewport : true  });
						}

					GEvent.addListener(Direcs, "addoverlay", GEvent.callback(Direcs, cb2())); 		// 11/21/09
			    	}		// end function set Directions()
	
			function cb2() {                               // callback function 10/6/09
				var output_direcs = "";
				for ( var i = 0; i < gdir.getNumRoutes(); i++) {        // Traverse all routes - not really needed here, but ...
					var groute = gdir.getRoute(i);
					var distanceTravelled = 0;             // if you want to start summing these
	 
					for ( var j = 0; j < groute.getNumSteps(); j++) {                // Traverse the steps this route
						var gstep = groute.getStep(j);
						var directions_text =  gstep.getDescriptionHtml();
						var directions_dist = gstep.getDistance().html;
						output_direcs = output_direcs + directions_text + " " + directions_dist + ". " + "\n";
						}
					}
				output_direcs = output_direcs.replace("<div class=\"google_note\">", "\n -");	//10/6/09
				output_direcs = output_direcs.replace("Destination", "\n***Destination");	//10/6/09
				output_direcs = output_direcs.replace("&nbsp:", " ");	//10/6/09
				document.email_form.frm_direcs.value = output_direcs;	//10/6/09
				document.email_form.frm_u_id.value = f_unit;	//10/6/09
				document.email_form.frm_scope.value = tick_name;	//10/29/09

				have_direcs = 1;	//10/6/09
				$("mail_button").style.display = "inline-block";	//10/6/09
				$("loading").style.display = "none";		// 10/28/09	
				$("loading_2").style.display = "none";
				$("directions_ok_no").style.display = "inline-block";			
				}                // end function cb2()
	
			function mail_direcs(f) {	//10/6/09
				f.target = 'Mail Form'
				newwindow_mail=window.open('',f.target,'titlebar, location=0, resizable=1, scrollbars, height=360,width=600,status=0,toolbar=0,menubar=0,location=0, left=100,top=300,screenX=100,screenY=300');
				if (isNull(newwindow_mail)) {
					alert ("Email edit operation requires popups to be enabled -- please adjust your browser options.");
					return;
					}
				newwindow_mail.focus();
				f.submit();
				return false;
				}
		
			function do_sidebar(sidebar, color, id, unit_id) {						// No map
				var letter = ""+ id;										// start with 1 - 1/5/09 - 1/29/09
				marker = null;
				gmarkers[id] = null;										// marker to array for side bar click function
		
				side_bar_html += "<TR ID = '_tr" + id  + "' CLASS='" + colors[(id+1)%2] +"' VALIGN='bottom' onClick = myclick(" + id + "," + unit_id +");><TD>";
	
				side_bar_html += "<IMG BORDER=0 SRC='rtarrow.gif' ID = \"R" + id + "\"  STYLE = 'visibility:hidden;' /></TD>";
				var letter = ""+ id;										// start with 1 - 1/5/09 - 1/29/09
	
	//			var the_class = (direcs[id])?  "emph" : "td_label";
				var the_class = (lats[id])?  "emph" : "td_label";
				side_bar_html += "<TD CLASS='" + the_class + "' ALIGN='right'>" + letter + " "+ sidebar +"</TD></TR>\n";
				return null;
				}				// end function create Marker()
	
	
			function createMarker(point,sidebar,tabs, color, id, unit_id) {		// Creates marker and sets up click event infowindow
				do_sidebar(sidebar, color, id, unit_id)
				var icon = new GIcon(listIcon);
				var uid = unit_id;
				var letter = ""+ id;
											// start with 1 - 1/5/09 - 1/29/09
				var icon_url = "./our_icons/gen_icon.php?blank=" + escape(icons[color]) + "&text=" + letter;				// 1/5/09
		
				icon.image = icon_url;		// ./our_icons/gen_icon.php?blank=4&text=zz"
				var marker = new GMarker(point, icon);
				marker.id = color;				// for hide/unhide - unused
			
				GEvent.addListener(marker, "click", function() {		// here for both side bar and icon click
					map.closeInfoWindow();
					which = id;
					gmarkers[which].hide();
					marker.openInfoWindowTabsHtml(infoTabs[id]);
					var dMapDiv = document.getElementById("detailmap");
					var detailmap = new GMap2(dMapDiv);
					detailmap.addControl(new GSmallMapControl());
					detailmap.setCenter(point, 17);  					// larger # = closer
					detailmap.addOverlay(marker);
					});
			
				gmarkers[id] = marker;							// marker to array for side bar click function
				infoTabs[id] = tabs;							// tabs to array
				bounds.extend(point);							// extend the bounding box		
		
				return marker;
				}				// end function create Marker()
				
			function createdummyMarker(point,sidebar,tabs, color, id, unit_id) {		// Creates marker and sets up click event infowindow
				do_sidebar(sidebar, color, id, unit_id)
				var icon = new GIcon(listIcon);
				var uid = unit_id;
				var letter = ""+ id;
											// start with 1 - 1/5/09 - 1/29/09
				var icon_url = "./our_icons/question1.png";				// 1/5/09
				icon.image = icon_url;
				var marker = new GMarker(point, icon);
				marker.id = color;				// for hide/unhide - unused
			
				GEvent.addListener(marker, "click", function() {		// here for both side bar and icon click
					map.closeInfoWindow();
					which = id;
					gmarkers[which].hide();
					marker.openInfoWindowTabsHtml(infoTabs[id]);
					var dMapDiv = document.getElementById("detailmap");
					var detailmap = new GMap2(dMapDiv);
					detailmap.addControl(new GSmallMapControl());
					detailmap.setCenter(point, 17);  					// larger # = closer
					detailmap.addOverlay(marker);
					});
			
				gmarkers[id] = marker;							// marker to array for side bar click function
				infoTabs[id] = tabs;							// tabs to array
				bounds.extend(point);							// extend the bounding box		
		
				return marker;
				}				// end function create Marker()				
		
			function myclick(id, unit_id) {								// responds to side bar click
				var norecfac = "";
				if (document.getElementById(current_id)) {
					document.getElementById(current_id).style.visibility = "hidden";			// hide last check if defined
					}
				current_id= "R"+id;
				document.getElementById(current_id).style.visibility = "visible";			// show newest
				if (lats[id]) {																// position data?
					$('mail_dir_but').style.visibility = "visible";			// 11/12/09	
<?php 
    if ($lat == 0.999999 && $lng == 0.999999) {
        // test of tickets entered in no-maps mode 8/4/10
        ?>
					
						var thelat = <?php 
        print get_variable('def_lat');
        ?>
; var thelng = <?php 
        print get_variable('def_lng');
        ?>
;		// coords of click point
<?php 
    } else {
        ?>
						var thelat = <?php 
        print $lat;
        ?>
; var thelng = <?php 
        print $lng;
        ?>
;		// coords of click point
<?php 
    }
    // end of test of tickets entered in no-maps mode 8/4/10
    if ($row_ticket['rec_facility'] > 0) {
        ?>
			
						var thereclat = <?php 
        print $rf_lat;
        ?>
; var thereclng = <?php 
        print $rf_lng;
        ?>
;									//adds in receiving facility
						if (direcs[id]) {
							setDirections(lats[id] + " " + lngs[id], thelat + " " + thelng, thereclat + " " + thereclng, "en_US", unit_id);	// get directions
							}
<?php 
    } else {
        ?>
			
						if (direcs[id]) {
							setDirections(lats[id] + " " + lngs[id], thelat + " " + thelng, norecfac, "en_US", unit_id);					// get directions
							}
<?php 
    }
    ?>
					}
				else {
					$('directions').innerHTML = "";							// no position data, no directions
					$('mail_dir_but').style.visibility = "hidden";			// 11/12/09	 -	
					}
	
				$("directions").innerHTML= "";								// prior directions no longer apply - 11/21/09
				if (gdir) {	gdir.clear();}

				}					// end function my click(id)
	
			var the_grid;
			var grid = false;
			function doGrid() {
				if (grid) {
					map.removeOverlay(the_grid);
					}
				else {
					the_grid = new LatLonGraticule();
					map.addOverlay(the_grid);
					}
				grid = !grid;
				}			// end function doGrid
				
		    var trafficInfo = new GTrafficOverlay();
		    var toggleState = true;
		
			function doTraffic() {				// 10/16/08
				if (toggleState) {
			        map.removeOverlay(trafficInfo);
			     	} 
				else {
			        map.addOverlay(trafficInfo);
			    	}
		        toggleState = !toggleState;			// swap
			    }				// end function doTraffic()
		
			var starting = false;
	
			function sv_win(theLat, theLng) {				// 8/17/09
				if(starting) {return;}						// dbl-click proof
				starting = true;					
	//			alert(622);
				var url = "street_view.php?thelat=" + theLat + "&thelng=" + theLng;
				newwindow_sl=window.open(url, "sta_log",  "titlebar=no, location=0, resizable=1, scrollbars, height=450,width=640,status=0,toolbar=0,menubar=0,location=0, left=100,top=300,screenX=100,screenY=300");
				if (!(newwindow_sl)) {
					alert ("Street view operation requires popups to be enabled. Please adjust your browser options - or else turn off the Call Board option.");
					return;
					}
				newwindow_sl.focus();
				starting = false;
				}		// end function sv win()
	
			
			function handleErrors(){		//G_GEO_UNKNOWN_DIRECTIONS 	
				if (gdir.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS ) {
					alert("501: directions unavailable\n\nClick map point for directions.");
					}
				else if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
					alert("440: No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
				else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
					alert("442: A map request could not be processed, reason unknown.\n Error code: " + gdir.getStatus().code);
				else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
					alert("444: Technical error.\n Error code: " + gdir.getStatus().code);
				else if (gdir.getStatus().code == G_GEO_BAD_KEY)
					alert("448: The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
				else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
					alert("450: A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
				else alert("451: An unknown error occurred.");
				}		// end function handleErrors()
	
			function onGDirectionsLoad(){ 
	//			var temp = gdir.getSummaryHtml();
				}		// function onGDirectionsLoad()
	
			function guest () {
				alert ("Demonstration only.  Guests may not commit dispatch!");
				}
				
			function validate(){		// frm_id_str
				msgstr="";
				for (var i =1;i<unit_sets.length;i++) {				// 3/30
					if (unit_sets[i]) {
						msgstr+=unit_names[i]+"\n";
						document.routes_Form.frm_id_str.value += unit_ids[i] + "|";
						}
					}
				if (msgstr.length==0) {
					var more = (nr_units>1)? "s": ""
					alert ("Please select unit" + more + ", or cancel");
					return false;
					}
				else {
					var quick = <?php 
    print intval(get_variable("quick") == 1) ? "true;\n" : "false;\n";
    ?>
				
					if ((quick) || (confirm ("Please confirm unit dispatch\n\n" + msgstr))) {		// 11/23/09
	
						document.routes_Form.frm_id_str.value = document.routes_Form.frm_id_str.value.substring(0, document.routes_Form.frm_id_str.value.length - 1);	// drop trailing separator
						document.routes_Form.frm_name_str.value = msgstr;	// for re-use
						document.routes_Form.submit();
	//					document.getElementById("outer").style.display = "none";		4/26/10
						document.getElementById("bottom").style.display = "block";					
						}
					else {
						document.routes_Form.frm_id_str.value="";	
						return false;
						}
					}
	
				}		// end function validate()
		
			function exists(myarray,myid) {
				var str_key = " " + myid;		// force associative
				return ((typeof myarray[str_key])!="undefined");		// exists if not undefined
				}		// end function exists()
				
			var icons=[];						// note globals
<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}unit_types` ORDER BY `id`";
    // types in use
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $icons = $GLOBALS['icons'];
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // map type to blank icon id
        $blank = $icons[$row['icon']];
        print "\ticons[" . $row['id'] . "] = " . $row['icon'] . ";\n";
        //
    }
    unset($result);
    ?>
			var map;
			var center;
			var zoom;
			
		    var gdir;				// directions
		    var geocoder = null;
		    var addressMarker;
			$("mail_button").style.display = "none";		// 10/28/09
			$("loading").style.display = "none";		// 10/28/09		
			
			var side_bar_html = "<TABLE border=0 CLASS='sidebar' ID='tbl_responders' STYLE = 'WIDTH: <?php 
    print $sidebar_width;
    ?>
px;'>";
	
			var gmarkers = [];
			var infoTabs = [];
			var lats = [];
			var lngs = [];
			var unit_names = [];		// names 
			var unit_sets = [];			// settings
			var unit_ids = [];			// id's
			var unit_assigns =  [];		// unit id's assigned this incident
			var direcs =  [];			// if true, do directions - 7/13/09
	
			var which;			// marker last selected
			var i = 0;			// sidebar/icon index
			map = new GMap2(document.getElementById("map_canvas"));		// create the map
			map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
//			map.addControl(new GSmallMapControl());						// 9/23/08
			map.setUIToDefault();										// 8/13/10
			map.addControl(new GMapTypeControl());
			var bounds = new GLatLngBounds();						// create empty bounding box			
			
			do_landb();				// 8/1/11 - show scribbles				
<?php 
    if (intval(get_variable('terrain')) == 1) {
        ?>
				map.addMapType(G_PHYSICAL_MAP);
<?php 
    }
    ?>
	
	
			gdir = new GDirections(map, document.getElementById("directions"));
			
			GEvent.addListener(gdir, "load", onGDirectionsLoad);
			try {GEvent.addListener(gdir, "error", handleErrors);}
			catch (e) {}
		
			var listIcon = new GIcon();
			listIcon.image = "./markers/yellow.png";	// yellow.png - 16 X 28
			listIcon.shadow = "./markers/sm_shadow.png";
			listIcon.iconSize = new GSize(20, 34);
			listIcon.shadowSize = new GSize(37, 34);
			listIcon.iconAnchor = new GPoint(8, 28);
			listIcon.infoWindowAnchor = new GPoint(9, 2);
			listIcon.infoShadowAnchor = new GPoint(18, 25);
		
			var newIcon = new GIcon();
			newIcon.image = "./markers/white.png";	// yellow.png - 20 X 34
			newIcon.shadow = "./markers/shadow.png";
			newIcon.iconSize = new GSize(20, 34);
			newIcon.shadowSize = new GSize(37, 34);
			newIcon.iconAnchor = new GPoint(8, 28);
			newIcon.infoWindowAnchor = new GPoint(9, 2);
			newIcon.infoShadowAnchor = new GPoint(18, 25);
																		// set Incident position
			var point = new GLatLng(<?php 
    print $lat;
    ?>
, <?php 
    print $lng;
    ?>
);	// 675
			bounds.extend(point);										// Incident into BB
		
			GEvent.addListener(map, "infowindowclose", function() {		// re-center after  move/zoom

				setDirections(last_from, last_to, "en_US") ;

				});
			var accept_click = false;					// 10/15/08
			GEvent.addListener(map, "click", function(marker, point) {		// point.lat()
				var the_start = point.lat().toString() + "," + point.lng().toString();
				var the_end = thelat.toString() + "," + thelng.toString();	
				setDirections(the_start, the_end, "en_US");
				});				// end GEvent.addListener()
	
			var nr_units = 	0;
			var email= false;
			
<?php 
    function get_cd_str($in_row)
    {
        // unit row in,
        global $unit_id;
        //																			// first, already on this run?
        $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` WHERE  `ticket_id` = " . get_ticket_id() . "\n\t\t\t\t\t AND (`responder_id`={$in_row['unit_id']}) \n\t\t\t\t\t AND ((`clear` IS NULL) OR (DATE_FORMAT(`clear`,'%y') = '00')) LIMIT 1;";
        // 6/25/10
        $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        if (mysql_affected_rows() == 1) {
            return " CHECKED DISABLED ";
        }
        if ($unit_id != "" && (mysql_affected_rows() != 1 || mysql_affected_rows() == 1 && intval($in_row['multi']) == 1)) {
            print "checked";
            return " CHECKED ";
        }
        // 12/18/10 - Checkbox checked here individual unit seleted.
        if (intval($in_row['dispatch']) == 2) {
            return " DISABLED ";
        }
        // 2nd, disallowed  - 5/30/10
        if (intval($in_row['multi']) == 1) {
            return "";
        }
        // 3rd, allowed
        $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\t\t\t\tWHERE `responder_id`={$in_row['unit_id']} \n\t\t\t\t\tAND ((`clear` IS NULL) OR (DATE_FORMAT(`clear`,'%y') = '00'))\n\t\t\t\t\tLIMIT 1;";
        // 6/25/10
        $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        if (mysql_affected_rows() == 1) {
            return " DISABLED ";
        } else {
            return "";
        }
    }
    // function get cd_str($in_row)
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    // build js array of responders to this ticket - possibly none
    $query = "SELECT `ticket_id`, `responder_id` \n\t\t\t\tFROM `{$GLOBALS['mysql_prefix']}assigns` WHERE `ticket_id` = " . get_ticket_id();
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($assigns_row = stripslashes_deep(mysql_fetch_array($result))) {
        print "\t\tunit_assigns[' '+ " . $assigns_row['responder_id'] . "]= true;\n";
        // note string forced
    }
    print "\n";
    // ===================================================================================
    $query = "SELECT *, UNIX_TIMESTAMP(problemstart) AS problemstart, UNIX_TIMESTAMP(problemend) AS problemend \n\t\t\t\tFROM `{$GLOBALS['mysql_prefix']}ticket` \n\t\t\t\tWHERE `id`= " . get_ticket_id() . " LIMIT 1;";
    // 4/5/10
    $result_pos = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    if (mysql_affected_rows() == 1) {
        $row_position = stripslashes_deep(mysql_fetch_array($result_pos));
        $latitude = $row_position['lat'];
        $longitude = $row_position['lng'];
        $problemstart = $row_position['problemstart'];
        $problemend = $row_position['problemend'];
        unset($result_pos);
    } else {
        //			dump ($query);
    }
    $where = empty($unit_id) ? "" : " AND `r`.`id` = {$unit_id} ";
    // revised 5/23/08 per AD7PE
    //			$where2 = (empty($capabilities))? "" : " AND (";	// 12/18/10
    if (!empty($unit_id)) {
        $where2 = "";
    } else {
        $where2 = empty($capabilities) ? "" : " AND (";
        // 12/18/10
        $searchitems = empty($capabilities) ? "" : explode(" ", $capabilities);
        if ($searchitems) {
            for ($j = 0; $j < count($searchitems); $j++) {
                if ($j + 1 != count($searchitems)) {
                    $where2 .= "`r`.`capab` LIKE '%{$searchitems[$j]}%' {$searchtype}";
                } else {
                    $where2 .= "`r`.`capab` LIKE '%{$searchitems[$j]}%')";
                }
            }
        }
    }
    switch (intval(trim(get_variable('locale')))) {
        // nm conversion, 3/15/11
        case 0:
            $nm_to_what = 1.1515;
            // mi
            $capt = "mi";
            break;
        case 1:
            $nm_to_what = 1.1515 * 1.609344;
            // UK - km
            $capt = "km";
            break;
        case 2:
            $nm_to_what = 1.1515 * 1.609344;
            // ROW - km
            $capt = "km";
            break;
        default:
            $nm_to_what = 1.1515 * 1.609344;
            // ERROR?
            $capt = "km";
            break;
    }
    $have_position = !($latitude == 0.999999 && $longitude == 0.999999);
    $by_distance = $sortby_distance && $have_position ? "`distance` ASC, " : "";
    // 6/19/10 - user-set variable, 2/5/11 calls assigned added as order element
    // 5/30/10, 11/24/10
    // ============================= Regions Stuff
    // Allows Tickets to be dispatched to any responders in the same region as the current user.
    // $query = "SELECT * FROM `$GLOBALS[mysql_prefix]allocates` WHERE `type`= 4 AND `resource_id` = '$_SESSION[user_id]' ORDER BY `id` ASC;";	// 4/18/11
    // $result = mysql_query($query);	// 5/4/11
    // $al_groups = array();
    // $al_names = "";
    // while ($row = stripslashes_deep(mysql_fetch_assoc($result))) 	{	// 5/4/11
    // $al_groups[] = $row['group'];
    // $query2 = "SELECT * FROM `$GLOBALS[mysql_prefix]region` WHERE `id`= '$row[group]';";	// 5/4/11
    // $result2 = mysql_query($query2);	// 5/4/11
    // while ($row2 = stripslashes_deep(mysql_fetch_assoc($result2))) 	{	// 5/4/11
    // $al_names .= $row2['group_name'] . ", ";
    // }
    // }
    // if(isset($_SESSION['viewed_groups'])) {
    // $al_groups= explode(",",$_SESSION['viewed_groups']);
    // }
    // if(!isset($_SESSION['viewed_groups'])) {	//	5/4/11
    // $x=0;
    // $where3 = "AND (";
    // foreach($al_groups as $grp) {
    // $where4 = (count($al_groups) > ($x+1)) ? " OR " : ")";
    // $where3 .= "`a`.`group` = '{$grp}'";
    // $where3 .= $where4;
    // $x++;
    // }
    // } else {
    // $x=0;
    // $where3 = "AND (";
    // foreach($al_groups as $grp) {
    // $where4 = (count($al_groups) > ($x+1)) ? " OR " : ")";
    // $where3 .= "`a`.`group` = '{$grp}'";
    // $where3 .= $where4;
    // $x++;
    // }
    // }
    // $where3 .= " AND `a`.`type` = 2";
    // Replacement code - only allows Tickets to be dispatched to responders in the same region
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 1 AND `resource_id` = " . get_ticket_id() . " ORDER BY `id` ASC;";
    // 4/18/11
    $result = mysql_query($query);
    // 5/4/11
    $al_groups = array();
    $al_names = "";
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // 5/4/11
        $al_groups[] = $row['group'];
        $query2 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}region` WHERE `id`= '{$row['group']}';";
        // 5/4/11
        $result2 = mysql_query($query2);
        // 5/4/11
        while ($row2 = stripslashes_deep(mysql_fetch_assoc($result2))) {
            // 5/4/11
            $al_names .= $row2['group_name'] . ", ";
        }
    }
    $x = 0;
    $where3 = "AND (";
    foreach ($al_groups as $grp) {
        $where4 = count($al_groups) > $x + 1 ? " OR " : ")";
        $where3 .= "`a`.`group` = '{$grp}'";
        $where3 .= $where4;
        $x++;
    }
    $where3 .= " AND `a`.`type` = 2";
    // ================================ end of regions stuff
    $query = "(SELECT *, UNIX_TIMESTAMP(`updated`) AS `updated`, `r`.`name` AS `unit_name`, `t`.`name` AS `type_name`, `r`.`type` AS `type`,\n\t\t\t\t`r`.`id` AS `unit_id`, `r`.`capab` AS `capab`,\n\t\t\t\t`s`.`status_val` AS `unitstatus`, `contact_via`, \n\t\t\t\t(((acos(sin(({$latitude}*pi()/180)) * sin((`r`.`lat`*pi()/180))+cos(({$latitude}*pi()/180)) * cos((`r`.`lat`*pi()/180)) * cos((({$longitude} - `r`.`lng`)*pi()/180))))*180/pi())*60*{$nm_to_what}) AS `distance`,\n\t\t\t\t(SELECT  COUNT(*) as numfound FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\t\t\t\tWHERE `{$GLOBALS['mysql_prefix']}assigns`.`responder_id` = `r`.`id`  \n\t\t\t\t\tAND `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' )\n\t\t\t\t\tAS `calls_assigned`\t\t\t\n\t\t\t\t\n\t\t\t\tFROM `{$GLOBALS['mysql_prefix']}responder` `r`\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}un_status` `s` ON (`r`.`un_status_id` = `s`.`id`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}unit_types` `t` ON (`r`.`type` = `t`.`id`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON (`r`.`id` = `a`.`resource_id`)\t\t\t\t\t\n\t\t\t\t WHERE  `dispatch` = 0 {$where} {$where2} {$where3} GROUP BY unit_id )\n\t\t\tUNION DISTINCT\n\t\t\t\t(SELECT *, UNIX_TIMESTAMP(`updated`) AS `updated`, `r`.`name` AS `unit_name`, `t`.`name` AS `type_name`, `r`.`type` AS `type`,\n\t\t\t\t`r`.`id` AS `unit_id`, `r`.`capab` AS `capab`,\n\t\t\t\t`s`.`status_val` AS `unitstatus`, `contact_via`, \n\t\t\t\t9999 AS `distance`,\n\t\t\t\t(SELECT  COUNT(*) as numfound FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\t\t\t\tWHERE `{$GLOBALS['mysql_prefix']}assigns`.`responder_id` = `r`.`id`  \n\t\t\t\t\tAND `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' ) \n\t\t\t\t\tAS `calls_assigned`\t\t\t\n\t\t\t\t\n\t\t\t\tFROM `{$GLOBALS['mysql_prefix']}responder` `r`\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}un_status` `s` ON (`r`.`un_status_id` = `s`.`id`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}unit_types` `t` ON (`r`.`type` = `t`.`id`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON (`r`.`id` = `a`.`resource_id`)\t\t\t\t\t\n\t\t\t\t WHERE  `dispatch` > 0 {$where} {$where2} {$where3} GROUP BY unit_id )\n\t\t\t ORDER BY `dispatch` ASC, `calls_assigned` ASC, {$by_distance} `handle` ASC, `unit_name` ASC, `unit_id` ASC \t\t ";
    //	5/4/11
    //	 		dump($query);
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    if (mysql_affected_rows() > 0) {
        $end_date = intval($problemend) > 1 ? $problemend : time() - get_variable('delta_mins') * 60;
        $elapsed = my_date_diff($problemstart, $end_date);
        // 5/13/10
        //	==========================================================================================
        $search_arg = array_key_exists('capabilities', $_GET) ? "<TR class='even' STYLE = 'white-space:nowrap;'><TD COLSPAN='99' ALIGN='center'>Unit capabilities match: '" . $_GET['capabilities'] . "'</TD></TR>" : "";
        ?>
			side_bar_html += "<TR class='even'>	<TD CLASS='<?php 
        print $severityclass;
        ?>
' COLSPAN=99 ALIGN='center'><B>Routes to Incident: <I><?php 
        print shorten($row_ticket['scope'], 20) . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(" . $elapsed;
        ?>
)</I></B></TD></TR>\n";
			side_bar_html += "<?php 
        print $search_arg;
        ?>
";
			side_bar_html += "<TR class='odd'>	<TD COLSPAN=99 ALIGN='center'>Click line, icon or map for route</TD></TR>\n";
			side_bar_html += "<TR class='even' STYLE = 'white-space:nowrap;'><TD COLSPAN=3></TD><TD ALIGN='left'>Unit</TD><TD ALIGN='right'>SLD&nbsp;(<?php 
        print $capt;
        ?>
)</TD><TD ALIGN='center'>Call</TD><TD ALIGN='left'>Status</TD><TD>M</TD><TD ALIGN='left'>As of</TD></TR>\n";
	
<?php 
        // major while ... for RESPONDER data starts here
        $i = $k = 1;
        // sidebar/icon index
        while ($unit_row = stripslashes_deep(mysql_fetch_assoc($result))) {
            // 7/13/09
            $has_coords = my_is_float($unit_row['lat']) && my_is_float($unit_row['lng']);
            // 2/25/09, 7/7/09
            $has_rem_source = intval($unit_row['aprs']) == 1 || intval($unit_row['instam']) == 1 || intval($unit_row['locatea']) == 1 || intval($unit_row['gtrack']) == 1 || intval($unit_row['glat']) == 1;
            // 11/15/09
            if (is_email($unit_row['contact_via'])) {
                print "\t\t\t email= true;\n";
            }
            ?>
					nr_units++;
					var i = <?php 
            print $i;
            ?>
;						// top of loop
					
					unit_names[i] = "<?php 
            print addslashes($unit_row['unit_name']);
            ?>
";	// unit name 8/25/08, 4/27/09
					unit_preselected = "<?php 
            print $unit_id;
            ?>
";
					if (unit_preselected != "") {
						unit_sets[i] = true;								// pre-set checkbox settings
						show_butts(to_visible);		//	sets dispatch button visible if there is a pre-selected unit - for dispatch from unit functionality.	5/4/11
						} else {
						unit_sets[i] = false;
						}
					unit_ids[i] = <?php 
            print $unit_row['unit_id'];
            ?>
;
	 				direcs[i] = <?php 
            print intval($unit_row['direcs']) == 1 ? "true" : "false";
            ?>
;			// do directions - 7/13/09
<?php 
            if ($has_coords) {
                $tab_1 = "<TABLE CLASS='infowin' width='" . $_SESSION['scr_width'] / 4 . "px'>";
                $tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'>" . shorten($unit_row['unit_name'], 48) . "</TD></TR>";
                $tab_1 .= "<TR CLASS='even'><TD>Description:</TD><TD>" . shorten(str_replace($eols, " ", $unit_row['description']), 32) . "</TD></TR>";
                $tab_1 .= "<TR CLASS='odd'><TD>Status:</TD><TD>" . $unit_row['unitstatus'] . " </TD></TR>";
                $tab_1 .= "<TR CLASS='even'><TD>Contact:</TD><TD>" . $unit_row['contact_name'] . " Via: " . $unit_row['contact_via'] . "</TD></TR>";
                $tab_1 .= "<TR CLASS='odd'><TD>As of:</TD><TD>" . format_date($unit_row['updated']) . "</TD></TR>";
                $tab_1 .= "</TABLE>";
            }
            ?>
					new_element = document.createElement("input");								// please don't ask!
					new_element.setAttribute("type", 	"checkbox");
					new_element.setAttribute("name", 	"unit_<?php 
            print $unit_row['unit_id'];
            ?>
");
					new_element.setAttribute("id", 		"element_id");
					new_element.setAttribute("style", 	"visibility:hidden");
					document.forms['routes_Form'].appendChild(new_element);
					var multi = <?php 
            print intval($unit_row['multi']) == 1 ? "true;\n" : "false;\n";
            ?>
	// 5/22/09
<?php 
            $dispatched_to = array_key_exists($unit_row['unit_id'], $dispatches_disp) ? $dispatches_disp[$unit_row['unit_id']] : "";
            if ($has_coords) {
                if ($unit_row['lat'] == 0.999999 && $unit_row['lng'] == 0.999999) {
                    // check units created in no-maps mode 8/4/10
                    ?>
	
						lats[i] = <?php 
                    print get_variable('def_lat');
                    ?>
; 		// 774-1 now compute distance - in km
						lngs[i] = <?php 
                    print get_variable('def_lng');
                    ?>
;
<?php 
                } else {
                    ?>
						lats[i] = <?php 
                    print $unit_row['lat'];
                    ?>
; 		// 774-2 now compute distance - in km
						lngs[i] = <?php 
                    print $unit_row['lng'];
                    ?>
;
<?php 
                }
                // end check units created in no-maps mode 8/4/10
                if ($row_ticket['lat'] == 0.999999 && $row_ticket['lng'] == 0.999999) {
                    // check tickets created in no-maps mode 8/4/10
                    $ticket_lat = get_variable('def_lat');
                    $ticket_lng = get_variable('def_lng');
                } else {
                    $ticket_lat = $row_ticket['lat'];
                    $ticket_lng = $row_ticket['lng'];
                }
                ?>
							
<?php 
            }
            if ($has_coords && $has_rem_source && !empty($unit_row['callsign'])) {
                // 11/15/09
                $thespeed = "";
                $query = "SELECT *,UNIX_TIMESTAMP(packet_date) AS packet_date, UNIX_TIMESTAMP(updated) AS updated FROM {$GLOBALS['mysql_prefix']}tracks\n\t\t\t\t\t\t\tWHERE `source`= '{$unit_row['callsign']}' ORDER BY `packet_date` DESC LIMIT 1";
                $result_tr = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
                if (mysql_affected_rows() > 0) {
                    // got a track?
                    $track_row = stripslashes_deep(mysql_fetch_array($result_tr));
                    // most recent track report
                    $tab_2 = "<TABLE CLASS='infowin' width='" . $_SESSION['scr_width'] / 4 . "px'>";
                    $tab_2 .= "<TR><TH CLASS='even' COLSPAN=2>" . $track_row['source'] . "</TH></TR>";
                    $tab_2 .= "<TR CLASS='odd'><TD>Course: </TD><TD>" . $track_row['course'] . ", Speed:  " . $track_row['speed'] . ", Alt: " . $track_row['altitude'] . "</TD></TR>";
                    $tab_2 .= "<TR CLASS='even'><TD>Closest city: </TD><TD>" . $track_row['closest_city'] . "</TD></TR>";
                    $tab_2 .= "<TR CLASS='odd'><TD>Status: </TD><TD>" . $track_row['status'] . "</TD></TR>";
                    $tab_2 .= "<TR CLASS='even'><TD>As of: </TD><TD>" . format_date($track_row['packet_date']) . "</TD></TR>";
                    $tab_2 .= "</TABLE>";
                    ?>
							var myinfoTabs = [
								new GInfoWindowTab("<?php 
                    print nl2brr(shorten($unit_row['unit_name'], 8));
                    ?>
", "<?php 
                    print $tab_1;
                    ?>
"),
								new GInfoWindowTab("<?php 
                    print $track_row['source'];
                    ?>
", "<?php 
                    print $tab_2;
                    ?>
"),
								new GInfoWindowTab("Zoom", "<DIV ID='detailmap' CLASS='detailmap'></DIV>")
								];
<?php 
                    $thespeed = $track_row['speed'] == 0 ? "<FONT COLOR='red'><B>&bull;</B></FONT>" : "<FONT COLOR='green'><B>&bull;</B></FONT>";
                    if ($track_row['speed'] >= 50) {
                        $thespeed = "<FONT COLOR='WHITE'><B>&bull;</B></FONT>";
                    }
                    ?>
							var point = new GLatLng(<?php 
                    print $track_row['latitude'];
                    ?>
, <?php 
                    print $track_row['longitude'];
                    ?>
);	// 783 - mobile position
							bounds.extend(point);															// point into BB

<?php 
                } else {
                    // no track data
                    $k--;
                    // not a clickable unit for dispatch
                    ?>
							var myinfoTabs = [
								new GInfoWindowTab("<?php 
                    print nl2brr(shorten($unit_row['unit_name'], 12));
                    ?>
", "<?php 
                    print $tab_1;
                    ?>
"),
								new GInfoWindowTab("Zoom", "<DIV ID='detailmap' CLASS='detailmap'></DIV>")
								];
<?php 
                }
                // end  no track data
                // 8/7/09
            } else {
                // no rem_source
                if ($has_coords) {
                    //  2/25/09
                    ?>
							var myinfoTabs = [
								new GInfoWindowTab("<?php 
                    print nl2brr(shorten($unit_row['unit_name'], 12));
                    ?>
", "<?php 
                    print $tab_1;
                    ?>
"),
								new GInfoWindowTab("Zoom", "<DIV ID='detailmap' CLASS='detailmap'></DIV>")
								];
<?php 
                    if ($unit_row['lat'] == 0.999999 && $unit_row['lng'] == 0.999999) {
                        // check units created in no-maps mode 8/4/10
                        ?>
	
									lats[i] = <?php 
                        print get_variable('def_lat');
                        ?>
; 		// 819-1 now compute distance - in km
									lngs[i] = <?php 
                        print get_variable('def_lng');
                        ?>
;
<?php 
                    } else {
                        ?>
									lats[i] = <?php 
                        print $unit_row['lat'];
                        ?>
; 		// 819-2 now compute distance - in km
									lngs[i] = <?php 
                        print $unit_row['lng'];
                        ?>
;
<?php 
                    }
                    // end check units created in no-maps mode 8/4/10
                    if ($row_ticket['lat'] == 0.999999 && $row_ticket['lng'] == 0.999999) {
                        // check tickets created in no-maps mode 8/4/10
                        $ticket_lat = get_variable('def_lat');
                        $ticket_lng = get_variable('def_lng');
                    } else {
                        $ticket_lat = $row_ticket['lat'];
                        $ticket_lng = $row_ticket['lng'];
                    }
                }
                // end if ($has_coords)
                $thespeed = "";
            }
            // END IF/ELSE (rem_source)
            $the_disp_str = "";
            if ($unit_row['dispatch'] == 2) {
                print "\tsidebar_line = '<TD ALIGN=center><INPUT TYPE=checkbox disabled STYLE = \"visibility: hidden;\"></TD>'";
            } else {
                switch ($unit_row['calls_assigned']) {
                    // 8/29/10
                    case 0:
                        break;
                    case 1:
                        $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\t\t\t\t\t\t\t\tWHERE (`responder_id` = {$unit_row['unit_id']}\n\t\t\t\t\t\t\t\t\tAND `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' ) \n\t\t\t\t\t\t\t\t\tlimit 1";
                        $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
                        $row_as = stripslashes_deep(mysql_fetch_assoc($result_as));
                        $the_disp_str = "<SPAN CLASS='disp_stat'>&nbsp;" . get_disp_status($row_as) . "&nbsp;</SPAN>&nbsp;";
                        break;
                    default:
                        // display count
                        $the_disp_str = "<SPAN CLASS='disp_stat'>&nbsp;{$unit_row['calls_assigned']}&nbsp;</SPAN>&nbsp;";
                        break;
                }
                // end switch ()
                ?>
				
					sidebar_line = "<TD ALIGN='center'><INPUT TYPE='checkbox' <?php 
                print get_cd_str($unit_row);
                ?>
 NAME = 'unit_" + <?php 
                print $unit_row['unit_id'];
                ?>
 + "' onClick='show_butts(to_visible); unit_sets[<?php 
                print $i;
                ?>
]=this.checked;' /></TD>";
<?php 
            }
            ?>
				
	
					sidebar_line += "<TD TITLE = \"<?php 
            print addslashes($unit_row['unit_name']);
            ?>
\">";
<?php 
            $the_bg_color = $GLOBALS['UNIT_TYPES_BG'][$unit_row['icon']];
            // 2/1/10
            $the_text_color = $GLOBALS['UNIT_TYPES_TEXT'][$unit_row['icon']];
            $strike = $unit_row['dispatch'] == 0 ? "" : "color:red;text-decoration:line-through;";
            $the_style = "<SPAN STYLE='{$strike}background-color:{$the_bg_color};  opacity: .7; color:{$the_text_color};'>";
            $str_dist = $have_position ? number_format(round($unit_row['distance'], 1), 1) : "";
            // 3/5/11
            //					dump(__LINE__);
            ?>
					sidebar_line += "<NOBR><?php 
            print $the_style . shorten($unit_row['unit_name'], 20);
            ?>
</SPAN></NOBR></TD>";
					sidebar_line += "<TD ALIGN='right'><?php 
            print $str_dist;
            ?>
</TD>"; // 8/25/08, 4/27/09

					sidebar_line += "<?php 
            print get_assigned_td($unit_row['unit_id']);
            ?>
";		// 3/15/11
<?php 
            $the_style = "<SPAN STYLE='{$strike}background-color:{$unit_row['bg_color']}; color:{$unit_row['text_color']};'>";
            ?>
					sidebar_line += "<TD TITLE = \"<?php 
            print $unit_row['unitstatus'];
            ?>
\" CLASS='td_data'><?php 
            print $the_style . shorten($unit_row['unitstatus'], 12);
            ?>
</SPAN></TD>";
					sidebar_line += "<TD CLASS='td_data'><?php 
            print $thespeed;
            ?>
</TD>";
					sidebar_line += "<TD CLASS='td_data'><?php 
            print substr(format_sb_date($unit_row['updated']), 4);
            ?>
</TD>";
<?php 
            if ($has_coords) {
                //  2/25/09
                if ($unit_row['lat'] == 0.999999 && $unit_row['lng'] == 0.999999) {
                    // check for facilities entered in no maps mode 8/4/10
                    ?>
	
							var point = new GLatLng(<?php 
                    print get_variable('def_lat');
                    ?>
, <?php 
                    print get_variable('def_lng');
                    ?>
);	//  840 for each responder 832
							var unit_id = <?php 
                    print $unit_row['unit_id'];
                    ?>
;
							bounds.extend(point);																// point into BB
							var marker = createdummyMarker(point, sidebar_line, myinfoTabs,<?php 
                    print $unit_row['type'];
                    ?>
, i, unit_id);	// (point,sidebar,tabs, color, id)
							if (!(isNull(marker))) {
								map.addOverlay(marker);
								}
<?php 
                } else {
                    ?>
							var point = new GLatLng(<?php 
                    print $unit_row['lat'];
                    ?>
, <?php 
                    print $unit_row['lng'];
                    ?>
);	//  840 for each responder 832
							var unit_id = <?php 
                    print $unit_row['unit_id'];
                    ?>
;
							bounds.extend(point);																// point into BB
							var marker = createMarker(point, sidebar_line, myinfoTabs,<?php 
                    print $unit_row['type'];
                    ?>
, i, unit_id);	// (point,sidebar,tabs, color, id)
							if (!(isNull(marker))) {
								map.addOverlay(marker);
								}
<?php 
                }
                // end check for facilities entered in no maps mode 8/4/10
            } else {
                print "\n\t\t\t\tdo_sidebar(sidebar_line, color, i);\n";
            }
            // end if/else ($has_coords)
            $i++;
            $k++;
        }
        // end major while ($unit_row = ...)  for each responder
        print "\t\t var start = 1;\n";
        // already sorted - 3/24/10
    } else {
        print "\t\t var start = 0;\n";
        // already sorted - 3/24/10
    }
    //					responders complete
    if ($row_ticket['lat'] == 0.999999 && $row_ticket['lng'] == 0.999999) {
        // check for facilities entered in no maps mode 8/4/10
        ?>
				var point = new GLatLng(<?php 
        print get_variable('def_lat');
        ?>
, <?php 
        print get_variable('def_lng');
        ?>
);	// incident
				var baseIcon = new GIcon();
				var inc_icon = new GIcon(baseIcon, "./our_icons/question1.png", null);		// 10/26/08
				var thisMarker = new GMarker(point);
				map.addOverlay(thisMarker);				
<?php 
    } else {
        ?>
			
				var point = new GLatLng(<?php 
        echo $row_ticket['lat'];
        ?>
, <?php 
        echo $row_ticket['lng'];
        ?>
);	// incident
				var baseIcon = new GIcon();
				var inc_icon = new GIcon(baseIcon, "./markers/sm_black.png", null);		// 10/26/08
				var thisMarker = new GMarker(point);
				map.addOverlay(thisMarker);			
<?php 
    }
    ?>
			

	
			if (nr_units==0) {
				side_bar_html +="<TR CLASS='odd'><TD ALIGN='center' COLSPAN=99><BR /><BR /><H3>No Units!</H3></TD></TR>";	
				map.setCenter(new GLatLng(<?php 
    echo $row_ticket['lat'];
    ?>
, <?php 
    echo $row_ticket['lng'];
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
				}
			else {
				center = bounds.getCenter();
				zoom = map.getBoundsZoomLevel(bounds);		// -1 for further out	
//				var radii = new Array (0, 1, 2, 3, 4, 5,   6,   7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17) ;
				var radii = new Array (100, 100, 100, 100, 50, 50, 50, 50, 40, 20, 10, 5, 5, 5,  5,  5,  5,  5) ;	// miles
				var the_rad = radii[zoom];
 				drawCircle(<?php 
    print $row_position['lat'];
    ?>
,  <?php 
    print $row_position['lng'];
    ?>
, the_rad, "#000080", 1, 0.75, "#0000FF", .05);				
				map.setCenter(center,zoom);
				side_bar_html+= "<TR CLASS='" + colors[i%2] +"'><TD COLSPAN=99>&nbsp;</TD></TR>\n";
				side_bar_html+= "<TR CLASS='" + colors[(i+1)%2] +"'><TD COLSPAN=99 ALIGN='center'><B>M</B>obility:&nbsp;&nbsp; stopped: <FONT COLOR='red'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;moving: <FONT COLOR='green'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;fast: <FONT COLOR='white'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;silent: <FONT COLOR='black'><B>&bull;</B></FONT></TD></TR>\n";
				side_bar_html+= "<TR><TD>&nbsp;</TD></TR>\n";
				}
					
			side_bar_html +="</TABLE>\n";
			document.getElementById("side_bar").innerHTML = side_bar_html;	// put the assembled side_bar_html contents into the side bar div
	
			var thelat = <?php 
    print $lat;
    ?>
; var thelng = <?php 
    print $lng;
    ?>
;
	
			var norecfac = "";	//10/6/09
	
			if (start>0) {
	
				var current_id= "R"+start;			//
				document.getElementById(current_id).style.visibility = "visible";		// show link check image at the selected sidebar el ement
				$("mail_button").style.display = "none";	//10/6/09
				if (lats[start]) {
<?php 
    if ($rec_fac > 0) {
        ?>
				
						var thereclat = <?php 
        print $rf_lat;
        ?>
; var thereclng = <?php 
        print $rf_lng;
        ?>
;	//adds in receiving facility
						if (direcs[start]) {
							setDirections(lats[start] + " " + lngs[start], thelat + " " + thelng, thereclat + " " + thereclng, "en_US", unit_id);	// get directions	10/6/09
							}
<?php 
    } else {
        ?>
			
						if (direcs[start]) {
							setDirections(lats[start] + " " + lngs[start], thelat + " " + thelng, norecfac, "en_US", unit_id);	// get directions	10/6/09
							}
<?php 
    }
    // end if/else ($rec_fac > 0)
    ?>
					}		// end if (lats[start]) 
				}		// end if (start>0)
<?php 
    // ======================================
    ?>

				location.href = "#top";				// 11/12/09	
						
			}		// end if (GBrowserIsCompatible())
	
		else {
			alert("Sorry,  browser compatibility problem. Contact your tech support group.");
			}
	
		</SCRIPT>
		
<?php 
}
function do_list($unit_id = "")
{
    global $row_fac, $dispatches, $from_top, $from_left, $eol, $conversion;
    //	2/4/11
    ?>
<SCRIPT>
	var color=0;
	var last_from;
	var last_to;
	var current_id;
	var output_direcs = "";
	var have_direcs = 0;
	var fac_name = "<?php 
    print $row_fac['fac_name'];
    ?>
";	//10/29/09 - 11/13/09
	
	if (GBrowserIsCompatible()) {
		var colors = new Array ('odd', 'even');
	    function setDirections(fromAddress, toAddress, locale, unit_id) {
		$("mail_button").style.display = "none";
		$("loading").style.display = "inline-block";		// 10/28/09
	    	last_from = fromAddress;
	    	last_to = toAddress;
		f_unit = unit_id;
		   	G_START_ICON.image = "./our_icons/sm_white.png";
		   	G_START_ICON.iconSize = new GSize(12,20); 
		   	G_END_ICON.image = "./our_icons/sm_white.png";
		   	G_END_ICON.iconSize = new GSize(12,20);         	

	    	var Direcs = gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale, preserveViewport : true  });
			GEvent.addListener(Direcs, "addoverlay", GEvent.callback(Direcs, cb())); 
	    	}		// end function set Directions()

		function cb() {
			setTimeout(cb2,3000);     // I THINK you need quotes around the named function - here's 2 seconds of delay
		}      // end function cb()


		function cb2() {                                        // callback function 09/11/09
			var output_direcs = "";
			for ( var i = 0; i < gdir.getNumRoutes(); i++) {        // Traverse all routes - not really needed here, but ...
				var groute = gdir.getRoute(i);
				var distanceTravelled = 0;             // if you want to start summing these
 
				for ( var j = 0; j < groute.getNumSteps(); j++) {                // Traverse the steps this route
					var gstep = groute.getStep(j);
					var directions_text =  gstep.getDescriptionHtml();
					var directions_dist = gstep.getDistance().html;
//					alert ("1387 " + gstep.getDescriptionHtml());
//					alert ("1388 " + gstep.getDistance().html);
					output_direcs = output_direcs + directions_text + " " + directions_dist + ". " + "\n";

				}
			}
			output_direcs = output_direcs.replace("<div class=\"google_note\">", "\n - ");
			output_direcs = output_direcs.replace("&nbsp:", " ");
			document.email_form.frm_direcs.value = output_direcs;
			document.email_form.frm_u_id.value = f_unit;
			document.email_form.frm_scope.value = fac_name;	//10/29/09
			$("mail_button").style.display = "inline-block";	//10/6/09
			$("loading").style.display = "none";		// 10/28/09			
		}                // end function cb2()

		function mail_direcs(f) {
			f.target = 'Mail Form'
			newwindow_mail=window.open('',f.target,'titlebar, location=0, resizable=1, scrollbars, height=360,width=600,status=0,toolbar=0,menubar=0,location=0, left=100,top=300,screenX=100,screenY=300');
			if (isNull(newwindow_mail)) {
				alert ("Email edit operation requires popups to be enabled -- please adjust your browser options.");
				return;
				}
			newwindow_mail.focus();
			f.submit();
			return false;
			}

	
		function do_sidebar(sidebar, color, id, unit_id) {						// No map
			var letter = ""+ id;	
			marker = null;
			gmarkers[id] = null;										// marker to array for side_bar click function
	
			side_bar_html += "<TR CLASS='" + colors[(id+1)%2] +"' VALIGN='bottom' onClick = myclick(" + id + "," + unit_id +");><TD>";
			side_bar_html += "<IMG BORDER=0 SRC='rtarrow.gif' ID = \"R" + id + "\"  STYLE = 'visibility:hidden;'></TD>";
			var letter = ""+ id;	
			var the_class = (lats[id])?  "emph" : "td_label";

			side_bar_html += "<TD CLASS='" + the_class + "'>" + letter + ". "+ sidebar +"</TD></TR>\n";
			return null;
			}				// end function create Marker()


		function createMarker(point,sidebar,tabs, color, id, unit_id) {		// Creates marker and sets up click event infowindow
			do_sidebar(sidebar, color, id, unit_id)
			var icon = new GIcon(listIcon);
			var uid = unit_id;
			var letter = ""+ id;	
			var icon_url = "./our_icons/gen_icon.php?blank=" + escape(icons[color]) + "&text=" + letter;
	
			icon.image = icon_url;		// ./our_icons/gen_icon.php?blank=4&text=zz"
			var marker = new GMarker(point, icon);
			marker.id = color;				// for hide/unhide - unused
		
			GEvent.addListener(marker, "click", function() {		// here for both side bar and icon click
				map.closeInfoWindow();
				which = id;
				gmarkers[which].hide();
				marker.openInfoWindowTabsHtml(infoTabs[id]);
				var dMapDiv = document.getElementById("detailmap");
				var detailmap = new GMap2(dMapDiv);
//				detailmap.addControl(new GSmallMapControl());
//				map.setUIToDefault();										// 8/13/10
//				detailmap.setCenter(point, 17;  					// larger # = closer
//				detailmap.addOverlay(marker);
				});
		
			gmarkers[id] = marker;							// marker to array for side_bar click function
			infoTabs[id] = tabs;							// tabs to array
			bounds.extend(point);							// extend the bounding box		
			return marker;
			}				// end function create Marker()
	
		function myclick(id, unit_id) {								// responds to side bar click - 11/13/09
//			alert("550 " + direcs[id]);
			which = id;
			document.getElementById(current_id).style.visibility = "hidden";		// hide last check
			current_id= "R"+id;
			document.getElementById(current_id).style.visibility = "visible";		// show newest
			if (!(lats[id])) {
				alert("611 Cannot route -  no position data currently available\n\nClick map point for directions.");
				$('directions').innerHTML = "";							// 11/13/09	
				$('mail_dir_but').style.visibility = "hidden";			// 11/13/09	
				}
			else {
				$('mail_dir_but').style.visibility = "visible";			// 11/13/09	
				var thelat = <?php 
    print $row_fac['lat'];
    ?>
; var thelng = <?php 
    print $row_fac['lng'];
    ?>
;		// coords of click point
				setDirections(lats[id] + " " + lngs[id], thelat + " " + thelng, "en_US", unit_id);							// get directions
				}
			}					// end function my click(id)
	
		var the_grid;
		var grid = false;
		function doGrid() {
			if (grid) {
				map.removeOverlay(the_grid);
				}
			else {
				the_grid = new LatLonGraticule();
				map.addOverlay(the_grid);
				}
			grid = !grid;
			}			// end function doGrid
			
	    var trafficInfo = new GTrafficOverlay();
	    var toggleState = true;
	
		function doTraffic() {
			if (toggleState) {
		        map.removeOverlay(trafficInfo);
		     	} 
			else {
		        map.addOverlay(trafficInfo);
		    	}
	        toggleState = !toggleState;			// swap
		    }				// end function doTraffic()
	
		var starting = false;

		function sv_win(theLat, theLng) {
			if(starting) {return;}						// dbl-click proof
			starting = true;					
//			alert(622);
			var url = "street_view.php?thelat=" + theLat + "&thelng=" + theLng;
			newwindow_sl=window.open(url, "sta_log",  "titlebar=no, location=0, resizable=1, scrollbars, height=450,width=640,status=0,toolbar=0,menubar=0,location=0, left=100,top=300,screenX=100,screenY=300");
			if (!(newwindow_sl)) {
				alert ("Street view operation requires popups to be enabled. Please adjust your browser options - or else turn off the Call Board option.");
				return;
				}
			newwindow_sl.focus();
			starting = false;
			}		// end function sv win()

		
		function handleErrors(){		//G_GEO_UNKNOWN_DIRECTIONS 
			if (gdir.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS ) {
				alert("501: directions unavailable\n\nClick map point for directions.");
				}
			else if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
				alert("440: No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
				alert("442: A map request could not be processed, reason unknown.\n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
				alert("444: Technical error.\n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_BAD_KEY)
				alert("448: The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
				alert("450: A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
			else alert("451: An unknown error occurred.");
			}		// end function handleErrors()

		function onGDirectionsLoad(){ 
//			var temp = gdir.getSummaryHtml();
			}		// function onGDirectionsLoad()

		function guest () {
			alert ("Demonstration only.  Guests may not commit dispatch!");
			}
			
		function validate(){		// frm_id_str
			msgstr="";
			for (var i =1;i<unit_sets.length;i++) {
				if (unit_sets[i]) {
					msgstr+=unit_names[i]+"\n";
					document.routes_Form.frm_id_str.value += unit_ids[i] + "|";
					}
				}
			if (msgstr.length==0) {
				var more = (nr_units>1)? "s": ""
				alert ("Please select unit" + more + ", or cancel");
				return false;
				}
			else {
				if (confirm ("Please confirm Unit dispatch as follows\n\n" + msgstr)) {
					document.routes_Form.frm_id_str.value = document.routes_Form.frm_id_str.value.substring(0, document.routes_Form.frm_id_str.value.length - 1);	// drop trailing separator
					document.routes_Form.frm_name_str.value = msgstr;	// for re-use
					document.routes_Form.submit();
					document.getElementById("outer").style.display = "none";
					document.getElementById("bottom").style.display = "block";					
					}
				else {
					document.routes_Form.frm_id_str.value="";	
					return false;
					}
				}

			}		// end function validate()
	
		function exists(myarray,myid) {
			var str_key = " " + myid;		// force associative
			return ((typeof myarray[str_key])!="undefined");		// exists if not undefined
			}		// end function exists()
			
		var icons=[];						// note globals
<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_types` ORDER BY `id`";
    // types in use
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $icons = $GLOBALS['fac_icons'];
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // map type to blank icon id
        $blank = $icons[$row['icon']];
        print "\ticons[" . $row['id'] . "] = " . $row['icon'] . ";\n";
        //
    }
    unset($result);
    ?>
		var map;
		var center;
		var zoom;
		
	    var gdir;				// directions
	    var geocoder = null;
	    var addressMarker;
		$("mail_button").style.display = "none";		// 10/28/09
		$("loading").style.display = "none";		// 10/28/09
		
		var side_bar_html = "<TABLE border=0 CLASS='sidebar' ID='tbl_responders'>";
		side_bar_html += "<TR class='even'>	<TD  COLSPAN=99 ALIGN='center'><B>Routes to Facility: <I><?php 
    print shorten($row_fac['fac_name'], 20);
    ?>
</I></B></TD></TR>\n";
		side_bar_html += "<TR class='odd'>	<TD COLSPAN=99 ALIGN='center'>Click line, icon or map for route</TD></TR>\n";
		side_bar_html += "<TR class='even'>	<TD COLSPAN=3></TD><TD ALIGN='center'>Unit</TD><TD ALIGN='center'>SLD</TD><TD ALIGN='center'>Facility</TD><TD ALIGN='center'>Status</TD><TD ALIGN='center'>As of</TD></TR>\n";

		var gmarkers = [];
		var infoTabs = [];
		var lats = [];
		var lngs = [];
		var distances = [];
		var unit_names = [];			// names
		var unit_contacts = [];		// contact emails
		var unit_sets = [];			// settings
		var unit_ids = [];			// id's
		var unit_assigns =  [];		// unit id's assigned this incident
		var direcs =  [];			// if true, do directions
		var which;			// marker last selected
		var i = 0;			// sidebar/icon index
	
//		map = new GMap2(document.getElementById("map_canvas"));		// create the map
//		map.addControl(new GSmallMapControl());
//		map.addControl(new GMapTypeControl());
<?php 
    if (get_variable('terrain') == 1) {
        ?>
//		map.addMapType(G_PHYSICAL_MAP);
<?php 
    }
    ?>
	

		gdir = new GDirections(map, document.getElementById("directions"));
		
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
		map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);		// <?php 
    echo get_variable('def_lat');
    ?>
	
		var bounds = new GLatLngBounds();						// create empty bounding box
	
		var listIcon = new GIcon();
		listIcon.image = "./markers/yellow.png";	// yellow.png - 16 X 28
//		listIcon.shadow = "./markers/sm_shadow.png";
		listIcon.iconSize = new GSize(20, 34);
//		listIcon.shadowSize = new GSize(37, 34);
		listIcon.iconAnchor = new GPoint(8, 28);
		listIcon.infoWindowAnchor = new GPoint(9, 2);
//		listIcon.infoShadowAnchor = new GPoint(18, 25);
	
		var newIcon = new GIcon();
		newIcon.image = "./markers/white.png";	// yellow.png - 20 X 34
//		newIcon.shadow = "./markers/shadow.png";
		newIcon.iconSize = new GSize(20, 34);
//		newIcon.shadowSize = new GSize(37, 34);
		newIcon.iconAnchor = new GPoint(8, 28);
		newIcon.infoWindowAnchor = new GPoint(9, 2);
//		newIcon.infoShadowAnchor = new GPoint(18, 25);
																	// set Incident position
		var point = new GLatLng(<?php 
    print $row_fac['lat'];
    ?>
, <?php 
    print $row_fac['lng'];
    ?>
);
		bounds.extend(point);

	
		GEvent.addListener(map, "infowindowclose", function() {		// re-center after  move/zoom
			setDirections(last_from, last_to, "en_US") ;
			});
		var accept_click = false;
		GEvent.addListener(map, "click", function(marker, point) {		// point.lat()
			var the_start = point.lat().toString() + "," + point.lng().toString();
			var the_end = thelat.toString() + "," + thelng.toString();			
			setDirections(the_start, the_end, "en_US");			
			});				// end GEvent.addListener()

		var nr_units = 	0;
		var email= false;
	    var km2mi = <?php 
    print $conversion;
    ?>
;				// 
		
<?php 
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    // build js array of responders to this ticket - possibly none
    $where = empty($unit_id) ? "" : " WHERE `{$GLOBALS['mysql_prefix']}responder`.`id` = {$unit_id} ";
    // revised 5/23/08 per AD7PE
    $query = "SELECT *, UNIX_TIMESTAMP(updated) AS updated, `{$GLOBALS['mysql_prefix']}responder`.`id` AS `unit_id`, `s`.`status_val` AS `unitstatus`, `contact_via` FROM {$GLOBALS['mysql_prefix']}responder\n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}un_status` `s` ON (`{$GLOBALS['mysql_prefix']}responder`.`un_status_id` = `s`.`id`)\n\t\t\t{$where}\n\t\t\tORDER BY `name` ASC, `unit_id` ASC";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    if (mysql_affected_rows() > 0) {
        // major while ... for RESPONDER data starts here
        $i = $k = 1;
        // sidebar/icon index
        while ($unit_row = stripslashes_deep(mysql_fetch_assoc($result))) {
            $has_coords = my_is_float($unit_row['lat']) && my_is_float($unit_row['lng']);
            if (is_email($unit_row['contact_via'])) {
                print "\t\temail= true\n";
            }
            ?>
				nr_units++;

				var i = <?php 
            print $i;
            ?>
;						// top of loop
				
				unit_names[i] = "<?php 
            print addslashes($unit_row['name']);
            ?>
";
				unit_sets[i] = false;								// pre-set checkbox settings				
				unit_ids[i] = <?php 
            print $unit_row['unit_id'];
            ?>
;
				distances[i]=9999.9;
 				direcs[i] = <?php 
            print intval($unit_row['direcs']) == 1 ? "true" : "false";
            ?>
;
<?php 
            if ($has_coords) {
                //					snap (__LINE__, $unit_row['unit_id']);
                $tab_1 = "<TABLE CLASS='infowin' width='" . $_SESSION['scr_width'] / 4 . "px'>";
                $tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'>" . shorten($unit_row['name'], 48) . "</TD></TR>";
                $tab_1 .= "<TR CLASS='even'><TD>Description:</TD><TD>" . shorten(str_replace($eols, " ", $unit_row['description']), 32) . "</TD></TR>";
                $tab_1 .= "<TR CLASS='odd'><TD>Status:</TD><TD>" . $unit_row['unitstatus'] . " </TD></TR>";
                $tab_1 .= "<TR CLASS='even'><TD>Contact:</TD><TD>" . $unit_row['contact_name'] . " Via: " . $unit_row['contact_via'] . "</TD></TR>";
                $tab_1 .= "<TR CLASS='odd'><TD>As of:</TD><TD>" . format_date($unit_row['updated']) . "</TD></TR>";
                $tab_1 .= "</TABLE>";
            }
            ?>
//				new_element = document.createElement("input");								// please don't ask!
//				new_element.setAttribute("type", 	"checkbox");
//				new_element.setAttribute("name", 	"unit_<?php 
            print $unit_row['unit_id'];
            ?>
");
//				new_element.setAttribute("id", 		"element_id");
//				new_element.setAttribute("style", 	"visibility:hidden");
//				document.forms['routes_Form'].appendChild(new_element);
				var dist_mi = "na";
				var multi = <?php 
            print intval($unit_row['multi']) == 1 ? "true;\n" : "false;\n";
            ?>
	
<?php 
            $dispatched_to = array_key_exists($unit_row['unit_id'], $dispatches) ? $dispatches[$unit_row['unit_id']] : "";
            if ($has_coords) {
                ?>
		
					lats[i] = <?php 
                print $unit_row['lat'];
                ?>
; 		// 774 now compute distance - in km
					lngs[i] = <?php 
                print $unit_row['lng'];
                ?>
;
					distances[i] = distCosineLaw(parseFloat(lats[i]), parseFloat(lngs[i]), parseFloat(<?php 
                print $row_fac['lat'];
                ?>
), parseFloat(<?php 
                print $row_fac['lng'];
                ?>
));
					var dist_mi = ((distances[i] * km2mi).toFixed(1)).toString();				// to miles
<?php 
            } else {
                ?>
					distances[i] = 9999.9;
					var dist_mi = "na";
<?php 
            }
            if (!empty($unit_row['callsign'])) {
                $thespeed = "";
                $query = "SELECT *,UNIX_TIMESTAMP(packet_date) AS packet_date, UNIX_TIMESTAMP(updated) AS updated FROM {$GLOBALS['mysql_prefix']}tracks\n\t\t\t\t\t\tWHERE `source`= '{$unit_row['callsign']}' ORDER BY `packet_date` DESC LIMIT 1";
                $result_tr = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
                if (mysql_affected_rows() > 0) {
                    // got a track?
                    $track_row = stripslashes_deep(mysql_fetch_array($result_tr));
                    // most recent track report
                    $tab_2 = "<TABLE CLASS='infowin' width='" . $_SESSION['scr_width'] / 4 . "px'>";
                    $tab_2 .= "<TR><TH CLASS='even' COLSPAN=2>" . $track_row['source'] . "</TH></TR>";
                    $tab_2 .= "<TR CLASS='odd'><TD>Course: </TD><TD>" . $track_row['course'] . ", Speed:  " . $track_row['speed'] . ", Alt: " . $track_row['altitude'] . "</TD></TR>";
                    $tab_2 .= "<TR CLASS='even'><TD>Closest city: </TD><TD>" . $track_row['closest_city'] . "</TD></TR>";
                    $tab_2 .= "<TR CLASS='odd'><TD>Status: </TD><TD>" . $track_row['status'] . "</TD></TR>";
                    $tab_2 .= "<TR CLASS='even'><TD>As of: </TD><TD>" . format_date($track_row['packet_date']) . "</TD></TR>";
                    $tab_2 .= "</TABLE>";
                    ?>
						var myinfoTabs = [
							new GInfoWindowTab("<?php 
                    print nl2brr(shorten($unit_row['name'], 8));
                    ?>
", "<?php 
                    print $tab_1;
                    ?>
"),
							new GInfoWindowTab("<?php 
                    print $track_row['source'];
                    ?>
", "<?php 
                    print $tab_2;
                    ?>
"),
							new GInfoWindowTab("Zoom", "<DIV ID='detailmap' CLASS='detailmap'></DIV>")
							];
<?php 
                    $thespeed = $track_row['speed'] == 0 ? "<FONT COLOR='red'><B>&bull;</B></FONT>" : "<FONT COLOR='green'><B>&bull;</B></FONT>";
                    if ($track_row['speed'] >= 50) {
                        $thespeed = "<FONT COLOR='WHITE'><B>&bull;</B></FONT>";
                    }
                    ?>
						var point = new GLatLng(<?php 
                    print $track_row['latitude'];
                    ?>
, <?php 
                    print $track_row['longitude'];
                    ?>
);
						bounds.extend(point);								// point into BB
<?php 
                } else {
                    // no track data
                    $k--;
                    // not a clickable unit for dispatch
                    ?>
						var myinfoTabs = [
							new GInfoWindowTab("<?php 
                    print nl2brr(shorten($unit_row['name'], 12));
                    ?>
", "<?php 
                    print $tab_1;
                    ?>
"),
							new GInfoWindowTab("Zoom", "<DIV ID='detailmap' CLASS='detailmap'></DIV>")
							];
<?php 
                }
                // end  no track data
            } else {
                // no callsign
                if ($has_coords) {
                    ?>
						var myinfoTabs = [
							new GInfoWindowTab("<?php 
                    print nl2brr(shorten($unit_row['name'], 12));
                    ?>
", "<?php 
                    print $tab_1;
                    ?>
"),
							new GInfoWindowTab("Zoom", "<DIV ID='detailmap' CLASS='detailmap'></DIV>")
							];
						
						lats[i] = <?php 
                    print $unit_row['lat'];
                    ?>
; // 819 now compute distance - in km
						lngs[i] = <?php 
                    print $unit_row['lng'];
                    ?>
;
						distances[i] = distCosineLaw(parseFloat(lats[i]), parseFloat(lngs[i]), parseFloat(<?php 
                    print $row_fac['lat'];
                    ?>
), parseFloat(<?php 
                    print $row_fac['lng'];
                    ?>
));	// note: km
					    var km2mi = <?php 
                    print $conversion;
                    ?>
;				// 
						var dist_mi = ((distances[i] * km2mi).toFixed(1)).toString();				// to feet
<?php 
                }
                // end if ($has_coords)
                $thespeed = "";
            }
            // END IF/ELSE (callsign)
            print !(intval($unit_row['multi']) == 1) && isset($dispatches[$unit_row['unit_id']]) ? "\n\tvar is_checked =  ' CHECKED ';\n\tvar is_disabled =  ' DISABLED ';\n" : "\n\tvar is_checked =  '';\n\tvar is_disabled =  '';\n";
            ?>
					
				sidebar_line = "<TD ALIGN='center'><INPUT TYPE='hidden' NAME = 'unit_" + <?php 
            print $unit_row['unit_id'];
            ?>
 + "' onClick='unit_sets[<?php 
            print $i;
            ?>
]=this.checked;'></TD>";

				sidebar_line += "<TD TITLE = \"<?php 
            print addslashes($unit_row['name']);
            ?>
\">";
				sidebar_line += "<NOBR><?php 
            print shorten($unit_row['name'], 20);
            ?>
</NOBR></TD>";

				sidebar_line += "<TD>"+ dist_mi+"</TD>"; // 8/25/08, 4/27/09
				sidebar_line += "<TD><NOBR><?php 
            print shorten(addslashes($dispatched_to), 20);
            ?>
</NOBR></TD>";
				sidebar_line += "<TD TITLE = \"<?php 
            print $unit_row['unitstatus'];
            ?>
\" CLASS='td_data'><?php 
            print shorten($unit_row['unitstatus'], 12);
            ?>
</TD>";
//				sidebar_line += "<TD CLASS='td_data'><?php 
            print $thespeed;
            ?>
</TD>";
				sidebar_line += "<TD CLASS='td_data'><?php 
            print substr(format_sb_date($unit_row['updated']), 4);
            ?>
</TD>";
<?php 
            if ($has_coords) {
                //  2/25/09
                ?>
		
					var point = new GLatLng(<?php 
                print $unit_row['lat'];
                ?>
, <?php 
                print $unit_row['lng'];
                ?>
);	//  840 for each responder 832
					var unit_id = <?php 
                print $unit_row['unit_id'];
                ?>
;
					bounds.extend(point);																// point into BB
					var marker = createMarker(point, sidebar_line, myinfoTabs,<?php 
                print $unit_row['type'];
                ?>
, i, unit_id);	// (point,sidebar,tabs, color, id, unit_id)
					if (!(isNull(marker))) {
						map.addOverlay(marker);
						}
<?php 
            } else {
                print "\n\tdo_sidebar(sidebar_line, color, i);\n";
            }
            // end if/else ($has_coords)
            $i++;
            $k++;
        }
        // end major while ($unit_row = ...)  for each responder
    }
    // end if(mysql_affected_rows()>0)
    ?>
 		var point = new GLatLng(<?php 
    echo $row_fac['lat'];
    ?>
, <?php 
    echo $row_fac['lng'];
    ?>
);	//
		var baseIcon = new GIcon();
		var inc_icon = new GIcon(baseIcon, "./markers/sm_black.png", null);
		var thisMarker = new GMarker(point);
		map.addOverlay(thisMarker);

		if (nr_units==0) {
			side_bar_html +="<TR CLASS='odd'><TD ALIGN='center' COLSPAN=99><BR /><B>No Units!</B></TD></TR>";;		
			map.setCenter(new GLatLng(<?php 
    echo $row_fac['lat'];
    ?>
, <?php 
    echo $row_fac['lng'];
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
			}
		else {
			center = bounds.getCenter();
			zoom = map.getBoundsZoomLevel(bounds);		// -1 for further out	
			map.setCenter(center,zoom);
			side_bar_html+= "<TR CLASS='" + colors[i%2] +"'><TD COLSPAN=99>&nbsp;</TD></TR>\n";
			side_bar_html+= "<TR><TD>&nbsp;</TD></TR>\n";
			}
				
		side_bar_html +="</TABLE>\n";
		document.getElementById("side_bar").innerHTML = side_bar_html;	// put the assembled side_bar_html contents into the side_bar div

		var thelat = <?php 
    print $row_fac['lat'];
    ?>
; var thelng = <?php 
    print $row_fac['lng'];
    ?>
;
		var start = min(distances);		// min straight-line distance to Incident

		if (start>0) {
			var current_id= "R"+start;			//
//			document.getElementById(current_id).style.visibility = "visible";		// show link check image at the selected sidebar el ement
//			if (lats[start]) {
//				setDirections(lats[start] + " " + lngs[start], thelat + " " + thelng, "en_US");
//				}
			}
		}		// end if (GBrowserIsCompatible())

	else {
		alert("Sorry,  browser compatibility problem. Contact your tech support group.");
		}

	</SCRIPT>
	
<?php 
}
function list_facilities($addon = '', $start)
{
    //	global {$_SESSION['fip']}, $fmp, {$_SESSION['editfile']}, {$_SESSION['addfile']}, {$_SESSION['unitsfile']}, {$_SESSION['facilitiesfile']}, {$_SESSION['routesfile']}, {$_SESSION['facroutesfile']};
    global $iw_width, $u_types, $tolerance;
    //	$assigns = array();
    //	$tickets = array();
    $query = "SELECT `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`, `{$GLOBALS['mysql_prefix']}assigns`.`responder_id`, `{$GLOBALS['mysql_prefix']}ticket`.`scope` AS `ticket` FROM `{$GLOBALS['mysql_prefix']}assigns` LEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` ON `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`=`{$GLOBALS['mysql_prefix']}ticket`.`id`";
    $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_as = stripslashes_deep(mysql_fetch_assoc($result_as))) {
        $assigns[$row_as['responder_id']] = $row_as['ticket'];
        $tickets[$row_as['responder_id']] = $row_as['ticket_id'];
    }
    unset($result_as);
    $calls = array();
    $calls_nr = array();
    $calls_time = array();
    $query = "SELECT * , UNIX_TIMESTAMP(packet_date) AS `packet_date` FROM `{$GLOBALS['mysql_prefix']}tracks` ORDER BY `packet_date` ASC";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), __FILE__, __LINE__);
    while ($row = mysql_fetch_assoc($result)) {
        if (isset($calls[$row['source']])) {
            // array_key_exists ( mixed key, array search )
            $calls_nr[$row['source']]++;
        } else {
            array_push($calls, trim($row['source']));
            $calls[trim($row['source'])] = TRUE;
            $calls_nr[$row['source']] = 1;
        }
        $calls_time[$row['source']] = $row['packet_date'];
        // save latest - note query order
    }
    $query = "SELECT `id` FROM `{$GLOBALS['mysql_prefix']}facilities`";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), __FILE__, __LINE__);
    $facilities = mysql_affected_rows() > 0 ? mysql_affected_rows() : "<I>none</I>";
    unset($result);
    ?>

<SCRIPT >

var color=0;
	var colors = new Array ('odd', 'even');

	function hideGroup(color) {
		for (var i = 0; i < gmarkers.length; i++) {
			if (gmarkers[i]) {
				if (gmarkers[i].id == color) {
					gmarkers[i].show();
					}
				else {
					gmarkers[i].hide();
					}
				}		// end if (gmarkers[i])
			} 	// end for ()
		elem = $("allIcons");
		elem.style.visibility = "visible";
		}			// end function

	function showAll() {
		for (var i = 0; i < gmarkers.length; i++) {
			if (gmarkers[i]) {
				gmarkers[i].show();
				}
			} 	// end for ()
		elem = $("allIcons");
		elem.style.visibility = "hidden";

		}			// end function




	function createMarker(point, tabs, color, id, fac_id) {						// (point, myinfoTabs,<?php 
    print $row['type'];
    ?>
, i)
		points = true;													// at least one
//		var letter = to_str(id);
		var fac_id = fac_id;	
		
		var icon = new GIcon(listIcon);
		var icon_url = "./our_icons/gen_fac_icon.php?blank=" + escape(icons[color]) + "&text=" + fac_id;

		icon.image = icon_url;		// 

		var marker = new GMarker(point, icon);
		marker.id = color;				// for hide/unhide - unused

		GEvent.addListener(marker, "click", function() {		// here for both side bar and icon click
			if (marker) {
				map.closeInfoWindow();
				which = id;
				gmarkers[which].hide();
				marker.openInfoWindowTabsHtml(infoTabs[id]);

				setTimeout(function() {										// wait for rendering complete
					if ($("detailmap")) {
						var dMapDiv = $("detailmap");
						var detailmap = new GMap2(dMapDiv);
						detailmap.addControl(new GSmallMapControl());
						detailmap.setCenter(point, 17);  						// larger # = closer
						detailmap.addOverlay(marker);
						}
					else {
						}
					},4000);				// end setTimeout(...)

				}		// end if (marker)
			});			// end GEvent.add Listener()

		gmarkers[id] = marker;									// marker to array for side_bar click function
		infoTabs[id] = tabs;									// tabs to array
		if (!(map_is_fixed)) {
			bounds.extend(point);
			}
		return marker;
		}				// end function create Marker()

	function createdummyMarker(point, tabs, color, id, fac_id) {						// 7/28/10
		points = true;													// at least one
//		var letter = to_str(id);
		var fac_id = fac_id;	
		
		var icon = new GIcon(listIcon);
		var icon_url = "./our_icons/question1.png";

		icon.image = icon_url;		// 

		var dummymarker = new GMarker(point, icon);
		dummymarker.id = color;				// for hide/unhide - unused

		GEvent.addListener(dummymarker, "click", function() {		// here for both side bar and icon click
			if (dummymarker) {
				map.closeInfoWindow();
				which = id;
				gmarkers[which].hide();
				dummymarker.openInfoWindowTabsHtml(infoTabs[id]);

				setTimeout(function() {										// wait for rendering complete
					if ($("detailmap")) {
						var dMapDiv = $("detailmap");
						var detailmap = new GMap2(dMapDiv);
						detailmap.addControl(new GSmallMapControl());
						detailmap.setCenter(point, 17);  						// larger # = closer
						detailmap.addOverlay(dummymarker);
						}
					else {
						}
					},4000);				// end setTimeout(...)

				}		// end if (marker)
			});			// end GEvent.add Listener()

		gmarkers[id] = dummymarker;									// marker to array for side_bar click function
		infoTabs[id] = tabs;									// tabs to array
		if (!(map_is_fixed)) {
			bounds.extend(point);
			}
		return dummymarker;
		}				// end function createdummyMarker()		

	function do_sidebar (sidebar, id, the_class, fac_id) {
		var fac_id = fac_id;
		side_bar_html += "<TR CLASS='" + colors[(id)%2] +"'>";
		side_bar_html += "<TD CLASS='" + the_class + "' onClick = myclick(" + id + "); >" + fac_id + sidebar +"</TD></TR>\n";		// 3/15/11
		}

	function do_sidebar_nm (sidebar, line_no, id, fac_id) {	
		var fac_id = fac_id;	
		var letter = to_str(line_no);	
		side_bar_html += "<TR CLASS='" + colors[(line_no)%2] +"'>";
		side_bar_html += "<TD onClick = myclick_nm(" + id + "); >" + fac_id + sidebar +"</TD></TR>\n";		// 1/23/09, 10/29/09 removed period, 11/11/09, 3/15/11
		}

	function myclick_nm(v_id) {				// Responds to sidebar click - view responder data
		document.view_form.id.value=v_id;
		document.view_form.submit();
		}

	function myclick(id) {					// Responds to sidebar click, then triggers listener above -  note [id]
		GEvent.trigger(gmarkers[id], "click");
		location.href = '#top';		// 11/11/090
		}

	function do_lat (lat) {
		document.forms[0].frm_lat.value=lat.toFixed(6);
		}
	function do_lng (lng) {
		document.forms[0].frm_lng.value=lng.toFixed(6);
		}

	function do_ngs() {						// LL to USNG into form
		document.forms[0].frm_ngs.disabled=false;
		document.forms[0].frm_ngs.value = LLtoUSNG(document.forms[0].frm_lat.value, document.forms[0].frm_lng.value, 5);
		document.forms[0].frm_ngs.disabled=true;
		}

	function do_sel_update_fac (in_unit, in_val) {							// 3/15/11
		to_server_fac(in_unit, in_val);
		}

	function to_server_fac(the_unit, the_status) {									// 3/15/11
		var querystr = "frm_responder_id=" + the_unit;
		querystr += "&frm_status_id=" + the_status;
	
		var url = "as_up_fac_status.php?" + querystr;			// 3/15/11
		var payload = syncAjax(url);						// 
		if (payload.substring(0,1)=="-") {	
			alert ("<?php 
    print __LINE__;
    ?>
: msg failed ");
			return false;
			}
		else {
			parent.frames['upper'].show_msg ('Facility status update applied!')
			return true;
			}				// end if/else (payload.substring(... )
		}		// end function to_server()

	var icons=new Array;							// maps type to icon blank

<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_types` ORDER BY `id`";
    // types in use
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $icons = $GLOBALS['fac_icons'];
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // map type to blank icon id
        $blank = $icons[$row['icon']];
        print "\ticons[" . $row['id'] . "] = " . $row['icon'] . ";\n";
        //
    }
    unset($result);
    $dzf = get_variable('def_zoom_fixed');
    print "\tvar map_is_fixed = ";
    print my_is_int($dzf) && $dzf == 2 || my_is_int($dzf) && $dzf == 3 ? "true;\n" : "false;\n";
    ?>
	var map;
	var side_bar_html = "<TABLE border=0 CLASS='sidebar' ID='tbl_facilities'>";
	side_bar_html += "<TR class='even'>	<TD colspan='99' ALIGN='center'><B><?php 
    print get_text("Facilities");
    ?>
 (<?php 
    print $facilities;
    ?>
)</B></TD></TR>";
	side_bar_html += "<TR class='odd'>	<TD colspan='99' ALIGN='center'>Click line or icon for details</TD></TR>";
	side_bar_html += "<TR class='even'>	<TD></TD><TD ALIGN='center'><B><?php 
    print get_text("Facility");
    ?>
</B></TD><TD ALIGN='center'><B><?php 
    print get_text("Type");
    ?>
</B></TD><TD ALIGN='center'><B><?php 
    print get_text("Status");
    ?>
</B></TD><TD ALIGN='center'><B><?php 
    print get_text("As of");
    ?>
</B></TD></TR>";
	var gmarkers = [];
	var infoTabs = [];
	var which;
	var i = <?php 
    print $start;
    ?>
;					// sidebar/icon index
	var points = false;								// none

	map = new GMap2($("map"));						// create the map
<?php 
    $maptype = get_variable('maptype');
    switch ($maptype) {
        case "1":
            break;
        case "2":
            ?>
		map.setMapType(G_SATELLITE_MAP);<?php 
            break;
        case "3":
            ?>
		map.setMapType(G_PHYSICAL_MAP);<?php 
            break;
        case "4":
            ?>
		map.setMapType(G_HYBRID_MAP);<?php 
            break;
        default:
            print "ERROR in " . basename(__FILE__) . " " . __LINE__ . "<BR />";
    }
    ?>

//	map.addControl(new GSmallMapControl());
	map.setUIToDefault();										// 8/13/10

	map.addControl(new GMapTypeControl());
<?php 
    if (get_variable('terrain') == 1) {
        ?>
	map.addMapType(G_PHYSICAL_MAP);
<?php 
    }
    ?>

	map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
	mapBounds=new GLatLngBounds(map.getBounds().getSouthWest(), map.getBounds().getNorthEast());

	var bounds = new GLatLngBounds();						// create  bounding box
	map.enableScrollWheelZoom();

	var listIcon = new GIcon();
	listIcon.image = "./markers/yellow.png";	// yellow.png - 16 X 28
	listIcon.shadow = "./markers/sm_shadow.png";
	listIcon.iconSize = new GSize(30, 30);
	listIcon.shadowSize = new GSize(16, 28);
	listIcon.iconAnchor = new GPoint(8, 28);
	listIcon.infoWindowAnchor = new GPoint(9, 2);
	listIcon.infoShadowAnchor = new GPoint(18, 25);

	GEvent.addListener(map, "infowindowclose", function() {		// re-center after  move/zoom
		map.addOverlay(gmarkers[which])
		});

<?php 
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    $status_vals = array();
    // build array of $status_vals
    $status_vals[''] = $status_vals['0'] = "TBD";
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_status` ORDER BY `id`";
    $result_st = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_st = stripslashes_deep(mysql_fetch_assoc($result_st))) {
        $temp = $row_st['id'];
        $status_vals[$temp] = $row_st['status_val'];
    }
    unset($result_st);
    $type_vals = array();
    // build array of $status_vals
    $type_vals[''] = $type_vals['0'] = "TBD";
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_types` ORDER BY `id`";
    $result_ty = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_ty = stripslashes_deep(mysql_fetch_assoc($result_ty))) {
        $temp = $row_ty['id'];
        $type_vals[$temp] = $row_ty['name'];
    }
    unset($result_ty);
    //	3/15/11
    $query = "SELECT *,UNIX_TIMESTAMP(updated) AS updated, `{$GLOBALS['mysql_prefix']}facilities`.id AS id, `{$GLOBALS['mysql_prefix']}facilities`.status_id AS status_id,\n\t\t`{$GLOBALS['mysql_prefix']}facilities`.description AS facility_description,\n\t\t`{$GLOBALS['mysql_prefix']}fac_types`.name AS fac_type_name, `{$GLOBALS['mysql_prefix']}facilities`.name AS name, `{$GLOBALS['mysql_prefix']}facilities`.street AS street,\n\t\t`{$GLOBALS['mysql_prefix']}facilities`.city AS city, `{$GLOBALS['mysql_prefix']}facilities`.state AS state \n\t\tFROM `{$GLOBALS['mysql_prefix']}facilities` \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}fac_types` ON `{$GLOBALS['mysql_prefix']}facilities`.type = `{$GLOBALS['mysql_prefix']}fac_types`.id \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}fac_status` ON `{$GLOBALS['mysql_prefix']}facilities`.status_id = `{$GLOBALS['mysql_prefix']}fac_status`.id \n\t\tORDER BY `{$GLOBALS['mysql_prefix']}facilities`.type ASC";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $i = 0;
    // counter
    // =============================================================================
    $utc = gmdate("U");
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // ==========  major while() for Facility ==========
        $the_bg_color = $GLOBALS['FACY_TYPES_BG'][$row['icon']];
        // 2/8/10
        $the_text_color = $GLOBALS['FACY_TYPES_TEXT'][$row['icon']];
        // 2/8/10
        $the_on_click = my_is_float($row['lat']) ? " onClick = myclick({$i}); " : " onClick = myclick_nm({$row['unit_id']}); ";
        //	3/15/11
        $got_point = FALSE;
        print "\n\t\tvar i={$i};\n";
        if (is_guest()) {
            $toedit = $tomail = $toroute = "";
        } else {
            $toedit = "&nbsp;&nbsp;&nbsp;&nbsp;<A HREF='{$_SESSION['facilitiesfile']}?func=responder&edit=true&id=" . $row['id'] . "'><U>Edit</U></A>";
            $tomail = "&nbsp;&nbsp;&nbsp;&nbsp;<SPAN onClick = 'do_mail_in_win({$row['id']})'><U><B>Email</B></U></SPAN>";
            $toroute = "&nbsp;<A HREF='{$_SESSION['facroutesfile']}?fac_id=" . $row['id'] . "'><U>Route To Facility</U></A>";
        }
        $temp = $row['status_id'];
        $the_status = array_key_exists($temp, $status_vals) ? $status_vals[$temp] : "??";
        $temp_type = $row['type'];
        $the_type = array_key_exists($temp_type, $type_vals) ? $type_vals[$temp_type] : "??";
        if (!$got_point && my_is_float($row['lat'])) {
            if ($row['lat'] == 0.999999 && $row['lng'] == 0.999999) {
                echo "\t\tvar point = new GLatLng(" . get_variable('def_lat') . ", " . get_variable('def_lng') . ");\n";
            } else {
                echo "\t\tvar point = new GLatLng(" . $row['lat'] . ", " . $row['lng'] . ");\n";
            }
            $got_point = TRUE;
        }
        $update_error = strtotime('now - 6 hours');
        // set the time for silent setting
        // name
        $name = $row['name'];
        //	10/8/09
        $temp = explode("/", $name);
        $display_name = $temp[0];
        //		$sidebar_line = "<TD CLASS='td_data' TITLE = '" . addslashes($display_name) . "'><U>" . addslashes(shorten($display_name, 48)) ."</U></TD>";	//	10/8/09
        //		$sidebar_line .= "<TD CLASS='td_data' TITLE = '" . addslashes ($the_type) . "'> " . shorten($the_type, 18) .
        //				"&nbsp;&nbsp;</TD>";
        //		$sidebar_line .= "<TD CLASS='td_data' TITLE = '" . addslashes ($the_status) . "'> " . shorten($the_status, 18) .
        //				"&nbsp;&nbsp;</TD>";
        $sidebar_line = "<TD TITLE = '" . addslashes($display_name) . "' {$the_on_click}><U><SPAN STYLE='background-color:{$the_bg_color};  opacity: .7; color:{$the_text_color};'>" . addslashes(shorten($display_name, 40)) . "</SPAN></U>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD><TD>{$the_type}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD>";
        $sidebar_line .= "<TD CLASS='td_data' TITLE = '" . addslashes($the_status) . "'> " . get_status_sel($row['id'], $row['status_id'], 'f') . "</TD>";
        //	3/15/11
        // as of
        $strike = $strike_end = "";
        $the_time = $row['updated'];
        $the_class = "td_data";
        $strike = $strike_end = "";
        $sidebar_line .= "<TD CLASS='{$the_class}'> {$strike}" . format_sb_date($the_time) . "{$strike_end}</TD>";
        // tab 1
        if (my_is_float($row['lat'])) {
            // position data?
            $temptype = $u_types[$row['type']];
            $the_type = $temptype[0];
            $tab_1 = "<TABLE CLASS='infowin' width='{$iw_width}'>";
            $tab_1 .= "<TR CLASS='even'><TD COLSPAN=2 ALIGN='center'><B>" . addslashes(shorten($display_name, 48)) . "</B> - " . $the_type . "</TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD ALIGN='right'>Description:&nbsp;</TD><TD ALIGN='left'>" . addslashes(shorten(str_replace($eols, " ", $row['description']), 32)) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='even'><TD ALIGN='right'>Status:&nbsp;</TD><TD ALIGN='left'>" . $the_status . " </TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD ALIGN='right'>Contact:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row['contact_name']) . " Via: " . addslashes($row['contact_email']) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='even'><TD ALIGN='right'>As of:&nbsp;</TD><TD ALIGN='left'>" . format_date($row['updated']) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'>" . $toedit . $tomail . "&nbsp;&nbsp;<A HREF='{$_SESSION['facilitiesfile']}?func=responder&view=true&id=" . $row['id'] . "'><U>View</U></A></TD></TR>";
            // 08/8/02
            $tab_1 .= "</TABLE>";
            $tab_2 = "<TABLE CLASS='infowin' width='{$iw_width}' ALIGN = 'center' >";
            $tab_2 .= "<TR CLASS='odd'><TD ALIGN='right' STYLE= 'width:50%'>Security contact:&nbsp;</TD><TD ALIGN='left' STYLE= 'width:50%'>" . addslashes($row['security_contact']) . " </TD></TR>";
            $tab_2 .= "<TR CLASS='even'><TD ALIGN='right'>Security email:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row['security_email']) . " </TD></TR>";
            $tab_2 .= "<TR CLASS='odd'><TD ALIGN='right'>Security phone:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row['security_phone']) . " </TD></TR>";
            $tab_2 .= "<TR CLASS='even'><TD ALIGN='right'>" . get_text("Access rules") . ":&nbsp;</TD><TD ALIGN='left'>" . addslashes(str_replace($eols, " ", $row['access_rules'])) . "</TD></TR>";
            $tab_2 .= "<TR CLASS='odd'><TD ALIGN='right'>Security reqs:&nbsp;</TD><TD ALIGN='left'>" . addslashes(str_replace($eols, " ", $row['security_reqs'])) . "</TD></TR>";
            $tab_2 .= "<TR CLASS='even'><TD ALIGN='right'>Opening hours:&nbsp;</TD><TD ALIGN='left'>" . addslashes(str_replace($eols, " ", $row['opening_hours'])) . "</TD></TR>";
            $tab_2 .= "<TR CLASS='odd'><TD ALIGN='right'>Prim pager:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row['pager_p']) . " </TD></TR>";
            $tab_2 .= "<TR CLASS='even'><TD ALIGN='right'>Sec pager:&nbsp;</TD><TD ALIGN='left'>" . addslashes($row['pager_s']) . " </TD></TR>";
            $tab_2 .= "</TABLE>";
            // tab 2
            $tabs_done = FALSE;
            // default
            if (!$tabs_done) {
                //
                ?>
			var myinfoTabs = [
				new GInfoWindowTab("<?php 
                print nl2brr(addslashes(shorten($row['name'], 10)));
                ?>
", "<?php 
                print $tab_1;
                ?>
"),
				new GInfoWindowTab("More ...", "<?php 
                print str_replace($eols, " ", $tab_2);
                ?>
"),
				new GInfoWindowTab("Zoom", "<div id='detailmap' class='detailmap'></div>")
				];

<?php 
            }
            // end if/else
            $name = $row['name'];
            // 10/8/09
            $temp = explode("/", $name);
            $index = substr($temp[count($temp) - 1], -6, strlen($temp[count($temp) - 1]));
            // 3/19/11
            if ($row['lat'] == 0.999999 && $row['lng'] == 0.999999) {
                // check for facilities added in no mpas mode 7/28/10
                ?>
		var fac_id = "<?php 
                print $index;
                ?>
";	//	10/8/09
		var the_class = ((map_is_fixed) && (!(mapBounds.containsLatLng(point))))? "emph" : "td_label";

		do_sidebar ("<?php 
                print $sidebar_line;
                ?>
", i, the_class, fac_id);
		var dummymarker = createdummyMarker(point, myinfoTabs,<?php 
                print $row['type'];
                ?>
, i, fac_id);	// 771 (point,tabs, color, id)
		map.addOverlay(dummymarker);
<?php 
            } else {
                ?>
		var fac_id = "<?php 
                print $index;
                ?>
";	//	10/8/09
		var the_class = ((map_is_fixed) && (!(mapBounds.containsLatLng(point))))? "emph" : "td_label";

		do_sidebar ("<?php 
                print $sidebar_line;
                ?>
", i, the_class, fac_id);
		var marker = createMarker(point, myinfoTabs,<?php 
                print $row['type'];
                ?>
, i, fac_id);	// 771 (point,tabs, color, id)
		map.addOverlay(marker);
<?php 
            }
            // End of check for facilities added in no maps mode 7/28/10
        } else {
            // end position data available
            $name = $row['name'];
            // 11/11/09
            $temp = explode("/", $name);
            $index = substr($temp[count($temp) - 1], -6, strlen($temp[count($temp) - 1]));
            // 3/19/11
            ?>
			var fac_id = "<?php 
            print $index;
            ?>
";	//	11/11/09
<?php 
            print "\tdo_sidebar_nm (\" {$sidebar_line} \" , i, {$row['id']}, fac_id);\n";
            // sidebar only - no map
        }
        $i++;
        // zero-based
    }
    // end  ==========  while() for Facility ==========
    ?>
	if (!(map_is_fixed)) {
		if (!points) {		// any?
			map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
			}
		else {
			center = bounds.getCenter();
			zoom = map.getBoundsZoomLevel(bounds);
			map.setCenter(center,zoom);
			}
		}

	side_bar_html+= "<TR CLASS='" + colors[i%2] +"'></TR>";
	side_bar_html +="<TR><TD><?php 
    print get_facilities_legend();
    ?>
</TD></TR>\n";	//	3/15/11
<?php 
    if (!empty($addon)) {
        print "\n\tside_bar_html +=\"" . $addon . "\"\n";
    }
    ?>
	side_bar_html +="</TABLE>\n";
	$("side_bar").innerHTML += side_bar_html;	// append the assembled side_bar_html contents to the side_bar div

<?php 
    do_kml();
    ?>


</SCRIPT>
<?php 
}
function do_list($unit_id = "")
{
    global $row_unit;
    ?>
<SCRIPT>
	var color=0;
	var last;				// id of last/current responder sidebar element
	var last_from;
	var last_to;
	
	if (GBrowserIsCompatible()) {
		var colors = new Array ('odd', 'even');
	    function setDirections(fromAddress, toAddress, locale) {
	    	last_from = fromAddress;
	    	last_to = toAddress;
//	    	alert("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
	    	gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
//	    	alert (235);
	    	}		// end function set Directions()
	
		function createMarker(point,sidebar,tabs, color, id) {		// Creates marker and sets up click event infowindow
			var icon = new GIcon(listIcon);
			icon.image = icons[color] + (id % 100) + ".png";		//e.g.,marker9.png, 100 icons limit
			var marker = new GMarker(point, icon);
			marker.id = color;				// for hide/unhide - unused
	
			GEvent.addListener(marker, "click", function() {		// here for both side bar and icon click
				map.closeInfoWindow();
				which = id;
				gmarkers[which].hide();
				marker.openInfoWindowTabsHtml(infoTabs[id]);
				var dMapDiv = document.getElementById("detailmap");
				var detailmap = new GMap2(dMapDiv);
				detailmap.addControl(new GSmallMapControl());
				detailmap.setCenter(point, 17);  					// larger # = closer - 7/16/10
				detailmap.addOverlay(marker);
				});
	
			gmarkers[id] = marker;							// marker to array for side_bar click function
			infoTabs[id] = tabs;							// tabs to array
	
			side_bar_html += "<TR CLASS='" + colors[(id+1)%2] +"' VALIGN='bottom' onClick = myclick(" + id + ");><TD>";
			side_bar_html += "<IMG BORDER=0 SRC='rtarrow.gif' ID = \"R" + id + "\"  STYLE = 'visibility:hidden;'></TD>";
			side_bar_html += "<TD CLASS='td_label'>" + (id) + ". "+ sidebar +"</TD></TR>\n";
			bounds.extend(point);							// extend the bounding box
	
			return marker;
			}				// end function create Marker()
	
		function myclick(id) {								// Responds to sidebar click
			if (!(lats[id])) {
				alert("Cannot route -  no position data currently available");
				return false;
				}
			else {
				which = id;
				document.getElementById(last).style.visibility = "hidden";		// hide last check
				var element= "R"+id;
				document.getElementById(element).style.visibility = "visible";
				last = element;													// new 'last' = current selection
//				GEvent.trigger(gmarkers[id], "click");
				var thelat = <?php 
    print $row_unit['lat'];
    ?>
; var thelng = <?php 
    print $row_unit['lng'];
    ?>
;
				setDirections(lats[id] + " " + lngs[id], thelat + " " + thelng, "en_US");
				}
			}
	
		function doGrid() {
			map.addOverlay(new LatLonGraticule());
			}
	
		function handleErrors(){		//G_GEO_UNKNOWN_DIRECTIONS 
			if (gdir.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS )
				alert("290: No driving directions are available to/from this location.\nError code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
				alert("292: No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
				alert("294: A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
				alert("296: The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	//		else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//			alert("296: The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_BAD_KEY)
				alert("300: The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
				alert("302: A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
			else alert("303: An unknown error occurred.");
			}		// end function handleErrors()
	
		function onGDirectionsLoad(){ 
			var temp = gdir.getSummaryHtml();
//			alert(extr_num(temp));
//	 		Use this function to access information about the latest load() results.
//	 			e.g.
//	 		document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
//	 		and yada yada yada...
			}		// function onGDirectionsLoad()

		function guest () {
			alert ("Demonstration only.  Guests may not commit dispatch!");
			}
			
		function validate(){		// frm_id_str
			msgstr="";
			for (var i =0;i<unit_sets.length;i++) {
				if (unit_sets[i]) {
					msgstr+=unit_names[i]+"\n";
					document.routes_Form.frm_id_str.value += unit_ids[i] + ",";
					}
				}
			if (msgstr.length==0) {
				var more = (nr_units>1)? "s": ""
				alert ("Please select unit" + more + ", or cancel");
				return false;
				}
			else {
				if (confirm ("Please confirm Unit dispatch as follows\n\n" + msgstr)) {
					document.routes_Form.frm_id_str.value = document.routes_Form.frm_id_str.value.substring(0, document.routes_Form.frm_id_str.value.length - 1);	// drop trailing separator
					document.routes_Form.frm_name_str.value = msgstr;	// for re-use
					document.routes_Form.submit();
					}
				else {
					document.routes_Form.frm_id_str.value="";	
					return false;
					}
				}

			}		// end function validate()
	
		function ifexists(myarray,myid) {
			var str_key = " " + myid;		// force associative
			return ((typeof myarray[str_key])!="undefined");		// exists if not undefined
			}		// end function ifexists()
			
		var icons=[];						// note globals
		icons[1] = "./markers/YellowIcons/marker";		//e.g.,marker9.png
		icons[2] = "./markers/RedIcons/marker";
		icons[3] = "./markers/BlueIcons/marker";
		icons[4] = "./markers/GreenIcons/marker";
		icons[5] = "./markers/WhiteIcons/marker";
	
		var map;
		var center;
		var zoom;
		
	    var gdir;				// directions
	    var geocoder = null;
	    var addressMarker;
		
		var side_bar_html = "<TABLE border=0 CLASS='sidebar' ID='tbl_responders'>";
		side_bar_html += "<TR class='even'>	<TD colspan=99 ALIGN='center'><B>Routes to Incident <I><?php 
    print shorten($row_unit['scope'], 20);
    ?>
</I></B></TD></TR>";
		side_bar_html += "<TR class='odd'>	<TD colspan=99 ALIGN='center'>Click line or icon for route</TD></TR>";
		side_bar_html += "<TR class='even'>	<TD COLSPAN=2></TD><TD ALIGN='center'>Unit</TD><TD ALIGN='center'>SLD</TD><TD ALIGN='center'>Status</TD><TD>M</TD><TD ALIGN='center'>As of</TD><TD>Assign</TD></TR>";
		var gmarkers = [];
		var infoTabs = [];
		var lats = [];
		var lngs = [];
		var distances = [];
		var which;			// marker last selected
		var i = 0;			// sidebar/icon index
	
		map = new GMap2(document.getElementById("map_canvas"));		// create the map
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
<?php 
    if (get_variable('terrain') == 1) {
        ?>
		map.addMapType(G_PHYSICAL_MAP);
<?php 
    }
    ?>
	
		map.enableScrollWheelZoom(); 	

		gdir = new GDirections(map, document.getElementById("directions"));
		
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
		
		map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);		// <?php 
    echo get_variable('def_lat');
    ?>
	
		var bounds = new GLatLngBounds();						// create empty bounding box
	
		var listIcon = new GIcon();
		listIcon.image = "./markers/yellow.png";	// yellow.png - 16 X 28
		listIcon.shadow = "./markers/sm_shadow.png";
		listIcon.iconSize = new GSize(20, 34);
		listIcon.shadowSize = new GSize(37, 34);
		listIcon.iconAnchor = new GPoint(8, 28);
		listIcon.infoWindowAnchor = new GPoint(9, 2);
		listIcon.infoShadowAnchor = new GPoint(18, 25);
	
		var newIcon = new GIcon();
		newIcon.image = "./markers/white.png";	// yellow.png - 20 X 34
		newIcon.shadow = "./markers/shadow.png";
		newIcon.iconSize = new GSize(20, 34);
		newIcon.shadowSize = new GSize(37, 34);
		newIcon.iconAnchor = new GPoint(8, 28);
		newIcon.infoWindowAnchor = new GPoint(9, 2);
		newIcon.infoShadowAnchor = new GPoint(18, 25);
																	// set Incident position
		var point = new GLatLng(<?php 
    print $row_unit['lat'];
    ?>
, <?php 
    print $row_unit['lng'];
    ?>
);	
		bounds.extend(point);										// Incident into BB
	
		GEvent.addListener(map, "infowindowclose", function() {		// re-center after  move/zoom
			setDirections(last_from, last_to, "en_US") ;
//			map.setCenter(center,zoom);
//			alert ("289 " + which);
//			map.addOverlay(gmarkers[which])
//			alert ("290 " + zoom);
			});
	
//		GEvent.addListener(map, "click", function(marker, point) {
//			if (marker) {
//				document.forms[0].frm_lat.disabled=document.forms[0].frm_lat.disabled=false;
//				document.forms[0].frm_lat.value=document.forms[0].frm_lng.value="";
//				document.forms[0].frm_lat.disabled=document.forms[0].frm_lat.disabled=true;
//				}
//			});				// end GEvent.addListener() "click"
		unit_names = 	new Array();				// names 
		unit_sets = 	new Array();				// settings
		unit_ids = 		new Array();				// id's
		unit_assigns = 	new Array();				// unit id's assigned this incident
		var nr_units = 	0;
<?php 
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    //						build js array of responders to this ticket - possibly none
    $query = "SELECT `ticket_id`, `responder_id` FROM `{$GLOBALS['mysql_prefix']}assigns` WHERE `ticket_id` = " . $_GET['ticket_id'];
    //		dump($query);
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($assigns_row = stripslashes_deep(mysql_fetch_array($result))) {
        print "\t\tunit_assigns[' '+ " . $assigns_row['responder_id'] . "]= true;\n";
        // note string forced
    }
    print "\n";
    $where = empty($unit_id) ? "" : " WHERE `{$GLOBALS['mysql_prefix']}responder`.`id` = {$unit_id} ";
    // revised 5/23/08 per AD7PE
    $query = "SELECT *, UNIX_TIMESTAMP(updated) AS updated, `{$GLOBALS['mysql_prefix']}responder`.`id` AS `unit_id`, `s`.`status_val` AS `unitstatus` FROM {$GLOBALS['mysql_prefix']}responder\n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}un_status` `s` ON (`{$GLOBALS['mysql_prefix']}responder`.`un_status_id` = `s`.`id`)\n\t\t\t{$where}\n\t\t\tORDER BY `name` ASC, `unit_id` ASC";
    //		dump($query);
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    if (mysql_affected_rows() > 0) {
        // major while ... for RESPONDER data starts here
        $i = 1;
        // sidebar/icon index
        while ($unit_row = stripslashes_deep(mysql_fetch_array($result))) {
            ?>
				nr_units++;
				var i = <?php 
            print $i;
            ?>
;						// top of loop
				unit_names[i] = '<?php 
            print $unit_row['name'];
            ?>
';	// unit name
				unit_sets[i] = false;								// pre-set checkbox settings				
				unit_ids[i] = <?php 
            print $unit_row['unit_id'];
            ?>
;
				distances[i]=9999.9;
<?php 
            $tab_1 = "<TABLE CLASS='infowin' width='" . $_SESSION['scr_width'] / 4 . "px'>";
            $tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'>" . shorten($unit_row['name'], 48) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='even'><TD>Description:</TD><TD>" . shorten(str_replace($eols, " ", $unit_row['description']), 32) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD>Status:</TD><TD>" . $unit_row['unitstatus'] . " </TD></TR>";
            $tab_1 .= "<TR CLASS='even'><TD>Contact:</TD><TD>" . $unit_row['contact_name'] . " Via: " . $unit_row['contact_via'] . "</TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD>As of:</TD><TD>" . format_date($unit_row['updated']) . "</TD></TR>";
            $tab_1 .= "</TABLE>";
            ?>
				new_element = document.createElement("input");								// please don't ask!
				new_element.setAttribute("type", 	"checkbox");
				new_element.setAttribute("name", 	"unit_<?php 
            print $unit_row['unit_id'];
            ?>
");
				new_element.setAttribute("id", 		"element_id");
				new_element.setAttribute("style", 	"visibility:hidden");
				document.forms['routes_Form'].appendChild(new_element);
				var dist_mi = "na";
<?php 
            if (intval($unit_row['mobile']) == 1) {
                $thespeed = "na";
                $query = "SELECT *,UNIX_TIMESTAMP(packet_date) AS packet_date, UNIX_TIMESTAMP(updated) AS updated FROM {$GLOBALS['mysql_prefix']}tracks\n\t\t\t\t\t\tWHERE `source`= '{$unit_row['callsign']}' ORDER BY `packet_date` DESC LIMIT 1";
                //					dump ($query);
                $result_tr = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
                if (mysql_affected_rows() > 0) {
                    // got a track?
                    $track_row = stripslashes_deep(mysql_fetch_array($result_tr));
                    // most recent track report
                    $tab_2 = "<TABLE CLASS='infowin' width='" . $_SESSION['scr_width'] / 4 . "px'>";
                    $tab_2 .= "<TR><TH CLASS='even' COLSPAN=2>" . $track_row['source'] . "</TH></TR>";
                    $tab_2 .= "<TR CLASS='odd'><TD>Course: </TD><TD>" . $track_row['course'] . ", Speed:  " . $track_row['speed'] . ", Alt: " . $track_row['altitude'] . "</TD></TR>";
                    $tab_2 .= "<TR CLASS='even'><TD>Closest city: </TD><TD>" . $track_row['closest_city'] . "</TD></TR>";
                    $tab_2 .= "<TR CLASS='odd'><TD>Status: </TD><TD>" . $track_row['status'] . "</TD></TR>";
                    $tab_2 .= "<TR CLASS='even'><TD>As of: </TD><TD>" . format_date($track_row['packet_date']) . "</TD></TR>";
                    $tab_2 .= "</TABLE>";
                    ?>
						var myinfoTabs = [
							new GInfoWindowTab("<?php 
                    print nl2brr(shorten($unit_row['name'], 8));
                    ?>
", "<?php 
                    print $tab_1;
                    ?>
"),
							new GInfoWindowTab("<?php 
                    print $track_row['source'];
                    ?>
", "<?php 
                    print $tab_2;
                    ?>
"),
							new GInfoWindowTab("Zoom", "<DIV ID='detailmap' CLASS='detailmap'></DIV>")
							];
		
						lats[i] = <?php 
                    print $track_row['latitude'];
                    ?>
;									// now compute distance - in km
						lngs[i] = <?php 
                    print $track_row['longitude'];
                    ?>
;
						distances[i] = distCosineLaw(parseFloat(lats[i]), parseFloat(lngs[i]), parseFloat(<?php 
                    print $row_unit['lat'];
                    ?>
), parseFloat(<?php 
                    print $row_unit['lng'];
                    ?>
));
					    var km2mi = <?php 
                    print $conversion;
                    ?>
;				// 
						var dist_mi = ((distances[i] * km2mi).toFixed(1)).toString();				// to miles
<?php 
                    $thespeed = $track_row['speed'] == 0 ? "<FONT COLOR='red'><B>&bull;</B></FONT>" : "<FONT COLOR='green'><B>&bull;</B></FONT>";
                    if ($track_row['speed'] >= 50) {
                        $thespeed = "<FONT COLOR='WHITE'><B>&bull;</B></FONT>";
                    }
                    ?>
						var point = new GLatLng(<?php 
                    print $track_row['latitude'];
                    ?>
, <?php 
                    print $track_row['longitude'];
                    ?>
);	// mobile position
						bounds.extend(point);															// point into BB
<?php 
                } else {
                    // no track data
                    ?>
						var dist_mi = "na";
<?php 
                }
                // end  no track data
                ?>
						
					sidebar_line = "<TD><?php 
                print shorten($unit_row['name'], 32);
                ?>
</TD><TD>"+ dist_mi+"</TD>";
					sidebar_line += "<TD CLASS='td_data'><?php 
                print shorten($unit_row['unitstatus'], 12);
                ?>
</TD>";
					sidebar_line += "<TD CLASS='td_data'><?php 
                print $thespeed;
                ?>
</TD>";
					sidebar_line += "<TD CLASS='td_data'><?php 
                print format_sb_date($unit_row['updated']);
                ?>
</TD>";
					var is_checked = (ifexists(unit_assigns,'<?php 
                print $unit_row['unit_id'];
                ?>
'))? " CHECKED ": "";
					var is_disabled = (ifexists(unit_assigns,'<?php 
                print $unit_row['unit_id'];
                ?>
'))? " DISABLED ": "";
					sidebar_line += "<TD ALIGN='center'><INPUT TYPE='checkbox' " + is_checked + is_disabled + " NAME = 'unit_" + <?php 
                print $unit_row['unit_id'];
                ?>
 + "' onClick='unit_sets[<?php 
                print $i;
                ?>
]=this.checked;'></TD>";
					var marker = createMarker(point, sidebar_line, myinfoTabs,<?php 
                print $unit_row['type'];
                ?>
, i);	// (point,sidebar,tabs, color, id)
					map.addOverlay(marker);
<?php 
            } else {
                // fixed position with location info.
                ?>
						var myinfoTabs = [
							new GInfoWindowTab("<?php 
                print nl2brr(shorten($unit_row['name'], 12));
                ?>
", "<?php 
                print $tab_1;
                ?>
"),
							new GInfoWindowTab("Zoom", "<DIV ID='detailmap' CLASS='detailmap'></DIV>")
							];
						
						lats[i] = <?php 
                print $unit_row['lat'];
                ?>
;									// now compute distance - in km
						lngs[i] = <?php 
                print $unit_row['lng'];
                ?>
;
						distances[i] = distCosineLaw(parseFloat(lats[i]), parseFloat(lngs[i]), parseFloat(<?php 
                print $row_unit['lat'];
                ?>
), parseFloat(<?php 
                print $row_unit['lng'];
                ?>
));	// note: km
					    var km2mi = <?php 
                print $conversion;
                ?>
;				// 
						var dist_mi = ((distances[i] * km2mi).toFixed(1)).toString();				// to feet
			
						sidebar_line = "<TD><?php 
                print shorten($unit_row['name'], 16);
                ?>
</TD><TD>"+ dist_mi+"</TD>";
						sidebar_line += "<TD CLASS='td_data'><?php 
                print shorten($unit_row['unitstatus'], 12);
                ?>
</TD>";
						sidebar_line += "<TD CLASS='td_data'></TD><TD CLASS='td_data'><?php 
                print format_sb_date($unit_row['updated']);
                ?>
</TD>"; 
						var is_checked = (ifexists(unit_assigns,'<?php 
                print $unit_row['unit_id'];
                ?>
'))? " CHECKED ": "";
						var is_disabled = (ifexists(unit_assigns,'<?php 
                print $unit_row['unit_id'];
                ?>
'))? " DISABLED ": "";
						sidebar_line += "<TD ALIGN='center'><INPUT TYPE='checkbox' " + is_checked  + is_disabled + " NAME = 'unit_" + <?php 
                print $unit_row['unit_id'];
                ?>
 + "' onClick='unit_sets[<?php 
                print $i;
                ?>
]=this.checked;'></TD>";
		
						var point = new GLatLng(<?php 
                print $unit_row['lat'];
                ?>
, <?php 
                print $unit_row['lng'];
                ?>
);	// for each responder
						bounds.extend(point);																// point into BB
						
						var marker = createMarker(point, sidebar_line, myinfoTabs, <?php 
                print $unit_row['type'];
                ?>
, i);	// (point,sidebar,tabs, color, id)
						map.addOverlay(marker);						
<?php 
            }
            // end if/else (mysql_affected_rows()>0;) - no track data
            $i++;
        }
        // end major while ($unit_row = ...) for each responder
    }
    // end if(mysql_affected_rows()>0)
    //					responders complete
    ?>
		if (nr_units==0) {
			side_bar_html +="<TR CLASS='odd'><TD ALIGN='center' COLSPAN=99><BR /><B>No Units!</B></TD></TR>";;		
			map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
			}
		else {
			center = bounds.getCenter();
			zoom = map.getBoundsZoomLevel(bounds);		// -1 for further out	
			map.setCenter(center,zoom);
			side_bar_html+= "<TR CLASS='" + colors[i%2] +"'><TD COLSPAN=99>&nbsp;</TD></TR>";
			side_bar_html+= "<TR CLASS='" + colors[(i+1)%2] +"'><TD COLSPAN=99 ALIGN='center'><B>M</B>obility:&nbsp;&nbsp; stopped: <FONT COLOR='red'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;moving: <FONT COLOR='green'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;fast: <FONT COLOR='white'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;silent: <FONT COLOR='black'><B>&bull;</B></FONT></TD></TR>";
			side_bar_html+= "<TR><TD>&nbsp;</TD></TR>";
<?php 
    $thefunc = is_guest() ? "guest()" : "validate()";
    // reject guest attempts
    ?>
			side_bar_html+= "<TR><TD COLSPAN=99 ALIGN='center'><INPUT TYPE='button' VALUE='Cancel'  onClick='history.back();'>";
			side_bar_html+= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<INPUT TYPE='button' value='DISPATCH SELECTED UNITS' onClick = '<?php 
    print $thefunc;
    ?>
' />";
			side_bar_html+= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<INPUT TYPE='RESET' VALUE='Reset' onClick = 'doReset()'>";
			side_bar_html+= "</TD></TR>";
			}
	
		side_bar_html +="</TABLE>\n";
		document.getElementById("side_bar").innerHTML = side_bar_html;	// put the assembled side_bar_html contents into the side_bar div
	
		var thelat = <?php 
    print $row_unit['lat'];
    ?>
; var thelng = <?php 
    print $row_unit['lng'];
    ?>
;
		var start = min(distances);		// min straight-line distance to Incident
		if (start>0) {
			var last= "R"+start;			//
			document.getElementById(last).style.visibility = "visible";		// show link check image at the selected sidebar element
			setDirections(lats[start] + " " + lngs[start], thelat + " " + thelng, "en_US");
			}	
		}		// end if (GBrowserIsCompatible())

	else {
		alert("Sorry,  browser compatibility problem. Contact your tech support group.");
		}
	</SCRIPT>
	
<?php 
}
function list_facilities($addon = '', $start)
{
    global $iw_width, $u_types, $tolerance;
    //	$assigns = array();
    //	$tickets = array();
    // $query = "SELECT `$GLOBALS[mysql_prefix]assigns`.`ticket_id`, `$GLOBALS[mysql_prefix]assigns`.`responder_id`, `$GLOBALS[mysql_prefix]ticket`.`scope` AS `ticket` FROM `$GLOBALS[mysql_prefix]assigns` LEFT JOIN `$GLOBALS[mysql_prefix]ticket` ON `$GLOBALS[mysql_prefix]assigns`.`ticket_id`=`$GLOBALS[mysql_prefix]ticket`.`id`";
    // $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename( __FILE__), __LINE__);
    // while ($row_as = stripslashes_deep(mysql_fetch_array($result_as))) {
    // $assigns[$row_as['responder_id']] = $row_as['ticket'];
    // $tickets[$row_as['responder_id']] = $row_as['ticket_id'];
    // }
    // unset($result_as);
    // $calls = array();
    // $calls_nr = array();
    // $calls_time = array();
    ?>

<SCRIPT >

var color=0;
	var colors = new Array ('odd', 'even');

	function hideDiv(div_area, hide_cont, show_cont) {	//	3/15/11
		if (div_area == "buttons_sh") {
			var controlarea = "hide_controls";
			}
		if (div_area == "resp_list_sh") {
			var controlarea = "resp_list";
			}
		if (div_area == "facs_list_sh") {
			var controlarea = "facs_list";
			}
		if (div_area == "incs_list_sh") {
			var controlarea = "incs_list";
			}
		if (div_area == "region_boxes") {
			var controlarea = "region_boxes";
			}			
		var divarea = div_area 
		var hide_cont = hide_cont 
		var show_cont = show_cont 
		if($(divarea)) {
			$(divarea).style.display = 'none';
			$(hide_cont).style.display = 'none';
			$(show_cont).style.display = '';
			} 
		var params = "f_n=" +controlarea+ "&v_n=h&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";
		var url = "persist2.php";
		sendRequest (url, gb_handleResult, params);			
		} 

	function showDiv(div_area, hide_cont, show_cont) {	//	3/15/11
		if (div_area == "buttons_sh") {
			var controlarea = "hide_controls";
			}
		if (div_area == "resp_list_sh") {
			var controlarea = "resp_list";
			}
		if (div_area == "facs_list_sh") {
			var controlarea = "facs_list";
			}
		if (div_area == "incs_list_sh") {
			var controlarea = "incs_list";
			}
		if (div_area == "region_boxes") {
			var controlarea = "region_boxes";
			}				
		var divarea = div_area
		var hide_cont = hide_cont 
		var show_cont = show_cont 
		if($(divarea)) {
			$(divarea).style.display = '';
			$(hide_cont).style.display = '';
			$(show_cont).style.display = 'none';
			}
		var params = "f_n=" +controlarea+ "&v_n=s&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";
		var url = "persist2.php";
		sendRequest (url, gb_handleResult, params);					
		} 	
	
	function do_sidebar (sidebar, id, the_class, fac_id, fac_index) {
		var fac_id = fac_id;
		side_bar_html += "<TR CLASS='" + colors[(id)%2] +"' onClick = myclick(" + fac_index + ");>";
//		side_bar_html += "<TD CLASS='" + the_class + "'>" + fac_id + sidebar +"</TD></TR>\n";	//10/29/09 removed period
		side_bar_html += sidebar + "</TR>\n";	//10/29/09 removed period
		}

	function myclick(fac_index) {				// Responds to sidebar click - view facility data
		document.view_form.id.value=fac_index;
		document.view_form.submit();
		}

	function do_sidebar_nm (sidebar, line_no, id, fac_id) {	
		var fac_id = fac_id;	
		var letter = to_str(line_no);	
		side_bar_html += "<TR CLASS='" + colors[(line_no)%2] +"'>";
		side_bar_html += "<TD onClick = myclick_nm(" + id + "); >" + fac_id + sidebar +"</TD></TR>\n";		// 1/23/09, 10/29/09 removed period, 11/11/09, 3/15/11
		}

	function myclick_nm(v_id) {				// Responds to sidebar click - view responder data
		document.view_form.id.value=v_id;
		document.view_form.submit();
		}
		
	var icons=new Array;							// maps type to icon blank

<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_types` ORDER BY `id`";
    // types in use
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $icons = $GLOBALS['fac_icons'];
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // map type to blank icon id
        $blank = $icons[$row['icon']];
        print "\ticons[" . $row['id'] . "] = " . $row['icon'] . ";\n";
        //
    }
    unset($result);
    $dzf = get_variable('def_zoom_fixed');
    print "\tvar map_is_fixed = ";
    print my_is_int($dzf) && $dzf == 2 || my_is_int($dzf) && $dzf == 3 ? "true;\n" : "false;\n";
    ?>
	var side_bar_html = "<TABLE border=0 CLASS='sidebar' ID='tbl_facilities' WIDTH = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.6));
    ?>
 >";
	side_bar_html += "<TR class='even'><TD ALIGN='left'><B>Icon</B></TD><TD ALIGN='left'><B><?php 
    print get_text("Handle");
    ?>
</B></TD><TD ALIGN='left'><B><?php 
    print get_text("Facility");
    ?>
</B></TD><TD ALIGN='left'><B><?php 
    print get_text("Type");
    ?>
</B></TD><TD ALIGN='left'><B><?php 
    print get_text("Status");
    ?>
</B></TD><TD ALIGN='center'><B><?php 
    print get_text("As of");
    ?>
</B></TD></TR>";

	var which;
	var i = <?php 
    print $start;
    ?>
;					// sidebar/icon index
	var points = false;								// none

<?php 
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    //	$bulls = array(0 =>"",1 =>"red",2 =>"green",3 =>"white",4 =>"black");
    $status_vals = array();
    // build array of $status_vals
    $status_vals[''] = $status_vals['0'] = "TBD";
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_status` ORDER BY `id`";
    $result_st = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_st = stripslashes_deep(mysql_fetch_assoc($result_st))) {
        $temp = $row_st['id'];
        $status_vals[$temp] = $row_st['status_val'];
    }
    unset($result_st);
    $type_vals = array();
    // build array of $status_vals
    $type_vals[''] = $type_vals['0'] = "TBD";
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}fac_types` ORDER BY `id`";
    $result_ty = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_ty = stripslashes_deep(mysql_fetch_assoc($result_ty))) {
        $temp = $row_ty['id'];
        $type_vals[$temp] = $row_ty['name'];
    }
    unset($result_ty);
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}';";
    // 6/10/11
    $result = mysql_query($query);
    // 6/10/11
    $al_groups = array();
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // 6/10/11
        $al_groups[] = $row['group'];
    }
    if (isset($_SESSION['viewed_groups'])) {
        //	6/10/11
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    }
    if (!isset($curr_viewed)) {
        $x = 0;
        //	6/10/11
        $where2 = "WHERE (";
        //	6/10/11
        foreach ($al_groups as $grp) {
            //	6/10/11
            $where3 = count($al_groups) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    } else {
        $x = 0;
        //	6/10/11
        $where2 = "WHERE (";
        //	6/10/11
        foreach ($curr_viewed as $grp) {
            //	6/10/11
            $where3 = count($curr_viewed) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    }
    $where2 .= "AND `a`.`type` = 3";
    //	6/10/11
    //	3/15/11, 6/10/11
    $query = "SELECT *,UNIX_TIMESTAMP(updated) AS updated,\n\t\t`t`.`id` AS `type_id`, \t\n\t\t`f`.id AS `id`, \n\t\t`f`.status_id AS status_id,\n\t\t`f`.description AS facility_description,\n\t\t`t`.name AS fac_type_name, \n\t\t`f`.name AS name, `f`.street AS street,\n\t\t`f`.city AS city, `f`.state AS state \n\t\tFROM `{$GLOBALS['mysql_prefix']}facilities` `f`\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON ( `f`.`id` = a.resource_id )\t\t\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}fac_types` `t` ON `f`.type = `t`.id \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}fac_status` `s` ON `f`.status_id = `s`.id \n\t\t{$where2}  GROUP BY `f`.id ORDER BY `f`.type ASC";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $num_facilities = mysql_affected_rows();
    $i = 0;
    // counter
    // =============================================================================
    $utc = gmdate("U");
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // ==========  major while() for Facility ==========
        $fac_gps = get_allocates(3, $row['id']);
        //	6/10/11
        $grp_names = "Groups Assigned: ";
        //	6/10/11
        $y = 0;
        //	6/10/11
        foreach ($fac_gps as $value) {
            //	6/10/11
            $counter = count($fac_gps) > $y + 1 ? ", " : "";
            $grp_names .= get_groupname($value);
            $grp_names .= $counter;
            $y++;
        }
        $grp_names .= " / ";
        $the_bg_color = $GLOBALS['FACY_TYPES_BG'][$row['icon']];
        // 2/8/10
        $the_text_color = $GLOBALS['FACY_TYPES_TEXT'][$row['icon']];
        // 2/8/10
        $the_on_click = my_is_float($row['lat']) ? " onClick = myclick({$i}); " : " onClick = myclick_nm({$row['id']}); ";
        //	3/15/11
        $got_point = FALSE;
        print "\n\t\tvar i={$i};\n";
        if (is_guest()) {
            $toedit = $tomail = $toroute = "";
        } else {
            $toedit = "&nbsp;&nbsp;&nbsp;&nbsp;<A HREF='facilities_nm.php?func=responder&edit=true&id=" . $row['id'] . "'><U>Edit</U></A>";
            $tomail = "&nbsp;&nbsp;&nbsp;&nbsp;<SPAN onClick = 'do_mail_in_win({$row['id']})'><U><B>Email</B></U></SPAN>";
            $toroute = "&nbsp;<A HREF='routes_nm.php?fac_id=" . $row['id'] . "'><U>Route To Facility</U></A>";
        }
        $temp = $row['status_id'];
        $the_status = array_key_exists($temp, $status_vals) ? $status_vals[$temp] : "??";
        $temp_type = $row['type_id'];
        $the_type = array_key_exists($temp_type, $type_vals) ? $type_vals[$temp_type] : "??";
        $update_error = strtotime('now - 6 hours');
        // set the time for silent setting
        // name
        $name = $row['name'];
        //	10/8/09
        $fac_index = $row['id'];
        //	10/8/09
        $temp = explode("/", $name);
        $display_name = $temp[0];
        $icon_str = $row['icon_str'];
        $sidebar_line = "<TD TITLE = '{$icon_str}'>" . $icon_str . "</TD>";
        // 10/8/09
        $handle = addslashes($row['handle']);
        //	5/30/10
        $sidebar_line .= "<TD TITLE = '{$handle}'>" . shorten($handle, 16) . "</TD>";
        // 10/8/09
        $sidebar_line .= "<TD TITLE = '" . $grp_names . "Facility Name: " . addslashes($display_name) . "' {$the_on_click}><U><SPAN STYLE='background-color:{$the_bg_color};  opacity: .7; color:{$the_text_color};'>" . addslashes(shorten($display_name, 40)) . "</SPAN></U>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD><TD>{$the_type}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD>";
        //	6/10/11
        $sidebar_line .= "<TD CLASS='td_data' TITLE = '" . addslashes($the_status) . "'> " . get_status_sel($row['id'], $row['status_id'], 'f') . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD>";
        //	3/15/11
        // as of
        $strike = $strike_end = "";
        $the_time = $row['updated'];
        $the_class = "td_data";
        $strike = $strike_end = "";
        $sidebar_line .= "<TD CLASS='{$the_class}'> {$strike}" . format_sb_date($the_time) . "{$strike_end}</TD>";
        $name = $row['name'];
        // 10/8/09
        $fac_index = $row['id'];
        //	10/8/09
        $temp = explode("/", $name);
        $index = substr($temp[count($temp) - 1], -6, strlen($temp[count($temp) - 1]));
        // 3/19/11
        ?>
		var fac_id = "<?php 
        print $index;
        ?>
";	//	10/8/09
		var fac_index = "<?php 
        print $fac_index;
        ?>
";	//	10/8/09		
		var the_class = "td_label";

<?php 
        print "\tdo_sidebar (\" {$sidebar_line} \", i, the_class, fac_id, fac_index);\n";
        $i++;
        // zero-based
    }
    // end  ==========  while() for Facility ==========
    ?>
var buttons_html = "";
<?php 
    if (!empty($addon)) {
        print "\n\tbuttons_html +=\"" . $addon . "\"\n";
    }
    ?>
	side_bar_html +="</TABLE>\n";
	$("side_bar").innerHTML += side_bar_html;	// append the assembled side_bar_html contents to the side_bar div
	$("buttons").innerHTML = buttons_html;	// append the assembled side_bar_html contents to the side_bar div
	$("num_facilities").innerHTML = <?php 
    print $num_facilities;
    ?>
;

</SCRIPT>

<?php 
}
예제 #8
0
function list_responders($addon = '', $start)
{
    global $iw_width, $u_types, $tolerance;
    $assigns = array();
    // 08/8/3
    $tickets = array();
    // ticket id's
    // 7/18/10
    $query = "SELECT `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`, `{$GLOBALS['mysql_prefix']}assigns`.`responder_id`,\n\t\t`{$GLOBALS['mysql_prefix']}ticket`.`scope` AS `ticket` \n\t\tFROM `{$GLOBALS['mysql_prefix']}assigns` \t\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` ON `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`=`{$GLOBALS['mysql_prefix']}ticket`.`id`\n\t\tWHERE ( `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' )";
    $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_as = stripslashes_deep(mysql_fetch_array($result_as))) {
        $assigns[$row_as['responder_id']] = $row_as['ticket'];
        $tickets[$row_as['responder_id']] = $row_as['ticket_id'];
    }
    unset($result_as);
    $calls = array();
    // 6/17/08
    $calls_nr = array();
    $calls_time = array();
    $query = "SELECT * , UNIX_TIMESTAMP(packet_date) AS `packet_date` FROM `{$GLOBALS['mysql_prefix']}tracks` ORDER BY `packet_date` ASC";
    // 6/17/08
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), __FILE__, __LINE__);
    while ($row = mysql_fetch_array($result)) {
        if (isset($calls[$row['source']])) {
            // array_key_exists ( mixed key, array search )
            $calls_nr[$row['source']]++;
        } else {
            //			array_push ($calls, trim($row['source']));
            $calls[trim($row['source'])] = TRUE;
            $calls_nr[$row['source']] = 1;
        }
        $calls_time[$row['source']] = $row['packet_date'];
        // save latest - note query order
    }
    ?>

<SCRIPT >

var color=0;
	var colors = new Array ('odd', 'even');

	function hideDiv(div_area, hide_cont, show_cont) {	//	3/15/11
		if (div_area == "buttons_sh") {
			var controlarea = "hide_controls";
			}
		if (div_area == "resp_list_sh") {
			var controlarea = "resp_list";
			}
		if (div_area == "facs_list_sh") {
			var controlarea = "facs_list";
			}
		if (div_area == "incs_list_sh") {
			var controlarea = "incs_list";
			}
		if (div_area == "region_boxes") {
			var controlarea = "region_boxes";
			}			
		var divarea = div_area 
		var hide_cont = hide_cont 
		var show_cont = show_cont 
		if($(divarea)) {
			$(divarea).style.display = 'none';
			$(hide_cont).style.display = 'none';
			$(show_cont).style.display = '';
			} 
		var params = "f_n=" +controlarea+ "&v_n=h&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";
		var url = "persist2.php";
		sendRequest (url, gb_handleResult, params);			
		} 

	function showDiv(div_area, hide_cont, show_cont) {	//	3/15/11
		if (div_area == "buttons_sh") {
			var controlarea = "hide_controls";
			}
		if (div_area == "resp_list_sh") {
			var controlarea = "resp_list";
			}
		if (div_area == "facs_list_sh") {
			var controlarea = "facs_list";
			}
		if (div_area == "incs_list_sh") {
			var controlarea = "incs_list";
			}
		if (div_area == "region_boxes") {
			var controlarea = "region_boxes";
			}				
		var divarea = div_area
		var hide_cont = hide_cont 
		var show_cont = show_cont 
		if($(divarea)) {
			$(divarea).style.display = '';
			$(hide_cont).style.display = '';
			$(show_cont).style.display = 'none';
			}
		var params = "f_n=" +controlarea+ "&v_n=s&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";
		var url = "persist2.php";
		sendRequest (url, gb_handleResult, params);					
		} 	

	function hideGroup(color) {
		for (var i = 0; i < gmarkers.length; i++) {
			if (gmarkers[i]) {
				if (gmarkers[i].id == color) {
					gmarkers[i].show();
					}
				else {
					gmarkers[i].hide();
					}
				}		// end if (gmarkers[i])
			} 	// end for ()
		elem = $("allIcons");
		elem.style.visibility = "visible";
		}			// end function

	function showAll() {
		for (var i = 0; i < gmarkers.length; i++) {
			if (gmarkers[i]) {
				gmarkers[i].show();
				}
			} 	// end for ()
		elem = $("allIcons");
		elem.style.visibility = "hidden";

		}			// end function

	function checkArray(form, arrayName)	{	//	5/3/11
		var retval = new Array();
		for(var i=0; i < form.elements.length; i++) {
			var el = form.elements[i];
			if(el.type == "checkbox" && el.name == arrayName && el.checked) {
				retval.push(el.value);
			}
		}
	return retval;
	}		
		
	function checkForm(form)	{	//	6/10/11
		var errmsg="";
		var itemsChecked = checkArray(form, "frm_group[]");
		if(itemsChecked.length > 0) {
			var params = "f_n=viewed_groups&v_n=" +itemsChecked+ "&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
			var url = "persist3.php";	//	3/15/11	
			sendRequest (url, fvg_handleResult, params);				
			form.submit();
		} else {
			errmsg+= "\tYou cannot Hide all the regions\n";
			if (errmsg!="") {
				alert ("Please correct the following and re-submit:\n\n" + errmsg);
				return false;
			}
		}
	}
	
	function fvg_handleResult(req) {	// 6/10/11	The persist callback function for viewed groups.
		document.region_form.submit();
		}
		
	function form_validate(theForm) {	//	5/3/11
//		alert("Validating");
		checkForm(theForm);
		}				// end function validate(theForm)			

	function sendRequest(url,callback,postData) {								// 2/14/09
		var req = createXMLHTTPObject();
		if (!req) return;
		var method = (postData) ? "POST" : "GET";
		req.open(method,url,true);
		req.setRequestHeader('User-Agent','XMLHTTP/1.0');
		if (postData)
			req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		req.onreadystatechange = function () {
			if (req.readyState != 4) return;
			if (req.status != 200 && req.status != 304) {
				return;
				}
			callback(req);
			}
		if (req.readyState == 4) return;
		req.send(postData);
		}

	var XMLHttpFactories = [
		function () {return new XMLHttpRequest()	},
		function () {return new ActiveXObject("Msxml2.XMLHTTP")	},
		function () {return new ActiveXObject("Msxml3.XMLHTTP")	},
		function () {return new ActiveXObject("Microsoft.XMLHTTP")	}
		];

	function createXMLHTTPObject() {
		var xmlhttp = false;
		for (var i=0;i<XMLHttpFactories.length;i++) {
			try {
				xmlhttp = XMLHttpFactories[i]();
				}
			catch (e) {
				continue;
				}
			break;
			}
		return xmlhttp;
		}		

	function createMarker(point,tabs, color, id, unit_id) {						// (point, myinfoTabs,<?php 
    print $row['type'];
    ?>
, i)
		points = true;
		var unit_id = unit_id;										// 2/13/09

		var icon = new GIcon(listIcon);
		
		var icon_url = "./our_icons/gen_icon.php?blank=" + color + "&text=" + unit_id;				// 1/5/09

		icon.image = icon_url;		// ./our_icons/gen_icon.php?blank=4&text=zz"

		var marker = new GMarker(point, icon);
		marker.id = color;				// for hide/unhide - unused

		GEvent.addListener(marker, "click", function() {		// here for both side bar and icon click
			if (marker) {
				map.closeInfoWindow();
				which = id;
				gmarkers[which].hide();
				marker.openInfoWindowTabsHtml(infoTabs[id]);

				setTimeout(function() {										// wait for rendering complete - 12/17/08
					if ($("detailmap")) {
						var dMapDiv = $("detailmap");
						var detailmap = new GMap2(dMapDiv);
						detailmap.addControl(new GSmallMapControl());
						detailmap.setCenter(point, 17);  						// larger # = closer
						detailmap.addOverlay(marker);
						}
					else {
	//					alert(62);
	//					alert($("detailmap"));
						}
					},4000);				// end setTimeout(...)

				}		// end if (marker)


			});			// end GEvent.add Listener()

		gmarkers[id] = marker;									// marker to array for side bar click function
		infoTabs[id] = tabs;									// tabs to array
		if (!(map_is_fixed)) {				// 4/3/09
			bounds.extend(point);
			}
		return marker;
		}				// end function create Marker()

	function createdummyMarker(point,tabs, color, id, unit_id) {						// (point, myinfoTabs,<?php 
    print $row['type'];
    ?>
, i)
		points = true;
		var unit_id = unit_id;										// 2/13/09

		var icon = new GIcon(listIcon);
		var icon_url = "./our_icons/question1.png";

		icon.image = icon_url;		// ./our_icons/gen_icon.php?blank=4&text=zz"

		var dummymarker = new GMarker(point, icon);
		dummymarker.id = color;				// for hide/unhide - unused

		GEvent.addListener(dummymarker, "click", function() {		// here for both side bar and icon click
			if (dummymarker) {
				map.closeInfoWindow();
				which = id;
				gmarkers[which].hide();
				dummymarker.openInfoWindowTabsHtml(infoTabs[id]);

				setTimeout(function() {										// wait for rendering complete - 12/17/08
					if ($("detailmap")) {
						var dMapDiv = $("detailmap");
						var detailmap = new GMap2(dMapDiv);
						detailmap.addControl(new GSmallMapControl());
						detailmap.setCenter(point, 17);  						// larger # = closer
						detailmap.addOverlay(dummymarker);
						}
					else {
	//					alert(62);
	//					alert($("detailmap"));
						}
					},4000);				// end setTimeout(...)

				}		// end if (marker)


			});			// end GEvent.add Listener()

		gmarkers[id] = dummymarker;									// marker to array for side bar click function
		infoTabs[id] = tabs;									// tabs to array
		if (!(map_is_fixed)) {				// 4/3/09
			bounds.extend(point);
			}
		return dummymarker;
		}				// end function create dummy Marker()		

	function do_sidebar (sidebar, id, the_class, sidebar_id) {
		var sidebar_id = sidebar_id;
		side_bar_html += "<TR CLASS='" + colors[(id)%2] +"'>";
		side_bar_html += "<TD WIDTH='5%' CLASS='" + the_class + "' onClick = myclick(" + id + "); >" + sidebar_id + sidebar +"</TD></TR>\n";		// 1/5/09, 3/4/09, 10/29/09 removed period
		}

	function do_sidebar_nm (sidebar, line_no, id, sidebar_id) {	
		var sidebar_id = sidebar_id;		
		side_bar_html += "<TR CLASS='" + colors[(line_no)%2] +"'>";
		side_bar_html += "<TD WIDTH='5%' onClick = myclick_nm(" + sidebar_id + "); >" + sidebar_id + sidebar +"</TD></TR>\n";		// 1/23/09, 10/29/09 removed period, 11/11/09
		}

	function myclick_nm(v_id) {				// Responds to sidebar click - view responder data
		document.view_form.id.value=v_id;
		document.view_form.submit();
		}

	function myclick(id) {					// Responds to sidebar click, then triggers listener above -  note [id]
		GEvent.trigger(gmarkers[id], "click");
		location.href = '#top';				// 11/11/09
		}

	function do_lat (lat) {
		document.forms[0].frm_lat.value=lat.toFixed(6);
		}
	function do_lng (lng) {
		document.forms[0].frm_lng.value=lng.toFixed(6);
		}
		
	function do_ngs() {											// LL to USNG
		var loc = <?php 
    print get_variable('locale');
    ?>
;
		document.forms[0].frm_ngs.disabled=false;
		if(loc == 0) {
			document.forms[0].frm_ngs.value = LLtoUSNG(document.forms[0].frm_lat.value, document.forms[0].frm_lng.value, 5);
			}
		if(loc == 1) {
			document.forms[0].frm_ngs.value = LLtoOSGB(document.forms[0].frm_lat.value, document.forms[0].frm_lng.value, 5);
			}
		if(loc == 2) {
			document.forms[0].frm_ngs.value = LLtoOSGB(document.forms[0].frm_lat.value, document.forms[0].frm_lng.value, 5);
			}			
		document.forms[0].frm_ngs.disabled=true;
		}		

	var icons=new Array;							// maps type to icon blank

<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}unit_types` ORDER BY `id`";
    // types in use
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $icons = $GLOBALS['icons'];
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // map type to blank icon id
        $blank = $row['icon'];
        print "\ticons[" . $row['id'] . "] = " . $blank . ";\n";
        //
    }
    unset($result);
    $dzf = get_variable('def_zoom_fixed');
    print "\tvar map_is_fixed = ";
    print my_is_int($dzf) && $dzf == 2 || my_is_int($dzf) && $dzf == 3 ? "true;\n" : "false;\n";
    ?>
	var map;
	var side_bar_html = "<TABLE border=0 CLASS='sidebar' WIDTH = '100%' >";

	side_bar_html += "<TR class='even'>	<TD></TD><TD ALIGN='left'><B>Unit</B></TD><TD ALIGN='left'><B>Handle</B></TD><TD ALIGN='left'><B>Dispatch</B></TD><TD ALIGN='left'><B>Status</B></TD><TD ALIGN='left'><B>M</B></TD><TD ALIGN='left'><B>As of</B></TD></TR>";
	var gmarkers = [];
	var infoTabs = [];
	var which;
	var i = <?php 
    print $start;
    ?>
;					// sidebar/icon index
	var points = false;								// none
	map = new GMap2($("map"));						// create the map
<?php 
    $maptype = get_variable('maptype');
    // 08/02/09
    switch ($maptype) {
        case "1":
            break;
        case "2":
            ?>
		map.setMapType(G_SATELLITE_MAP);<?php 
            break;
        case "3":
            ?>
		map.setMapType(G_PHYSICAL_MAP);<?php 
            break;
        case "4":
            ?>
		map.setMapType(G_HYBRID_MAP);<?php 
            break;
        default:
            print "ERROR in " . basename(__FILE__) . " " . __LINE__ . "<BR />";
    }
    ?>

//	map.addControl(new GSmallMapControl());					// 10/6/08
	map.setUIToDefault();										// 8/13/10

	map.addControl(new GMapTypeControl());
<?php 
    if (get_variable('terrain') == 1) {
        ?>
	map.addMapType(G_PHYSICAL_MAP);
<?php 
    }
    ?>

	map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
	mapBounds=new GLatLngBounds(map.getBounds().getSouthWest(), map.getBounds().getNorthEast());		// 4/4/09

	var bounds = new GLatLngBounds();						// create  bounding box
	map.enableScrollWheelZoom();

	var listIcon = new GIcon();
	listIcon.image = "./markers/yellow.png";	// yellow.png - 16 X 28
	listIcon.shadow = "./markers/sm_shadow.png";
	listIcon.iconSize = new GSize(20, 34);
	listIcon.shadowSize = new GSize(37, 34);
	listIcon.iconAnchor = new GPoint(8, 28);
	listIcon.infoWindowAnchor = new GPoint(9, 2);
	listIcon.infoShadowAnchor = new GPoint(18, 25);

	GEvent.addListener(map, "infowindowclose", function() {		// re-center after  move/zoom
		map.addOverlay(gmarkers[which])
		});
	
	do_landb();				// 8/1/11 - show scribbles	
//-----------------------BOUNDARIES STUFF--------------------6/10/11

	var thepoint;
	var points = new Array();
	var boundary = new Array();	
	var bound_names = new Array();

	GEvent.addListener(map, "click", function(overlay,boundpoint) {
		for (var n = 0; n < boundary.length; n++) {
			if (boundary[n].Contains(boundpoint)) {
				map.openInfoWindowHtml(boundpoint,"This is " + bound_names[n]);
				}
			}
		});			
<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}' ORDER BY `id` ASC;";
    //	6/10/11
    $result = mysql_query($query);
    //	6/10/11
    $a_gp_bounds = array();
    $gp_bounds = array();
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        //	6/10/11
        $al_groups[] = $row['group'];
        $query2 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}region` WHERE `id`= '{$row['group']}';";
        //	6/10/11
        $result2 = mysql_query($query2);
        // 4/18/11
        while ($row2 = stripslashes_deep(mysql_fetch_assoc($result2))) {
            //	//	6/10/11
            if ($row2['boundary'] != 0) {
                $a_gp_bounds[] = $row2['boundary'];
            }
        }
    }
    if (isset($_SESSION['viewed_groups'])) {
        //	6/10/11
        foreach (explode(",", $_SESSION['viewed_groups']) as $val_vg) {
            $query3 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}region` WHERE `id`= '{$val_vg}';";
            $result3 = mysql_query($query3);
            //	6/10/11
            while ($row3 = stripslashes_deep(mysql_fetch_assoc($result3))) {
                if ($row3['boundary'] != 0) {
                    $gp_bounds[] = $row3['boundary'];
                }
            }
        }
    } else {
        $gp_bounds = $a_gp_bounds;
    }
    foreach ($gp_bounds as $value) {
        //	6/10/11
        ?>
		var points = new Array();
<?php 
        if ($value != 0) {
            $query_bn = "SELECT * FROM `{$GLOBALS['mysql_prefix']}mmarkup` WHERE `id`='{$value}'";
            $result_bn = mysql_query($query_bn) or do_error($query_bn, mysql_error(), basename(__FILE__), __LINE__);
            while ($row_bn = stripslashes_deep(mysql_fetch_assoc($result_bn))) {
                extract($row_bn);
                $bn_name = $row_bn['line_name'];
                $points = explode(";", $line_data);
                for ($i = 0; $i < count($points); $i++) {
                    $coords = explode(",", $points[$i]);
                    ?>
					thepoint = new GLatLng(parseFloat(<?php 
                    print $coords[0];
                    ?>
), parseFloat(<?php 
                    print $coords[1];
                    ?>
));
					points.push(thepoint);
<?php 
                }
                // end for ($i = 0 ... )
                ?>

<?php 
                if (intval($filled) == 1) {
                    //	6/10/11
                    ?>
				var polyline = new GPolygon(points, add_hash("<?php 
                    print $line_color;
                    ?>
"), <?php 
                    print $line_width;
                    ?>
, <?php 
                    print $line_opacity;
                    ?>
, add_hash("<?php 
                    print $fill_color;
                    ?>
"), <?php 
                    print $fill_opacity;
                    ?>
, {clickable:false});
				boundary.push(polyline);
				bound_names.push("<?php 
                    print $bn_name;
                    ?>
"); 			
				<?php 
                } else {
                    ?>
				var polyline = new GPolyline(points, add_hash("<?php 
                    print $line_color;
                    ?>
"), <?php 
                    print $line_width;
                    ?>
, <?php 
                    print $line_opacity;
                    ?>
, , 0, {clickable:false});
				boundary.push(polyline);
				bound_names.push("<?php 
                    print $bn_name;
                    ?>
"); 			
<?php 
                }
                ?>
				map.addOverlay(polyline);
<?php 
            }
            //	End while
        }
        //	end if $value !=0
    }
    //	end foreach $gp_bounds
    //-------------------------END OF BOUNDARIES STUFF-------------------------
    function can_do_dispatch($the_row)
    {
        if (intval($the_row['multi']) == 1) {
            return TRUE;
        }
        $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` WHERE `responder_id` = {$the_row['id']}";
        // all dispatches this unit
        $result_temp = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        while ($row_temp = stripslashes_deep(mysql_fetch_array($result_temp))) {
            // check any open runs this unit
            if (!is_date($row_temp['clear'])) {
                // if  clear is empty, then NOT dispatch-able
                unset($result_temp, $row_temp);
                return FALSE;
            }
        }
        // end while ($row_temp ...)
        unset($result_temp, $row_temp);
        return TRUE;
        // none found, can dispatch
    }
    // end function can do_dispatch()
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    $bulls = array(0 => "", 1 => "red", 2 => "green", 3 => "white", 4 => "black");
    $status_vals = array();
    // build array of $status_vals
    $status_vals[''] = $status_vals['0'] = "TBD";
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}un_status` ORDER BY `id`";
    $result_st = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_st = stripslashes_deep(mysql_fetch_array($result_st))) {
        $temp = $row_st['id'];
        $status_vals[$temp] = $row_st['status_val'];
    }
    unset($result_st);
    $query_al = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}';";
    //	6/10/11
    $result_al = mysql_query($query_al);
    // 6/10/11
    $al_groups = array();
    while ($row_al = stripslashes_deep(mysql_fetch_assoc($result_al))) {
        //	6/10/11
        $al_groups[] = $row_al['group'];
    }
    if (isset($_SESSION['viewed_groups'])) {
        //	6/10/11
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    }
    if (!isset($curr_viewed)) {
        $x = 0;
        //	6/10/11
        $where2 = "WHERE (";
        //	6/10/11
        foreach ($al_groups as $grp) {
            //	6/10/11
            $where3 = count($al_groups) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    } else {
        $x = 0;
        //	6/10/11
        $where2 = "WHERE (";
        //	6/10/11
        foreach ($curr_viewed as $grp) {
            //	6/10/11
            $where3 = count($curr_viewed) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    }
    $where2 .= "AND `a`.`type` = 2";
    //	6/10/11
    //-----------------------UNIT RING FENCE STUFF--------------------6/10/11
    ?>
	var thepoint;
	var points = new Array();
		
<?php 
    $query_bn = "SELECT * FROM `{$GLOBALS['mysql_prefix']}mmarkup` `l`\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}responder` `r` ON ( `l`.`id` = `r`.`ring_fence`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON ( `r`.`id` = `a`.`resource_id` )\t\n\t\t\t\t{$where2} AND `use_with_u_rf`=1 GROUP BY `l`.`id`";
    $result_bn = mysql_query($query_bn) or do_error($query_bn, mysql_error(), basename(__FILE__), __LINE__);
    while ($row_bn = stripslashes_deep(mysql_fetch_assoc($result_bn))) {
        extract($row_bn);
        $bn_name = $row_bn['line_name'];
        $all_boundaries[] = $row_bn['ring_fence'];
        $points = explode(";", $line_data);
        for ($i = 0; $i < count($points); $i++) {
            $coords = explode(",", $points[$i]);
            ?>
			thepoint = new GLatLng(parseFloat(<?php 
            print $coords[0];
            ?>
), parseFloat(<?php 
            print $coords[1];
            ?>
));
			points.push(thepoint);
<?php 
        }
        // end for ($i = 0 ... )
        if (intval($filled) == 1) {
            //	6/10/11
            ?>
			var polyline = new GPolygon(points, add_hash("<?php 
            print $line_color;
            ?>
"), <?php 
            print $line_width;
            ?>
, <?php 
            print $line_opacity;
            ?>
, add_hash("<?php 
            print $fill_color;
            ?>
"), <?php 
            print $fill_opacity;
            ?>
, {clickable:false, id:"ringfence"});
			boundary.push(polyline);
			bound_names.push("<?php 
            print $bn_name;
            ?>
"); 
<?php 
        } else {
            ?>
			var polyline = new GPolyline(points, add_hash("<?php 
            print $line_color;
            ?>
"), <?php 
            print $line_width;
            ?>
, <?php 
            print $line_opacity;
            ?>
, , 0, {clickable:false, id:"ringfence"});
			boundary.push(polyline);
			bound_names.push("<?php 
            print $bn_name;
            ?>
"); 
<?php 
        }
        ?>
			map.addOverlay(polyline);
<?php 
    }
    //	End while
    //-------------------------END OF UNIT RING FENCE STUFF-------------------------
    //-----------------------UNIT EXCLUSION ZONE STUFF--------------------6/10/11
    ?>
	var thepoint;
	var points = new Array();
		
<?php 
    $query_bn = "SELECT * FROM `{$GLOBALS['mysql_prefix']}mmarkup` `l`\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}responder` `r` ON ( `l`.`id` = `r`.`excl_zone`)\n\t\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON ( `r`.`id` = `a`.`resource_id` )\t\n\t\t\t\t{$where2} AND `use_with_u_ex`=1 GROUP BY `l`.`id`";
    $result_bn = mysql_query($query_bn) or do_error($query_bn, mysql_error(), basename(__FILE__), __LINE__);
    while ($row_bn = stripslashes_deep(mysql_fetch_assoc($result_bn))) {
        extract($row_bn);
        $bn_name = $row_bn['line_name'];
        $all_boundaries[] = $row_bn['ring_fence'];
        $points = explode(";", $line_data);
        for ($i = 0; $i < count($points); $i++) {
            $coords = explode(",", $points[$i]);
            ?>
			thepoint = new GLatLng(parseFloat(<?php 
            print $coords[0];
            ?>
), parseFloat(<?php 
            print $coords[1];
            ?>
));
			points.push(thepoint);
<?php 
        }
        // end for ($i = 0 ... )
        if (intval($filled) == 1) {
            //	6/10/11
            ?>
			var polyline = new GPolygon(points, add_hash("<?php 
            print $line_color;
            ?>
"), <?php 
            print $line_width;
            ?>
, <?php 
            print $line_opacity;
            ?>
, add_hash("<?php 
            print $fill_color;
            ?>
"), <?php 
            print $fill_opacity;
            ?>
, {clickable:false, id:"ringfence"});
			boundary.push(polyline);
			bound_names.push("<?php 
            print $bn_name;
            ?>
"); 
<?php 
        } else {
            ?>
			var polyline = new GPolyline(points, add_hash("<?php 
            print $line_color;
            ?>
"), <?php 
            print $line_width;
            ?>
, <?php 
            print $line_opacity;
            ?>
, , 0, {clickable:false, id:"ringfence"});
			boundary.push(polyline);
			bound_names.push("<?php 
            print $bn_name;
            ?>
"); 
<?php 
        }
        ?>
			map.addOverlay(polyline);
<?php 
    }
    //	End while
    //-------------------------END OF UNIT EXCLUSION ZONE STUFF-------------------------
    $query = "SELECT *, UNIX_TIMESTAMP(updated) AS `updated`,\n\t\t`t`.`id` AS `type_id`,\n\t\t`r`.`id` AS `unit_id`,\n\t\t`r`.`name` AS `name`,\n\t\t`s`.`description` AS `stat_descr`,\n\t\t`r`.`description` AS `unit_descr`, \n\t\t`r`.`ring_fence` AS `ring_fence`,\t\n\t\t`r`.`excl_zone` AS `excl_zone`,\t\t\n\t\t(SELECT  COUNT(*) as numfound FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\tWHERE `{$GLOBALS['mysql_prefix']}assigns`.`responder_id` = unit_id  AND  (`clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' )) AS `nr_assigned` \n\t\tFROM `{$GLOBALS['mysql_prefix']}responder` `r` \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON ( `r`.`id` = a.resource_id )\t\t\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}unit_types` `t` ON ( `r`.`type` = t.id )\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}un_status` `s` ON ( `r`.`un_status_id` = s.id ) \t\t\n\t\t{$where2}  GROUP BY unit_id ORDER BY `nr_assigned` DESC,  `handle` ASC, `r`.`name` ASC ";
    // 2/1/10, 3/15/10, 6/10/11
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $num_units = mysql_affected_rows();
    $i = 0;
    // counter
    // =============================================================================
    $bulls = array(0 => "", 1 => "red", 2 => "green", 3 => "white", 4 => "black");
    $utc = gmdate("U");
    //									 ==========  major while() for RESPONDER ==========
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        $ringfence = $row['ring_fence'];
        $resp_gps = get_allocates(2, $row['unit_id']);
        //	6/10/11
        $grp_names = "Groups Assigned: ";
        //	6/10/11
        $y = 0;
        //	6/10/11
        foreach ($resp_gps as $value) {
            //	6/10/11
            $counter = count($resp_gps) > $y + 1 ? ", " : "";
            $grp_names .= get_groupname($value);
            $grp_names .= $counter;
            $y++;
        }
        $grp_names .= " / ";
        $track_type = get_remote_type($row);
        $index = $row['icon_str'];
        // 4/28/11
        $the_on_click = my_is_float($row['lat']) ? " onClick = myclick({$i}); " : " onClick = myclick_nm({$row['unit_id']}); ";
        $the_bg_color = $GLOBALS['UNIT_TYPES_BG'][$row['icon']];
        // 2/1/10
        $the_text_color = $GLOBALS['UNIT_TYPES_TEXT'][$row['icon']];
        // 2/1/10
        $do_dispatch = can_do_dispatch($row);
        // 11/17/09
        $got_point = FALSE;
        print "\n\t\tvar i={$i};\n";
        $tofac = is_guest() ? "" : "&nbsp;&nbsp;<A HREF='{$_SESSION['unitsfile']}?func=responder&view=true&dispfac=true&id=" . $row['unit_id'] . "'><U>To Facility</U></A>&nbsp;&nbsp;";
        // 10/6/09
        $todisp = is_guest() || !can_do_dispatch($row) ? "" : "&nbsp;&nbsp;<A HREF='{$_SESSION['unitsfile']}?func=responder&view=true&disp=true&id=" . $row['unit_id'] . "'><U>Dispatch</U></A>&nbsp;&nbsp;&nbsp;";
        // 08/8/02, 9/19/09
        $toedit = !can_edit() ? "" : "&nbsp;&nbsp;<A HREF='{$_SESSION['unitsfile']}?func=responder&edit=true&id=" . $row['unit_id'] . "'><U>Edit</U></A>&nbsp;&nbsp;&nbsp;&nbsp;";
        // 5/11/10
        $totrack = intval($row['mobile']) == 0 || empty($row['callsign']) ? "" : "&nbsp;&nbsp;<SPAN onClick = do_track('" . $row['callsign'] . "');><B><U>Tracks</B></U></SPAN>";
        $temp = $row['un_status_id'];
        // 2/24/09
        $the_status = array_key_exists($temp, $status_vals) ? $status_vals[$temp] : "??";
        // 2/2/09
        $row_track = FALSE;
        if ($track_type > 0) {
            // get most recent position data
            $do_legend = TRUE;
            $query = "SELECT *,UNIX_TIMESTAMP(packet_date) AS `packet_date`, UNIX_TIMESTAMP(updated) AS `updated` FROM \n\t\t\t\t`{$GLOBALS['mysql_prefix']}tracks`\n\t\t\t\tWHERE `source`= '{$row['callsign']}' ORDER BY `packet_date` DESC LIMIT 1";
            // newest
            $result_tr = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
            $row_track = mysql_affected_rows() > 0 ? stripslashes_deep(mysql_fetch_assoc($result_tr)) : FALSE;
            $aprs_updated = $row_track['updated'];
            $aprs_speed = $row_track['speed'];
            if ($row_track && my_is_float($row_track['latitude'])) {
                if ($row['lat'] == 0.999999 && $row['lng'] == 0.999999) {
                    echo "\t\tvar point = new GLatLng(" . get_variable('def_lat') . ", " . get_variable('def_lng') . ");\n";
                } else {
                    echo "\t\tvar point = new GLatLng(" . $row_track['latitude'] . ", " . $row_track['longitude'] . "); // 677\n";
                }
                $got_point = TRUE;
            }
            unset($result_tr);
        }
        if (!$got_point && my_is_float($row['lat'])) {
            if ($row['lat'] == 0.999999 && $row['lng'] == 0.999999) {
                echo "\t\tvar point = new GLatLng(" . get_variable('def_lat') . ", " . get_variable('def_lng') . ");\n";
            } else {
                echo "\t\tvar point = new GLatLng(" . $row['lat'] . ", " . $row['lng'] . ");\t// " . __LINE__ . "\n";
            }
            $got_point = TRUE;
        }
        $update_error = strtotime('now - 6 hours');
        // set the time for silent setting
        //			if ($instam_updated < $update_error) {$the_bull = "<FONT COLOR = 'black'><B>{$GLOBALS['TRACK_2L'][$track_type]}</B></FONT>";}
        // end bullet stuff
        // name, handle
        $handle = htmlentities($row['handle'], ENT_QUOTES);
        // 7/7/11
        $sidebar_line = "<TD WIDTH='15%' TITLE = '{$handle}' {$the_on_click}><NOBR>{$handle}</NOBR></TD>";
        $name = htmlentities($row['name'], ENT_QUOTES);
        $sidebar_line .= "<TD WIDTH='20%' TITLE = '{$name}' {$the_on_click}><U><SPAN STYLE='width: 30%; background-color:{$the_bg_color};  opacity: .7; color:{$the_text_color};'><NOBR>" . addslashes(shorten($row['name'], 14)) . "</NOBR></SPAN></U></TD>";
        // 10/8/09
        // assignments 3/16/09, 3/15/10 - 8/30/10
        $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` `t` ON (`{$GLOBALS['mysql_prefix']}assigns`.`ticket_id` = `t`.`id`)\n\t\t\tWHERE `responder_id` = '{$row['unit_id']}' AND (`clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' )";
        $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        $row_assign = mysql_affected_rows() == 0 ? FALSE : stripslashes_deep(mysql_fetch_assoc($result_as));
        switch ($row_assign['severity']) {
            //color tickets by severity
            case $GLOBALS['SEVERITY_MEDIUM']:
                $severityclass = 'severity_medium';
                break;
            case $GLOBALS['SEVERITY_HIGH']:
                $severityclass = 'severity_high';
                break;
            default:
                $severityclass = 'severity_normal';
                break;
        }
        switch (mysql_affected_rows()) {
            // 8/29/10
            case 0:
                $the_disp_str = "";
                break;
            case 1:
                $the_disp_str = get_disp_status($row_assign) . "&nbsp;";
                break;
            default:
                // multiples
                $the_disp_str = "<SPAN CLASS='disp_stat'>&nbsp;" . mysql_affected_rows() . "&nbsp;</SPAN>&nbsp;";
                break;
        }
        // end switch()
        $onclick = mysql_affected_rows() > 0 ? " onClick = 'open_tick_window ({$row_assign['ticket_id']})'" : "";
        $ass_td = mysql_affected_rows() > 0 ? "<TD WIDTH='20%' CLASS='{$severityclass}' TITLE = '{$row_assign['scope']}'  {$onclick} ><NOBR>{$the_disp_str}" . shorten($row_assign['scope'], 24) . "</NOBR></TD>" : "<TD WIDTH='20%'>na</TD>";
        unset($result_as);
        $sidebar_line .= $row['nr_assigned'] . $row_assign ? $ass_td : "<TD WIDTH='20%'>na</TD>";
        //  status, mobility  - 4/14/10
        $sidebar_line .= "<TD WIDTH='20%' TITLE = '" . addslashes($the_status) . "'> " . get_status_sel($row['unit_id'], $row['un_status_id'], "u") . ($the_bull = "");
        // define the bullet
        if ($row_track['speed'] > 50) {
            $the_bull = "<FONT COLOR = 'white'><B>{$GLOBALS['TRACK_2L'][$track_type]}</B></FONT>";
        }
        if ($row_track['speed'] < 50) {
            $the_bull = "<FONT COLOR = 'green'><B>{$GLOBALS['TRACK_2L'][$track_type]}</B></FONT>";
        }
        if ($row_track['speed'] == 0) {
            $the_bull = "<FONT COLOR = 'red'><B>{$GLOBALS['TRACK_2L'][$track_type]}</B></FONT>";
        }
        $tip = htmlentities($row['callsign'], ENT_QUOTES);
        $tip_str = "onMouseover=\\\"Tip('{$tip}')\\\" onmouseout=\\\"UnTip();\\\" ";
        $sidebar_line .= "<TD WIDTH='2%' {$tip_str}>{$the_bull}</TD>";
        // 4/14/10
        // as of
        $the_time = $row['updated'];
        $the_class = "";
        $strike = $strike_end = "";
        $the_flag = $name . "_flag";
        if ($track_type > 0 && abs($utc - $the_time) > $GLOBALS['TOLERANCE']) {
            // attempt to identify  non-current values
            $strike = "<STRIKE>";
            $strike_end = "</STRIKE>";
        }
        $sidebar_line .= "<TD WIDTH='18%' CLASS='{$the_class}'> {$strike}<SPAN id = '" . $name . "'><NOBR>" . format_sb_date($the_time) . "</NOBR></SPAN>{$strike_end}&nbsp;&nbsp;<SPAN ID = '" . $the_flag . "'></SPAN></TD>";
        // 6/17/08
        // tab 1
        if (my_is_float($row['lat'])) {
            // position data? 4/29/09
            $temptype = $u_types[$row['type_id']];
            $the_type = $temptype[0];
            // 1/1/09
            $tab_1 = "<TABLE CLASS='infowin' width='{$iw_width}'>";
            $tab_1 .= "<TR CLASS='even'><TD COLSPAN=2 ALIGN='center'><B>" . addslashes(shorten($row['name'], 48)) . "</B> - " . $the_type . "</TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD>Description:</TD><TD>" . addslashes(shorten(str_replace($eols, " ", $row['description']), 32)) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='even'><TD>Status:</TD><TD>" . $the_status . " </TD></TR>";
            $tab_1 .= "<TR CLASS='odd'><TD>Contact:</TD><TD>" . addslashes($row['contact_name']) . " Via: " . addslashes($row['contact_via']) . "</TD></TR>";
            $tab_1 .= "<TR CLASS='even'><TD>As of:</TD><TD>" . format_date($the_time) . "</TD></TR>";
            // 4/11/10
            if (array_key_exists($row['unit_id'], $assigns)) {
                $tab_1 .= "<TR CLASS='even'><TD CLASS='emph'>Dispatched to:</TD><TD CLASS='emph'><A HREF='main.php?id=" . $tickets[$row['unit_id']] . "'>" . addslashes(shorten($assigns[$row['unit_id']], 20)) . "</A></TD></TR>";
            }
            $tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'>" . $tofac . $todisp . $totrack . $toedit . "&nbsp;&nbsp;<A HREF='{$_SESSION['unitsfile']}?func=responder&view=true&id=" . $row['unit_id'] . "'><U>View</U></A></TD></TR>";
            // 08/8/02
            $tab_1 .= "</TABLE>";
            // tab 2
            if ($row_track) {
                // do all three tabs
                $tab_2 = "<TABLE CLASS='infowin' width='{$iw_width}'>";
                $tab_2 .= "<TR CLASS='even'><TD COLSPAN=2 ALIGN='center'><B>" . $row_track['source'] . "</B></TD></TR>";
                $tab_2 .= "<TR CLASS='odd'><TD>Course: </TD><TD>" . $row_track['course'] . ", Speed:  " . $row_track['speed'] . ", Alt: " . $row_track['altitude'] . "</TD></TR>";
                $tab_2 .= "<TR CLASS='even'><TD>Closest city: </TD><TD>" . $row_track['closest_city'] . "</TD></TR>";
                $tab_2 .= "<TR CLASS='odd'><TD>Status: </TD><TD>" . $row_track['status'] . "</TD></TR>";
                if (array_key_exists('packet_date', $row_track)) {
                    $tab_2 .= "<TR CLASS='even'><TD>As of: </TD><TD> {$strike}" . format_date($row_track['packet_date']) . "{$strike_end} (UTC)</TD></TR></TABLE>";
                }
                ?>
			var myinfoTabs = [
				new GInfoWindowTab("<?php 
                print nl2brr(addslashes(shorten($row['name'], 10)));
                ?>
", "<?php 
                print $tab_1;
                ?>
"),
				new GInfoWindowTab("<?php 
                print $GLOBALS['TRACK_2L'][$track_type];
                ?>
 <?php 
                print addslashes(substr($row_track['source'], -3));
                ?>
", "<?php 
                print $tab_2;
                ?>
"),
				new GInfoWindowTab("Zoom", "<div id='detailmap' class='detailmap'></div>")
				];
<?php 
            } else {
                // two tabs
                ?>
			var myinfoTabs = [
				new GInfoWindowTab("<?php 
                print nl2brr(addslashes(shorten($row['name'], 10)));
                ?>
", "<?php 
                print $tab_1;
                ?>
"),
				new GInfoWindowTab("Zoom", "<div id='detailmap' class='detailmap'></div>")
				];
<?php 
            }
            // end if/else  ($row_track)
            if ($row['lat'] == 0.999999 && $row['lng'] == 0.999999) {
                // check for no maps mode entries 7/28/10
                ?>
		var the_class = ((map_is_fixed) && (!(mapBounds.containsLatLng(point))))? "emph" : "td_label";		// 4/3/09
		do_sidebar ("<?php 
                print $sidebar_line;
                ?>
", i, the_class, "<?php 
                print $row['icon_str'];
                ?>
");
		var dummymarker = createdummyMarker(point, myinfoTabs,<?php 
                print $row['icon'];
                ?>
, i, "<?php 
                print $index;
                ?>
");	// 771 (point,tabs, color, id)
		map.addOverlay(dummymarker);
<?php 
            } else {
                ?>
		var the_class = ((map_is_fixed) && (!(mapBounds.containsLatLng(point))))? "emph" : "td_label";		// 4/3/09
		do_sidebar ("<?php 
                print $sidebar_line;
                ?>
", i, the_class, "<?php 
                print $index;
                ?>
");
		var marker = createMarker(point, myinfoTabs,<?php 
                print $row['icon'];
                ?>
, i, "<?php 
                print $index;
                ?>
");	// 771 (point,tabs, color, id)
		map.addOverlay(marker);
<?php 
            }
        } else {
            print "\tdo_sidebar_nm (\" {$sidebar_line} \" , i, {$row['id']}, '{$index}');\n";
            // sidebar only - no map, 11/11/09, 5/12/10
        }
        $i++;
        // zero-based
    }
    // end  ==========  while() for RESPONDER ==========
    $source_legend = isset($do_legend) ? "<TD CLASS='emph' ALIGN='left'>Source time</TD>" : "<TD></TD>";
    // if any remote data/time 3/24/09
    ?>
	if (!(map_is_fixed)) {		// 4/3/09
		if (!points) {		// any?
			map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
			}
		else {
			center = bounds.getCenter();
			zoom = map.getBoundsZoomLevel(bounds);
			map.setCenter(center,zoom);
			}
		}

	side_bar_html+= "<TR CLASS='" + colors[i%2] +"'><TD COLSPAN=6>&nbsp;</TD><?php 
    print $source_legend;
    ?>
</TR>";
<?php 
    if (!empty($addon)) {
        print "\n\tside_bar_html +=\"" . $addon . "\"\n";
    }
    ?>
	side_bar_html +="</TABLE>\n";
	$("side_bar").innerHTML += side_bar_html;	// append the assembled side_bar_html contents to the side bar div
	$("num_units").innerHTML = <?php 
    print $num_units;
    ?>
;		

<?php 
    //	print "<TABLE BORDER = 4 >{$buttons}</TABLE>";
    do_kml();
    ?>

</SCRIPT>

<?php 
}
function list_responders($addon = '', $start)
{
    global $u_types;
    ?>
<SCRIPT>

	try {
		parent.frames["upper"].document.getElementById("whom").innerHTML  = "<?php 
    print $_SESSION['user'];
    ?>
";
		parent.frames["upper"].document.getElementById("level").innerHTML = "<?php 
    print get_level_text($_SESSION['level']);
    ?>
";
		parent.frames["upper"].document.getElementById("script").innerHTML  = "<?php 
    print LessExtension(basename(__FILE__));
    ?>
";
		}
	catch(e) {
		}
	var color=0;
	var colors = new Array ('odd', 'even');
	var starting = false;

	function $() {								// 1/23/09
		var elements = new Array();
		for (var i = 0; i < arguments.length; i++) {
			var element = arguments[i];
			if (typeof element == 'string')
				element = document.getElementById(element);
			if (arguments.length == 1)
				return element;
			elements.push(element);
			}
		return elements;
		}

	function isNull(val) {								// checks var stuff = null;
		return val === null;
		}
	function do_aprs_window() {				// 6/25/08
//				echo '<a href="mycgi?foo=', urlencode($userinput), '">';
	
//		var url = "http://www.openaprs.net?center=" + "<?php 
    print urlencode(get_variable('def_lat') . ',' . get_variable('def_lng'));
    ?>
";
		var url = "http://www.openaprs.net?center=" + "<?php 
    print get_variable('def_lat') . ',' . get_variable('def_lng');
    ?>
";
		var spec ="titlebar, resizable=1, scrollbars, height=640,width=640,status=0,toolbar=0,menubar=0,location=0, left=50,top=250,screenX=50,screenY=250";
		newwindow=window.open(url, 'openaprs',  spec);
		if (isNull(newwindow)) {
			alert ("APRS display requires popups to be enabled. Please adjust your browser options.");
			return;
			}
		newwindow.focus();
		}				// end function

	function do_track(callsign) {
		if (parent.frames["upper"].logged_in()) {
			map.closeInfoWindow();
			var width = <?php 
    print get_variable('map_width');
    ?>
+360;
			var spec ="titlebar, resizable=1, scrollbars, height=640,width=" + width + ",status=0,toolbar=0,menubar=0,location=0, left=100,top=300,screenX=100,screenY=300";
			var url = "track_u.php?source="+callsign;
			newwindow=window.open(url, callsign,  spec);
			if (isNull(newwindow)) {
				alert ("Track display requires popups to be enabled. Please adjust your browser options.");
				return;
				}
//			starting = false;
			newwindow.focus();
			}
		}				// end function

	function hideGroup(color) {
		for (var i = 0; i < gmarkers.length; i++) {
			if (gmarkers[i]) {
				if (gmarkers[i].id == color) {
					gmarkers[i].show();
					}
				else {
					gmarkers[i].hide();
					}
				}		// end if (gmarkers[i])
			} 	// end for ()
		elem = document.getElementById("allIcons");
		elem.style.visibility = "visible";
		}			// end function

	function showAll() {
		for (var i = 0; i < gmarkers.length; i++) {
			if (gmarkers[i]) {
				gmarkers[i].show();
				}
			} 	// end for ()
		elem = document.getElementById("allIcons");
		elem.style.visibility = "hidden";

		}			// end function

	function create_track_Marker(point,html, mytype, ender, heading) {
		switch (mytype){
			case 1:
//				alert(99);
				var marker = new GMarker(point, starticon);	
				GEvent.addListener(marker, "click", function() {
					marker.openInfoWindowHtml(html);
					});
				break;
			case ender:
//				alert(106);
				var marker = new GMarker(point, endicon);	
				GEvent.addListener(marker, "click", function() {
					marker.openInfoWindowHtml(html);
					});
				break;
			default : 
				var infoicon = new GIcon();
				infoicon.image = "./markers/" + direcs[heading];
				
				infoicon.iconSize = new GSize(15, 15);
				infoicon.iconAnchor = new GPoint(4, 4);
			
				var marker = new GMarker(point, infoicon);	
				GEvent.addListener(marker, "click", function() {
					marker.openInfoWindowHtml(html);
					});
				}
		return marker;
		}
																// 1/24/09
	function createMarker(point,tabs, color, id) {				// Creates marker and sets up click event infowindow 
		points = true;											// at least one
		var letter = String.fromCharCode("A".charCodeAt(0) + id);		// start with A - 1/5/09

		var icon = new GIcon(listIcon);
		var icon_url = "./our_icons/gen_icon.php?blank=" + escape(icons[color]) + "&text=" + letter;				// 1/5/09
		icon.image = icon_url;		// ./our_icons/gen_icon.php?blank=4&text=zz"

		var marker = new GMarker(point, icon);
		marker.id = color;				// for hide/unhide - unused

		GEvent.addListener(marker, "click", function() {		// here for both side bar and icon click
			map.closeInfoWindow();
			which = id;
			gmarkers[which].hide();
			marker.openInfoWindowTabsHtml(infoTabs[id]);
			
//			var dMapDiv = document.getElementById("detailmap");
//			var detailmap = new GMap2(dMapDiv);
//			detailmap.addControl(new GSmallMapControl());
//			detailmap.setCenter(point, 13);  					// larger # = closer
//			detailmap.addOverlay(marker);

			setTimeout(function() {										// wait for rendering complete - 12/17/08
			if ($("detailmap")) {				
				var dMapDiv = $("detailmap");
				var detailmap = new GMap2(dMapDiv);
				detailmap.addControl(new GSmallMapControl());
				detailmap.setCenter(point, 17);  						// larger # = closer
				detailmap.addOverlay(marker);
				}
			else {
//				alert(62);
//				alert($("detailmap"));
				}
			},4000);				// end setTimeout(...)


		});			// end 	GEvent.addListener()




		gmarkers[id] = marker;									// marker to array for side_bar click function
		infoTabs[id] = tabs;									// tabs to array
//		bounds.extend(point);									// extend the bounding box - removed 5/26/08
		return marker;
		}				// end function create Marker()
		
	function do_sidebar (sidebar, id, call) {
		var letter = String.fromCharCode("A".charCodeAt(0) + id);								// start with A - 1/5/09
		side_bar_html += "<TR CLASS='" + colors[(id)%2] +"' onClick = myclick(" + id + ");>";
		side_bar_html += "<TD CLASS='td_label'>" + letter + ". "+ sidebar +"</TD></TR>\n";		// 1/5/09
		}

	function do_sidebar_nm (sidebar, line_no, rcd_id) {							// no map - view responder // view_Form
		var letter = String.fromCharCode("A".charCodeAt(0) + line_no);							// start with A - 1/5/09
		side_bar_html += "<TR CLASS='" + colors[(line_no)%2] +"' onClick = myclick_nm(" + id + ");>";
		side_bar_html += "<TD CLASS='td_label'>" + letter + ". "+ sidebar +"</TD></TR>\n";		// 1/23/09
		}

	function myclick_nm(v_id) {				// Responds to sidebar click - view responder data
		alert("No track data");
		}

	function myclick(id, call) {					// Responds to sidebar click, then triggers listener above -  note [id]
		GEvent.trigger(gmarkers[id], "click");
		}

	function doGrid() {
		map.addOverlay(new LatLonGraticule());
		}

	function do_lat (lat) {
		document.forms[0].frm_lat.disabled=false;
		document.forms[0].frm_lat.value=lat.toFixed(6);
		document.forms[0].frm_lat.disabled=true;
		}
	function do_lng (lng) {
		document.forms[0].frm_lng.disabled=false;
		document.forms[0].frm_lng.value=lng.toFixed(6);
		document.forms[0].frm_lng.disabled=true;
		}
						// 2/24/09
	var direcs=new Array("north.png","north_east.png","east.png","south_east.png","south.png","south_west.png","west.png","north_west.png", "north.png");	// 10/4/08

	var icons=[];						// note globals

<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}unit_types` ORDER BY `id`";
    // types in use
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $icons = $GLOBALS['icons'];
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // map type to blank icon id
        $blank = $icons[$row['icon']];
        print "\ticons[" . $row['id'] . "] = " . $row['icon'] . ";\n";
        //
    }
    unset($result);
    ?>

	var starticon = new GIcon();
	starticon.image = "./markers/start.png";	
	starticon.iconSize = new GSize(16, 16);
	starticon.iconAnchor = new GPoint(8, 8);

	var endicon = new GIcon();
	endicon.image = "./markers/end.png";
	endicon.iconSize = new GSize(16, 16);
	endicon.iconAnchor = new GPoint(8, 8);

	var map;
	var side_bar_html = "<TABLE border=0 CLASS='sidebar' ID='tbl_responders'>";
	side_bar_html += "<TR class='even'>	<TD colspan=99 ALIGN='center'><B>Mobile Units</B></TD></TR>";
	side_bar_html += "<TR class='odd'>	<TD colspan=99 ALIGN='center'>Click line or icon for information</TD></TR>";
	side_bar_html += "<TR class='even'>	<TD></TD><TD ALIGN='center'>Name</TD><TD ALIGN='center'>Description</TD><TD ALIGN='center'>Status</TD><TD>M</TD><TD ALIGN='center'>#</TD><TD ALIGN='center'>As of</TD></TR>";
	var gmarkers = [];
	var infoTabs = [];
	var which;
	var i = k = 0;			// sidebar/icon index, track point index
	var points = false;								// none

	map = new GMap2(document.getElementById("map"));		// create the map
//	map.addControl(new GSmallMapControl());
	map.setUIToDefault();									// 8/13/10

	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);		// <?php 
    echo get_variable('def_lat');
    ?>

	var bounds = new GLatLngBounds();						// create  bounding box
//	map.addControl(new GOverviewMapControl());
	map.enableScrollWheelZoom(); 	

	var listIcon = new GIcon();
	listIcon.image = "./markers/yellow.png";	
	listIcon.shadow = "./markers/sm_shadow.png";
	listIcon.iconSize = new GSize(20, 34);
	listIcon.shadowSize = new GSize(37, 34);
	listIcon.iconAnchor = new GPoint(8, 28);
	listIcon.infoWindowAnchor = new GPoint(9, 2);
	listIcon.infoShadowAnchor = new GPoint(18, 25);

	GEvent.addListener(map, "infowindowclose", function() {		// re-center after  move/zoom
		map.setCenter(center,zoom);
		map.addOverlay(gmarkers[which])
		});

<?php 
    $calls = array();
    $calls_nr = array();
    $calls_time = array();
    $query = "SELECT * , UNIX_TIMESTAMP(updated) AS `updated` FROM `{$GLOBALS['mysql_prefix']}tracks_hh` ORDER BY `id` DESC LIMIT 20";
    // 6/17/08
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), __FILE__, __LINE__);
    while ($row = mysql_fetch_assoc($result)) {
        if (isset($calls[$row['source']])) {
            // array_key_exists ( mixed key, array search )
            $calls_nr[$row['source']]++;
        } else {
            //			array_push ($calls, trim($row['source']));
            $calls[trim($row['source'])] = TRUE;
            $calls_nr[$row['source']] = 1;
        }
        $calls_time[$row['source']] = $row['packet_date'];
        // save latest - note query order
    }
    //	dump($calls);
    //	dump($calls_nr);
    //	dump($calls_time);
    $query = "SELECT `id`, `status_val` FROM `{$GLOBALS['mysql_prefix']}un_status`";
    // build unit status values array
    $temp_result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), __FILE__, __LINE__);
    $status_vals[0] = "TBD";
    while ($temp_row = mysql_fetch_assoc($temp_result)) {
        // build array of values
        $status_vals[$temp_row['id']] = $temp_row['status_val'];
    }
    $query = "SELECT *, UNIX_TIMESTAMP(updated) AS updated FROM `{$GLOBALS['mysql_prefix']}responder` WHERE `mobile` = 1 AND `aprs` = 1 AND `callsign` <> '' ORDER BY `name`";
    // 1/24/09
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    //	dump(mysql_affected_rows());
    $bulls = array(0 => "", 1 => "red", 2 => "green", 3 => "white", 4 => "black");
    // major while ... for mobile RESPONDER data starts here
    $aprs = FALSE;
    // legend show/not boolean
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        $toedit = is_guest() ? "" : "<A HREF='units.php?func=responder&edit=true&id=" . $row['id'] . "'><U>Edit</U></A>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        $totrack = empty($row['callsign']) ? "" : "&nbsp;&nbsp;&nbsp;&nbsp;<SPAN onClick = do_track('" . $row['callsign'] . "');><U>Tracks</U></SPAN>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        $temp = $row['un_status_id'];
        // 2/24/09
        $the_status = array_key_exists($temp, $status_vals) ? $status_vals[$temp] : "??";
        // 2/2/09
        if (!$row['mobile'] == 1) {
            // for fixed units
            $mode = $row['lat'] == 0 ? 4 : 0;
            //  toss invalid lat's
            ?>
		var point = new GLatLng(<?php 
            print $row['lat'];
            ?>
, <?php 
            print $row['lng'];
            ?>
);	// mobile position

<?php 
        } else {
            // is mobile, do infowin, etc.
            $query = "SELECT DISTINCT `source`, `latitude`, `longitude` ,`course` ,`speed` ,`altitude` ,`closest_city` ,`status` , UNIX_TIMESTAMP(packet_date) AS `packet_date`, UNIX_TIMESTAMP(updated) AS `updated` FROM `{$GLOBALS['mysql_prefix']}tracks_hh` WHERE `source` = '" . $row['callsign'] . "' ORDER BY `updated`";
            //	6/16/08
            $result_tr = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
            if (mysql_affected_rows() > 0) {
                ?>
				var j=1;				// point counter this unit
				var ender = <?php 
                print mysql_affected_rows();
                ?>
 ;
<?php 
                $last = "";
                while ($row_tr = stripslashes_deep(mysql_fetch_assoc($result_tr))) {
                    ?>
					bounds.extend(new GLatLng(<?php 
                    print $row_tr['latitude'];
                    ?>
, <?php 
                    print $row_tr['longitude'];
                    ?>
));	// all points to bounding box
					var point = new GLatLng(<?php 
                    print $row_tr['latitude'];
                    ?>
, <?php 
                    print $row_tr['longitude'];
                    ?>
);
					var html = "<b><?php 
                    print $row_tr['source'];
                    ?>
</b><br /><br /><?php 
                    print format_date($row['updated']);
                    ?>
";
					var heading = Math.round(<?php 
                    print intval($row_tr['course']);
                    ?>
/45);		// 10/4/08
		
					var marker = create_track_Marker(point, html, j, ender, heading);
					map.addOverlay(marker);	

<?php 
                    if (!empty($last)) {
                        ?>
			
						var polyline = new GPolyline([
						    new GLatLng(<?php 
                        print $last['latitude'];
                        ?>
, <?php 
                        print $last['longitude'];
                        ?>
),		// prior point
						    new GLatLng(<?php 
                        print $row_tr['latitude'];
                        ?>
, <?php 
                        print $row_tr['longitude'];
                        ?>
)	// current point
							], "#FF0000", 2);
						map.addOverlay(polyline);
						points++;
						j++;k++;
<?php 
                    }
                    // end if (!empty($last))
                    $last = $row_tr;
                    // either way
                }
                // end while ($row_tr...)
                $mode = $last['speed'] == 0 ? 1 : 2;
                if ($last['speed'] >= 50) {
                    $mode = 3;
                }
                ?>
					var point = new GLatLng(<?php 
                print $last['latitude'];
                ?>
, <?php 
                print $last['longitude'];
                ?>
);	// mobile position
<?php 
            } else {
                // no track data, do sidebar only
                $mode = 4;
            }
            // end if/else (mysql_affected_rows()>0;) - no track data
        }
        // end mobile
        //										common to all modes
        $the_bull = $mode == 0 ? "" : "<FONT COLOR=" . $bulls[$mode] . "><B>&bull;</B></FONT>";
        $eols = array("\r\n", "\n", "\r");
        // all flavors of eol
        $sidebar_line = "<TD>" . shorten($row['name'], 30) . "</TD><TD>" . shorten(str_replace($eols, " ", $row['description']), 16) . "</TD>";
        //		$sidebar_line .= "<TD CLASS='td_data'> " . shorten($status_vals[$row['un_status_id']], 16) . "</TD><TD CLASS='td_data'> " . $the_bull . "</TD>";
        $sidebar_line .= "<TD CLASS='td_data'> " . shorten($the_status, 16) . "</TD><TD CLASS='td_data'> " . $the_bull . "</TD>";
        $the_count = isset($calls[$row['callsign']]) ? $calls_nr[$row['callsign']] : "";
        // track records
        //		$the_time = (isset($calls[$row['callsign']]))? $calls_time[$row['callsign']]: $row['updated'];		// latest report time
        if (isset($calls[$row['callsign']])) {
            $the_time = $calls_time[$row['callsign']];
            $the_class = "aprs";
            $aprs = TRUE;
            // show legend
        } else {
            $the_time = $row['updated'];
            $the_class = "td_data";
        }
        $sidebar_line .= "<TD CLASS='td_data' ALIGN='right'> " . $the_count . "</TD>";
        $sidebar_line .= "<TD CLASS='{$the_class}'>" . format_sb_date($the_time) . "</TD>";
        ?>

		var do_map = true;		// default
		
<?php 
        $temptype = $u_types[$row['type']];
        $the_type = $temptype[0];
        // 1/1/09
        $tab_1 = "<TABLE CLASS='infowin' width='" . $_SESSION['scr_width'] / 4 . "'>";
        //		$tab_1 .= "<TR CLASS='even'><TD COLSPAN=2 ALIGN='center'><B>" . shorten($row['name'], 48) . "</B> - " . $types[$row['type']] . "</TD></TR>";
        $tab_1 .= "<TR CLASS='even'><TD COLSPAN=2 ALIGN='center'><B>" . shorten($row['name'], 48) . "</B> - " . $the_type . "</TD></TR>";
        $tab_1 .= "<TR CLASS='odd'><TD>Description:</TD><TD>" . shorten(str_replace($eols, " ", $row['description']), 32) . "</TD></TR>";
        //		$tab_1 .= "<TR CLASS='even'><TD>Status:</TD><TD>" . $status_vals[$row['un_status_id']] . " </TD></TR>";
        $tab_1 .= "<TR CLASS='odd'><TD>Contact:</TD><TD>" . $row['contact_name'] . " Via: " . $row['contact_via'] . "</TD></TR>";
        $tab_1 .= "<TR CLASS='even'><TD>As of:</TD><TD>" . format_date($row['updated']) . "</TD></TR>";
        $tab_1 .= "<TR CLASS='odd'><TD COLSPAN=2 ALIGN='center'>Details:" . $totrack . "&nbsp;&nbsp;&nbsp;&nbsp;" . $toedit . "<A HREF='units.php?func=responder&view=true&id=" . $row['id'] . "'><U>View</U></A></TD></TR>";
        $tab_1 .= "</TABLE>";
        //		dump($row['callsign']);
        switch ($mode) {
            case 0:
                // not mobile
                ?>
			
				do_sidebar ("<?php 
                print str_replace($eols, " ", $sidebar_line);
                ?>
", i, <?php 
                print $row_tr['source'];
                ?>
);
				var myinfoTabs = [
					new GInfoWindowTab("<?php 
                print nl2brr(shorten($row['name'], 10));
                ?>
", "<?php 
                print $tab_1;
                ?>
"),
					new GInfoWindowTab("Zoom", "<div id='detailmap' class='detailmap'></div>")
					];
<?php 
                break;
            case 1:
                // stopped
            // stopped
            case 2:
                // moving
            // moving
            case 3:
                // fast
                ?>
			
				do_sidebar ("<?php 
                print str_replace($eols, " ", $sidebar_line);
                ?>
", i);
<?php 
                $tab_2 = "<TABLE CLASS='infowin' width='" . $_SESSION['scr_width'] / 4 . "'>";
                $tab_2 .= "<TR CLASS='even'><TD COLSPAN=2 ALIGN='center'><B>" . $last['source'] . "</B></TD></TR>";
                $tab_2 .= "<TR CLASS='odd'><TD>Course: </TD><TD>" . $last['course'] . ", Speed:  " . $last['speed'] . ", Alt: " . $last['altitude'] . "</TD></TR>";
                $tab_2 .= "<TR CLASS='even'><TD>Closest city: </TD><TD>" . $last['closest_city'] . "</TD></TR>";
                $tab_2 .= "<TR CLASS='odd'><TD>Status: </TD><TD>" . $last['status'] . "</TD></TR>";
                $tab_2 .= "<TR CLASS='even'><TD>As of: </TD><TD>" . format_date($last['packet_date']) . "(UTC)</TD></TR>";
                //	6/16/08
                $tab_2 .= "</TABLE>";
                ?>

				var myinfoTabs = [
					new GInfoWindowTab("<?php 
                print nl2brr(shorten($row['name'], 10));
                ?>
", "<?php 
                print $tab_1;
                ?>
"),
					new GInfoWindowTab("<?php 
                print $last['source'];
                ?>
", "<?php 
                print $tab_2;
                ?>
"),
					new GInfoWindowTab("Zoom", "<div id='detailmap' class='detailmap'></div>")
					];
<?php 
                break;
            case 4:
                // mobile - no track
                ?>
				do_sidebar_nm ("<?php 
                print str_replace($eols, " ", $sidebar_line);
                ?>
", i, <?php 
                print $row['id'];
                ?>
);	// special sidebar link - adds id for view
				var do_map = false;
<?php 
                break;
            default:
                echo "mode error: {$mode}";
                break;
        }
        // end switch
        ?>
			if (do_map) {
				var marker = createMarker(point, myinfoTabs,<?php 
        print $row['type'];
        ?>
, i);	// (point,tabs, color, id)
				map.addOverlay(marker);
				}
			i++;				// zero-based
<?php 
    }
    // end major while ($row = ...) for each responder
    $aprs_legend = $aprs ? "<TD CLASS='aprs' ALIGN='center'>APRS time</TD>" : "<TD></TD>";
    ?>
	if (!points) {		// any?
		map.setCenter(new GLatLng(<?php 
    echo get_variable('def_lat');
    ?>
, <?php 
    echo get_variable('def_lng');
    ?>
), <?php 
    echo get_variable('def_zoom');
    ?>
);
		}
	else {
		center = bounds.getCenter();
		zoom = map.getBoundsZoomLevel(bounds)-1;
		map.setCenter(center,zoom);
		}
	side_bar_html+= "<TR CLASS='" + colors[i%2] +"'><TD COLSPAN=6>&nbsp;</TD></TR>";
	side_bar_html+= "<TR CLASS='" + colors[(i+1)%2] +"'><TD COLSPAN=6 ALIGN='center'><B>M</B>obility:&nbsp;&nbsp; stopped: <FONT COLOR='red'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;moving: <FONT COLOR='green'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;fast: <FONT COLOR='white'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;silent: <FONT COLOR='black'><B>&bull;</B></FONT></TD><?php 
    print $aprs_legend;
    ?>
</TR>";
<?php 
    if (!empty($addon)) {
        print "\n\tside_bar_html +=\"" . $addon . "\"\n";
    }
    //	$temp = get_variable('auto_poll');
    //	$aprs_but = (intval($temp>0))? "<TR><TD COLSPAN=99 ALIGN='center'><INPUT TYPE='button' value= 'APRS'  onClick ='do_aprs_window();'></TD></TR>": "";
    $aprs_but = "";
    ?>
	side_bar_html += "<?php 
    print $aprs_but;
    ?>
";
	
	document.getElementById("side_bar").innerHTML += side_bar_html;	// append the assembled side_bar_html contents to the side_bar div
	
<?php 
    do_kml();
    ?>
</SCRIPT>
<?php 
}
예제 #10
0
                        print "<TR CLASS = 'even'><TD CLASS='td_label' ALIGN='center'  COLSPAN=6>Select Closed Tickets for Permanent Deletion</TD></TR>";
                        //				print "<TR CLASS = 'odd'><TD COLSPAN=3>&nbsp;</TD></TR>";
                        print "<TR CLASS = 'odd'><TD ALIGN='left'>&nbsp;&nbsp;&nbsp;Ticket</TD><TD ALIGN='left'>&nbsp;&nbsp;&nbsp;Closed</TD><TD>Actions</TD><TD ALIGN='center'>Patients</TD><TD ALIGN='center'>Assigns</TD><TD>Del</TD></TR>";
                        $i = 0;
                        while ($row = stripslashes_deep(mysql_fetch_array($result))) {
                            $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}action` WHERE `ticket_id` = " . $row['id'];
                            $res_temp = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
                            $no_acts = mysql_affected_rows();
                            $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}patient` WHERE `ticket_id` = " . $row['id'];
                            $res_temp = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
                            $no_pers = mysql_affected_rows();
                            $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` WHERE `ticket_id` = " . $row['id'];
                            $res_temp = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
                            $no_assns = mysql_affected_rows();
                            print "<TR CLASS='" . $evenodd[$i % 2] . "'><TD CLASS='td_label'>" . shorten($row['scope'], 50) . "</TD>";
                            print "<TD CLASS='td_label'>" . format_sb_date($row['problemend']) . "</TD>";
                            print "<TD ALIGN='center'>{$no_acts}</TD>";
                            print "<TD ALIGN='center'>{$no_pers}</TD>";
                            print "<TD ALIGN='center'>{$no_assns}</TD>";
                            print "<TD CLASS='td_label'><INPUT TYPE='checkbox' NAME = 'T" . $row['id'] . "' onClick = 'this.form.delcount.value++;'></TD></TR>\n";
                            $i++;
                        }
                        // end while($row ...)
                        print "<TR CLASS='" . $evenodd[$i % 2] . "'><TD ALIGN='center' COLSPAN=6><BR/>";
                        ?>
					<INPUT TYPE='button' VALUE='Cancel' 	onClick='document.can_Form.submit();'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
					<INPUT TYPE='button' VALUE='Select All' onClick = 'document.del_Form.delcount.value=1; all_ticks(true)';>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
					<INPUT TYPE='button' VALUE='Reset' 		onClick = 'document.del_Form.reset();'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
					<INPUT TYPE='button' VALUE='Submit' 	onClick = 'collect();'></TD></TR>
					<INPUT TYPE='hidden' NAME = 'idstr' VALUE=''>
					<INPUT TYPE='hidden' NAME = 'delcount' VALUE=0>
function do_list($unit_id = "", $capabilities = "", $searchtype)
{
    global $row_ticket, $dispatches_disp, $dispatches_act, $from_top, $from_left, $eol, $sidebar_width;
    switch ($row_ticket['severity']) {
        //color tickets by severity
        case $GLOBALS['SEVERITY_MEDIUM']:
            $severityclass = 'severity_medium';
            break;
        case $GLOBALS['SEVERITY_HIGH']:
            $severityclass = 'severity_high';
            break;
        default:
            $severityclass = '';
            break;
    }
    $query = "SELECT *,UNIX_TIMESTAMP(problemstart) AS problemstart,UNIX_TIMESTAMP(problemend) AS problemend,UNIX_TIMESTAMP(booked_date) AS booked_date,\n\t\tUNIX_TIMESTAMP(date) AS date,UNIX_TIMESTAMP(`{$GLOBALS['mysql_prefix']}ticket`.`updated`) AS updated, `{$GLOBALS['mysql_prefix']}ticket`.`description` AS `tick_descr` FROM `{$GLOBALS['mysql_prefix']}ticket`  \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}in_types` `ty` ON (`{$GLOBALS['mysql_prefix']}ticket`.`in_types_id` = `ty`.`id`)\t\t\n\t\tWHERE `{$GLOBALS['mysql_prefix']}ticket`.`id`= " . quote_smart($_GET['ticket_id']) . " LIMIT 1";
    // 7/24/09 10/16/08 Incident location 09/25/09 Pre Booking
    //	print __LINE__;
    //	dump($query);
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $row_ticket = stripslashes_deep(mysql_fetch_array($result));
    $facility = $row_ticket['facility'];
    $rec_fac = $row_ticket['rec_facility'];
    $lat = $row_ticket['lat'];
    $lng = $row_ticket['lng'];
    $problemstart = $row_ticket['problemstart'];
    $problemend = $row_ticket['problemend'];
    //	dump(mysql_format_date($row_ticket['problemstart']));
    //	print "var thelat = " . $lat . ";\nvar thelng = " . $lng . ";\n";		// set js-accessible location data
    unset($result);
    if ($rec_fac > 0) {
        $query_rfc = "SELECT * FROM `{$GLOBALS['mysql_prefix']}facilities` WHERE `id`= {$rec_fac} ";
        // 7/24/09 10/16/08 Incident location 10/06/09 Multi point routing
        $result_rfc = mysql_query($query_rfc) or do_error($query_rfc, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        $row_rec_fac = stripslashes_deep(mysql_fetch_array($result_rfc));
        $rf_lat = $row_rec_fac['lat'];
        $rf_lng = $row_rec_fac['lng'];
        $rf_name = $row_rec_fac['name'];
        //		print "var thereclat = " . $rf_lat . ";\nvar thereclng = " . $rf_lng . ";\n";		// set js-accessible location data for receiving facility
    } else {
        //		print "var thereclat;\nvar thereclng;\n";		// set js-accessible location data for receiving facility
    }
    ?>
<SCRIPT>
	var color=0;
	var last_from;
	var last_to;
	var rec_fac;
	var current_id;			// 10/25/08
	var output_direcs = "";	//10/6/09
	var have_direcs = 0;	//10/6/09
	var tick_name = '<?php 
    print $row_ticket['scope'];
    ?>
';	//10/29/09

		var colors = new Array ('odd', 'even');
		
		var Direcs = null;			// global
		var Now;
		var mystart;
		var myend;

		function do_sidebar(sidebar, color, id, unit_id) {						// No map
			var letter = ""+ id;										// start with 1 - 1/5/09 - 1/29/09
			marker = null;
			gmarkers[id] = null;										// marker to array for side bar click function
	
			side_bar_html += "<TR ID = '_tr" + id  + "' CLASS='" + colors[(id)%2] +"' VALIGN='bottom' onClick = myclick(" + id + "," + unit_id +");><TD>";

			side_bar_html += "<IMG BORDER=0 SRC='rtarrow.gif' ID = \"R" + id + "\"  STYLE = 'visibility:hidden;'></TD>";
			var letter = ""+ id;										// start with 1 - 1/5/09 - 1/29/09

//			var the_class = (direcs[id])?  "emph" : "td_label";
			var the_class = (lats[id])?  "emph" : "td_label";
			side_bar_html += "<TD CLASS='" + the_class + "'>" + letter + " "+ sidebar +"</TD></TR>\n";
			return null;
			}				// end function create Marker()


		function myclick(id, unit_id) {								// responds to side bar click
//			alert (821);
			var norecfac = "";
			if (document.getElementById(current_id)) {
				document.getElementById(current_id).style.visibility = "hidden";			// hide last check if defined
				}
			current_id= "R"+id;
			document.getElementById(current_id).style.visibility = "visible";			// show newest

			}					// end function my click(id)

		function handleErrors(){		//G_GEO_UNKNOWN_DIRECTIONS 
			if (gdir.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS ) {
				alert("501: directions unavailable\n\nClick map point for directions.");
				}
			else if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
				alert("440: No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
				alert("442: A map request could not be processed, reason unknown.\n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
				alert("444: Technical error.\n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_BAD_KEY)
				alert("448: The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
				alert("450: A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
			else alert("451: An unknown error occurred.");
			}		// end function handleErrors()

		function onGDirectionsLoad(){ 
//			var temp = gdir.getSummaryHtml();
			}		// function onGDirectionsLoad()

		function guest () {
			alert ("Demonstration only.  Guests may not commit dispatch!");
			}
			
		function validate(){		// frm_id_str
			msgstr="";
			for (var i =1;i<unit_sets.length;i++) {				// 3/30
				if (unit_sets[i]) {
					msgstr+=unit_names[i]+"\n";
					document.routes_Form.frm_id_str.value += unit_ids[i] + "|";
					}
				}
			if (msgstr.length==0) {
				var more = (nr_units>1)? "s": ""
				alert ("Please select unit" + more + ", or cancel");
				return false;
				}
			else {
				var quick = <?php 
    print intval(get_variable("quick") == 1) ? "true;\n" : "false;\n";
    ?>
			
//				if (confirm ("Please confirm Unit dispatch as follows\n\n" + msgstr)) {
				if ((quick) || (confirm ("Please confirm unit dispatch\n\n" + msgstr))) {		// 11/23/09

					document.routes_Form.frm_id_str.value = document.routes_Form.frm_id_str.value.substring(0, document.routes_Form.frm_id_str.value.length - 1);	// drop trailing separator
					document.routes_Form.frm_name_str.value = msgstr;	// for re-use
					document.routes_Form.submit();
					document.getElementById("outer").style.display = "none";
					document.getElementById("bottom").style.display = "block";					
					}
				else {
					document.routes_Form.frm_id_str.value="";	
					return false;
					}
				}

			}		// end function validate()
	
		function exists(myarray,myid) {
			var str_key = " " + myid;		// force associative
			return ((typeof myarray[str_key])!="undefined");		// exists if not undefined
			}		// end function exists()
			
		var icons=[];						// note globals
<?php 
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}unit_types` ORDER BY `id`";
    // types in use
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $icons = $GLOBALS['icons'];
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // map type to blank icon id
        $blank = $icons[$row['icon']];
        print "\ticons[" . $row['id'] . "] = " . $row['icon'] . ";\n";
        //
    }
    unset($result);
    ?>
		var side_bar_html = "<TABLE border=0 CLASS='sidebar' ID='tbl_responders' STYLE = 'WIDTH: <?php 
    print $sidebar_width;
    ?>
px;'>";

		var gmarkers = [];
		var lats = [];
		var lngs = [];
		var distances = [];
		var unit_names = [];		// names 
		var unit_sets = [];			// settings
		var unit_ids = [];			// id's
		var unit_assigns =  [];		// unit id's assigned this incident
		var direcs =  [];			// if true, do directions - 7/13/09

		var which;			// marker last selected
		var i = 0;			// sidebar/icon index
	
		var nr_units = 	0;
		var email= false;
		
<?php 
    function get_cd_str($in_row)
    {
        // unit row in,
        global $unit_id;
        // 11/18/10
        //																			// first, already on this run?
        $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` WHERE  `ticket_id` = " . quote_smart($_GET['ticket_id']) . "\n\t\t\t\t\t AND (`responder_id`={$in_row['unit_id']}) \n\t\t\t\t\t AND ((`clear` IS NULL) OR (DATE_FORMAT(`clear`,'%y') = '00')) LIMIT 1;";
        // 6/25/10
        $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        if (mysql_affected_rows() == 1) {
            return " CHECKED DISABLED ";
        }
        if ($unit_id != "" && (mysql_affected_rows() != 1 || mysql_affected_rows() == 1 && intval($in_row['multi']) == 1)) {
            print "checked";
            return " CHECKED ";
        }
        // 12/18/10 - Checkbox checked here individual unit seleted.
        if (intval($in_row['dispatch']) == 2) {
            return " DISABLED ";
        }
        // 2nd, disallowed  - 5/30/10
        if (intval($in_row['multi']) == 1) {
            return "";
        }
        // 3rd, allowed
        // 3rd, on another run?
        $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\t\t\t\tWHERE `responder_id`={$in_row['unit_id']} \n\t\t\t\t\tAND ((`clear` IS NULL) OR (DATE_FORMAT(`clear`,'%y') = '00'))\n\t\t\t\t\tLIMIT 1;";
        // 6/25/10
        $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        if (mysql_affected_rows() == 1) {
            return " DISABLED ";
        } else {
            return "";
        }
    }
    // function get cd_str($in_row)
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    // build js array of responders to this ticket - possibly none
    $query = "SELECT `ticket_id`, `responder_id` FROM `{$GLOBALS['mysql_prefix']}assigns` WHERE `ticket_id` = " . quote_smart($_GET['ticket_id']);
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($assigns_row = stripslashes_deep(mysql_fetch_array($result))) {
        print "\t\tunit_assigns[' '+ " . $assigns_row['responder_id'] . "]= true;\n";
        // note string forced
    }
    print "\n";
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE `id`=" . quote_smart($_GET['ticket_id']) . " LIMIT 1;";
    // 4/5/10
    $result_pos = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    if (mysql_affected_rows() == 1) {
        $row_position = stripslashes_deep(mysql_fetch_array($result_pos));
        $latitude = $row_position['lat'];
        $longitude = $row_position['lng'];
        unset($result_pos);
    } else {
        //			dump ($query);
    }
    $where = empty($unit_id) ? "" : " AND `r`.`id` = {$unit_id} ";
    // revised 5/23/08 per AD7PE
    if (empty($unit_id)) {
        // 11/18/10
        $where2 = empty($capabilities) ? "" : " AND (";
        // 11/18/10
        $searchitems = empty($capabilities) ? "" : explode(" ", $capabilities);
        if ($searchitems) {
            for ($j = 0; $j < count($searchitems); $j++) {
                if ($j + 1 != count($searchitems)) {
                    $where2 .= "`{$GLOBALS['mysql_prefix']}responder`.`capab` LIKE '%{$searchitems[$j]}%' {$searchtype} ";
                } else {
                    $where2 .= "`{$GLOBALS['mysql_prefix']}responder`.`capab` LIKE '%{$searchitems[$j]}%')";
                }
            }
        }
    } else {
        $where2 = "";
    }
    // ============================= Regions Stuff
    // Allows Tickets to be dispatched to any responders in the same region as the current user.
    // $query = "SELECT * FROM `$GLOBALS[mysql_prefix]allocates` WHERE `type`= 4 AND `resource_id` = '$_SESSION[user_id]' ORDER BY `id` ASC;";	// 4/18/11
    // $result = mysql_query($query);	// 5/4/11
    // $al_groups = array();
    // $al_names = "";
    // while ($row = stripslashes_deep(mysql_fetch_assoc($result))) 	{	// 5/4/11
    // $al_groups[] = $row['group'];
    // $query2 = "SELECT * FROM `$GLOBALS[mysql_prefix]region` WHERE `id`= '$row[group]';";	// 5/4/11
    // $result2 = mysql_query($query2);	// 5/4/11
    // while ($row2 = stripslashes_deep(mysql_fetch_assoc($result2))) 	{	// 5/4/11
    // $al_names .= $row2['group_name'] . ", ";
    // }
    // }
    // if(isset($_SESSION['viewed_groups'])) {
    // $al_groups= explode(",",$_SESSION['viewed_groups']);
    // }
    // if(!isset($_SESSION['viewed_groups'])) {	//	5/4/11
    // $x=0;
    // $where3 = "AND (";
    // foreach($al_groups as $grp) {
    // $where4 = (count($al_groups) > ($x+1)) ? " OR " : ")";
    // $where3 .= "`a`.`group` = '{$grp}'";
    // $where3 .= $where4;
    // $x++;
    // }
    // } else {
    // $x=0;
    // $where3 = "AND (";
    // foreach($al_groups as $grp) {
    // $where4 = (count($al_groups) > ($x+1)) ? " OR " : ")";
    // $where3 .= "`a`.`group` = '{$grp}'";
    // $where3 .= $where4;
    // $x++;
    // }
    // }
    // $where3 .= " AND `a`.`type` = 2";
    // Replacement code - only allows Tickets to be dispatched to responders in the same region
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 1 AND `resource_id` = " . quote_smart($_GET['ticket_id']) . " ORDER BY `id` ASC;";
    // 4/18/11
    $result = mysql_query($query);
    // 5/4/11
    $al_groups = array();
    $al_names = "";
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // 5/4/11
        $al_groups[] = $row['group'];
        $query2 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}region` WHERE `id`= '{$row['group']}';";
        // 5/4/11
        $result2 = mysql_query($query2);
        // 5/4/11
        while ($row2 = stripslashes_deep(mysql_fetch_assoc($result2))) {
            // 5/4/11
            $al_names .= $row2['group_name'] . ", ";
        }
    }
    $x = 0;
    $where3 = "WHERE (";
    foreach ($al_groups as $grp) {
        $where4 = count($al_groups) > $x + 1 ? " OR " : ")";
        $where3 .= "`a`.`group` = '{$grp}'";
        $where3 .= $where4;
        $x++;
    }
    $where3 .= " AND (`a`.`type` = 2)";
    // ================================ end of regions stuff
    // 4/5/10
    $query = "SELECT *, UNIX_TIMESTAMP(`updated`) AS `updated`,\n\t\t\t`r`.`id` AS `unit_id`, \n\t\t\t`s`.`status_val` AS `unitstatus`, `contact_via`, \n\t\t\t(POW(ABS({$latitude} - `r`.`lat`), 2.0) +  POW(ABS({$longitude} - `r`.`lng`), 2.0)) AS `distance`\t\t\t\n\t\t\tFROM `{$GLOBALS['mysql_prefix']}responder` `r`\n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}un_status` `s` ON (`r`.`un_status_id` = `s`.`id`)\n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON (`r`.`id` = `a`.`resource_id`)\t\t\t\t\t\n\t\t\t{$where3} {$where} {$where2} GROUP BY unit_id\n\t\t\tORDER BY `distance` ASC, `handle` ASC, `name` ASC, `unit_id` ASC";
    // 12/09/09
    //		print $query;
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    if (mysql_affected_rows() > 0) {
        $end_date = intval($problemend) > 1 ? $problemend : time() - get_variable('delta_mins') * 60;
        //			dump(mysql_format_date($problemstart));
        //			dump(mysql_format_date($end_date));
        $elapsed = my_date_diff($problemstart, $end_date);
        // 5/13/10
        ?>
		side_bar_html += "<TR class='even'>	<TD CLASS='<?php 
        print $severityclass;
        ?>
' COLSPAN=99 ALIGN='center'><B>To Incident: <I><?php 
        print shorten($row_ticket['scope'], 20) . "</I>&nbsp;&nbsp;(" . $elapsed;
        ?>
)</B></TD></TR>\n";
		side_bar_html += "<TR class='odd' STYLE = 'white-space:nowrap;'><TD COLSPAN=3></TD><TD ALIGN='center'>Unit</TD><TD ALIGN='center'>Call</TD><TD ALIGN='center'>Status</TD><TD ALIGN='center'>As of</TD></TR>\n";

<?php 
        // major while ... for RESPONDER data starts here
        $i = $k = 1;
        // sidebar/icon index
        while ($unit_row = stripslashes_deep(mysql_fetch_assoc($result))) {
            // 7/13/09
            $has_coords = my_is_float($unit_row['lat']) && my_is_float($unit_row['lng']);
            // 2/25/09, 7/7/09
            $has_rem_source = intval($unit_row['aprs']) == 1 || intval($unit_row['instam']) == 1 || intval($unit_row['locatea']) == 1 || intval($unit_row['gtrack']) == 1 || intval($unit_row['glat']) == 1;
            // 11/15/09
            if (is_email($unit_row['contact_via'])) {
                print "\t\temail= true\n";
            }
            ?>
				nr_units++;

				var i = <?php 
            print $i;
            ?>
;						// top of loop
				
				unit_names[i] = "<?php 
            print addslashes($unit_row['name']);
            ?>
";	// unit name 8/25/08, 4/27/09
				unit_sets[i] = false;								// pre-set checkbox settings				
				unit_preselected = "<?php 
            print $unit_id;
            ?>
";
				if (unit_preselected != "") {
					unit_sets[i] = true;								// pre-set checkbox settings	
					} else {
					unit_sets[i] = false;
					}

				
				unit_ids[i] = <?php 
            print $unit_row['unit_id'];
            ?>
;
				new_element = document.createElement("input");								// please don't ask!
				new_element.setAttribute("type", 	"checkbox");
				new_element.setAttribute("name", 	"unit_<?php 
            print $unit_row['unit_id'];
            ?>
");
				new_element.setAttribute("id", 		"element_id");
				new_element.setAttribute("style", 	"visibility:hidden");
				document.forms['routes_Form'].appendChild(new_element);
				var dist_mi = "na";
				var multi = <?php 
            print intval($unit_row['multi']) == 1 ? "true;\n" : "false;\n";
            ?>
	// 5/22/09
<?php 
            $dispatched_to = array_key_exists($unit_row['unit_id'], $dispatches_disp) ? $dispatches_disp[$unit_row['unit_id']] : "";
            ?>
					
				sidebar_line = "<TD ALIGN='center'><INPUT TYPE='checkbox' <?php 
            print get_cd_str($unit_row);
            ?>
 NAME = 'unit_" + <?php 
            print $unit_row['unit_id'];
            ?>
 + "' onClick='unit_sets[<?php 
            print $i;
            ?>
]=this.checked;'></TD>";

				sidebar_line += "<TD TITLE = \"<?php 
            print addslashes($unit_row['name']);
            ?>
\">";
				sidebar_line += "<NOBR><?php 
            print shorten($unit_row['name'], 20);
            ?>
</NOBR></TD>";
				sidebar_line += "<TD><NOBR><?php 
            print shorten(addslashes($dispatched_to), 20);
            ?>
</NOBR></TD>";
				sidebar_line += "<TD TITLE = \"<?php 
            print $unit_row['unitstatus'];
            ?>
\" CLASS='td_data'><?php 
            print shorten($unit_row['unitstatus'], 12);
            ?>
</TD>";
				sidebar_line += "<TD CLASS='td_data'><?php 
            print substr(format_sb_date($unit_row['updated']), 4);
            ?>
</TD>";
<?php 
            print "\n\t\t\t\tdo_sidebar(sidebar_line, color, i);\n";
            $i++;
            $k++;
        }
        // end major while ($unit_row = ...)  for each responder
        print "\t\t var start = 1;\n";
        // already sorted - 3/24/10
    } else {
        print "\t\t var start = 0;\n";
        // already sorted - 3/24/10
    }
    //					responders complete
    ?>

		if (nr_units==0) {
			side_bar_html +="<TR CLASS='odd'><TD ALIGN='center' COLSPAN=99><BR /><BR /><H3>No Units!</H3></TD></TR>";	
			}
		else {
			side_bar_html+= "<TR CLASS='" + colors[i%2] +"'><TD COLSPAN=99>&nbsp;</TD></TR>\n";
			side_bar_html+= "<TR CLASS='" + colors[(i+1)%2] +"'><TD COLSPAN=99 ALIGN='center'><B>M</B>obility:&nbsp;&nbsp; stopped: <FONT COLOR='red'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;moving: <FONT COLOR='green'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;fast: <FONT COLOR='white'><B>&bull;</B></FONT>&nbsp;&nbsp;&nbsp;silent: <FONT COLOR='black'><B>&bull;</B></FONT></TD></TR>\n";
			side_bar_html+= "<TR><TD>&nbsp;</TD></TR>\n";
			}
				
		side_bar_html +="</TABLE>\n";
		document.getElementById("side_bar").innerHTML = side_bar_html;	// put the assembled side_bar_html contents into the side bar div

		if (start>0) {

			var current_id= "R"+start;			//
			document.getElementById(current_id).style.visibility = "visible";		// show link check image at the selected sidebar el ement
				location.href = "#top";				// 11/12/09
				}
	</SCRIPT>
	
<?php 
}
function list_tickets($sort_by_field = '', $sort_value = '', $my_offset = 0)
{
    // list tickets ===================================================
    $time = microtime(true);
    // Gets microseconds
    global $istest, $units_side_bar_height, $do_blink, $nature, $disposition, $patient, $incident, $incidents;
    // 12/3/10
    $can_edit = get_can_edit();
    $query = "SELECT `id` FROM `{$GLOBALS['mysql_prefix']}responder` LIMIT 1";
    // 1/28/11
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $any_units = mysql_affected_rows() == 1;
    $query_sched = "SELECT * FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE (\n\t\t`status`='{$GLOBALS['STATUS_OPEN']}' OR\n\t\t`status`='{$GLOBALS['STATUS_SCHEDULED']})' \n\t\t LIMIT 1";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $any_open_tickets = mysql_affected_rows() == 1;
    $query_sched = "SELECT * FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE (\n\t\t`status`='{$GLOBALS['STATUS_CLOSED']}')\n\t\t LIMIT 1";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $any_closed_tickets = mysql_affected_rows() == 1;
    $query = "SELECT `id` FROM `{$GLOBALS['mysql_prefix']}facilities` LIMIT 1";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $any_facilities = mysql_affected_rows() == 1;
    unset($result);
    @session_start();
    //
    $captions = array("Current situation", "{$incidents} closed today", "{$incidents} closed yesterday+", "{$incidents} closed this week", "{$incidents} closed last week", "{$incidents} closed last week+", "{$incidents} closed this month", "{$incidents} closed last month", "{$incidents} closed this year", "{$incidents} closed last year", "Scheduled {$incidents}");
    $by_severity = array(0, 0, 0);
    // counters // 5/2/10
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}' ORDER BY `id` ASC;";
    //	5/4/11
    $result = mysql_query($query);
    //	5/4/11
    $al_groups = array();
    $al_names = "";
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        //	5/4/11
        $al_groups[] = $row['group'];
        $query2 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}region` WHERE `id`= '{$row['group']}';";
        //	5/4/11
        $result2 = mysql_query($query2);
        // 4/18/11
        while ($row2 = stripslashes_deep(mysql_fetch_assoc($result2))) {
            //	//	5/4/11
            $al_names .= $row2['group_name'] . ", ";
        }
    }
    if (is_super()) {
        //	5/4/11
        $al_names .= "Superadmin Level";
    }
    if (array_key_exists('func', $_GET) && $_GET['func'] == 10) {
        //	3/15/11
        $func = 10;
    } else {
        extract($_GET);
    }
    $cwi = get_variable('closed_interval');
    // closed window interval in hours
    if (isset($_SESSION['list_type'])) {
        $func = $_SESSION['list_type'];
    }
    // 12/02/10	 persistance for the tickets list
    //	$get_status = ((empty($_GET) || ((!empty($_GET)) && (empty ($_GET['status'])))) ) ? "" : $_GET['status'] ;
    $get_sortby = empty($_GET) || !empty($_GET) && empty($_GET['sortby']) ? "" : $_GET['sortby'];
    $get_offset = empty($_GET) || !empty($_GET) && empty($_GET['offset']) ? "" : $_GET['offset'];
    if (!isset($_GET['status'])) {
        $open = "Open";
    } else {
        $open = isset($_GET['status']) && $_GET['status'] == $GLOBALS['STATUS_OPEN'] ? "Open" : "";
        $open = isset($_GET['status']) && $_GET['status'] == $GLOBALS['STATUS_SCHEDULED'] ? "Scheduled" : "";
        //	11/29/10
    }
    if (isset($_SESSION['viewed_groups'])) {
        //	5/4/11
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    } else {
        $curr_viewed = $al_groups;
    }
    $curr_names = "";
    //	5/4/11
    $z = 0;
    //	5/4/11
    foreach ($curr_viewed as $grp_id) {
        //	5/4/11
        $counter = count($curr_viewed) > $z + 1 ? ", " : "";
        $curr_names .= get_groupname($grp_id);
        $curr_names .= $counter;
        $z++;
    }
    $heading = $captions[$func] . " - " . get_variable('map_caption');
    $regs_string = "<FONT SIZE='-1'>Allocated " . get_text("Regions") . ":&nbsp;&nbsp;" . $al_names . "&nbsp;&nbsp;|&nbsp;&nbsp;Currently Viewing " . get_text("Regions") . ":&nbsp;&nbsp;" . $curr_names . "</FONT>";
    //	5/4/11
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    $query = "SELECT `id` FROM `{$GLOBALS['mysql_prefix']}responder`";
    // 5/12/10
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), __FILE__, __LINE__);
    unset($result);
    $required = 48 + mysql_affected_rows() * 22;
    // derived by trial and error - emphasis the latter = 7/18/10
    $the_large_height = (int) min(round($units_side_bar_height * $_SESSION['scr_height'] * 2), $required);
    // see main for $units_side_bar_height value
    $the_height = (int) min(round($units_side_bar_height * $_SESSION['scr_height']), $required);
    // see main for $units_side_bar_height value
    //	$col_width = (int) floor($_SESSION['scr_width'] * .48);
    $buttons_width = (int) get_variable('map_width') - 50;
    $show_controls = isset($_SESSION['hide_controls']) && $_SESSION['hide_controls'] == "s" ? "" : "none";
    //	3/15/11
    $col_butt = isset($_SESSION['hide_controls']) && $_SESSION['hide_controls'] == "s" ? "" : "none";
    //	3/15/11
    $exp_butt = isset($_SESSION['hide_controls']) && $_SESSION['hide_controls'] == "h" ? "" : "none";
    //	3/15/11
    $show_resp = isset($_SESSION['resp_list']) && $_SESSION['resp_list'] == "s" ? "" : "none";
    //	3/15/11
    $resp_col_butt = isset($_SESSION['resp_list']) && $_SESSION['resp_list'] == "s" ? "" : "none";
    //	3/15/11
    $resp_exp_butt = isset($_SESSION['resp_list']) && $_SESSION['resp_list'] == "h" ? "" : "none";
    //	3/15/11
    $show_facs = isset($_SESSION['facs_list']) && $_SESSION['facs_list'] == "s" ? "" : "none";
    //	3/15/11
    $facs_col_butt = isset($_SESSION['facs_list']) && $_SESSION['facs_list'] == "s" ? "" : "none";
    //	3/15/11
    $facs_exp_butt = isset($_SESSION['facs_list']) && $_SESSION['facs_list'] == "h" ? "" : "none";
    //	3/15/11
    $user_level = is_super() ? 9999 : $_SESSION['user_id'];
    $regions_inuse = get_regions_inuse($user_level);
    $group = get_regions_inuse_numbers($user_level);
    //	dump($group);
    //	dump(get_tickets_allocated($group));
    ?>
<TABLE BORDER=0>
	<A NAME=top></a>
	<TR CLASS='even'><TD COLSPAN='3' ALIGN='center'><FONT CLASS='header'><?php 
    print $heading;
    ?>
 </FONT><SPAN ID='sev_counts' STYLE = 'margin-left: 40px'></SPAN></TD></TR>	<!-- 5/2/10 -->
	<TR CLASS='header'><TD COLSPAN='3' ALIGN='center'><SPAN ID='region_flags' style='background: #00FFFF; font-weight: bold;'></SPAN></TD></TR>	<!-- 5/2/10, 3/15/11, 5/4/11 -->
	<TR CLASS='spacer'><TD CLASS='spacer' COLSPAN='3' ALIGN='center'>&nbsp;</TD></TR>				<!-- 3/15/11 -->
	<TR><TD VALIGN='TOP' align='left'>
		<TABLE><TR class = 'heading'><TH width = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.4));
    ?>
 ALIGN='center' COLSPAN='99'>Incidents </TH></TR>
		<TR><TD>		
		<DIV ID = 'side_bar_header' style="height: 60px; width: <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.4));
    ?>
;"></DIV>
		<DIV ID = 'side_bar' style="max-height: <?php 
    print $the_large_height;
    ?>
px; min-height: 100px; overflow-y: scroll; overflow-x: hidden;"></DIV>
		</TD></TR></TABLE>
	<TD style="width: 20px;">&nbsp;&nbsp;</TD>
	<TD VALIGN='top' align='left'>
		<TABLE><TR class = 'heading'><TH width = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.4));
    ?>
 ALIGN='center' COLSPAN='99'>Responders </TH></TR><TR><TD>				<!-- 3/15/11 -->		
		<DIV ID = 'side_bar_r' style="max-height: <?php 
    print $the_height;
    ?>
px; min-height: 200px; overflow-y: scroll; overflow-x: hidden;"></DIV>
		<DIV ID = 'side_bar_rl'></DIV>				<!-- 3/15/11 -->		
		<DIV ID = 'units_legend'></DIV>
		</TD></TR></TABLE>	
		<TABLE><TR class = 'heading'><TH width = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.4));
    ?>
 ALIGN='center' COLSPAN='99'>Facilities </TH></TR><TR><TD>				<!-- 3/15/11 -->				
		<DIV ID = 'side_bar_f' style="max-height: <?php 
    print $the_height;
    ?>
px; min-height: 200px; overflow-y: scroll; overflow-x: hidden;"></DIV>
		<DIV ID = 'facs_legend'></DIV>
		</TD></TD></TR></TABLE>
	</TD></TR>				<!-- 3/15/11 -->			
	<TR><TD CLASS='td_label' COLSPAN='99' ALIGN='center'>
		<A HREF="mailto:info@TicketsCAD.org?subject=Question/Comment on Tickets Dispatch System"><u>Contact us</u>&nbsp;&nbsp;&nbsp;&nbsp;<IMG SRC="mail.png" BORDER="0" STYLE="vertical-align: text-bottom"></A>
		</TD></TR></TABLE>
		
	<FORM NAME='unit_form' METHOD='get' ACTION='<?php 
    echo $_SESSION['unitsfile'];
    ?>
'>
	<INPUT TYPE='hidden' NAME='func' VALUE='responder'>
	<INPUT TYPE='hidden' NAME='view' VALUE=''>
	<INPUT TYPE='hidden' NAME='edit' VALUE=''>
	<INPUT TYPE='hidden' NAME='id' VALUE=''>
	</FORM>

	<FORM NAME='tick_form' METHOD='get' ACTION='edit.php'>				<!-- 11/27/09 -->
	<INPUT TYPE='hidden' NAME='id' VALUE=''>
	</FORM>

	<FORM NAME='sort_form' METHOD='post' ACTION='main.php'>				<!-- 6/11/10 -->
	<INPUT TYPE='hidden' NAME='order' VALUE=''>
	</FORM>

	<FORM NAME='fac_sort_form' METHOD='post' ACTION='main.php'>				<!-- 3/15/11 -->
	<INPUT TYPE='hidden' NAME='forder' VALUE=''>
	</FORM>	
	
	<FORM NAME='facy_form' METHOD='get' ACTION='<?php 
    echo $_SESSION['facilitiesfile'];
    ?>
'>		<!-- 11/27/09 -->
	<INPUT TYPE='hidden' NAME='id' VALUE=''>
	<INPUT TYPE='hidden' NAME='edit' VALUE=''>
	<INPUT TYPE='hidden' NAME='view' VALUE=''>
	</FORM>

<SCRIPT>
//================================= 7/18/10
	$('region_flags').innerHTML = "<?php 
    print $regs_string;
    ?>
";			// 5/2/10
<?php 
    function get_buttons($user_id)
    {
        //	5/3/11
        $regs_viewed = "";
        if (isset($_SESSION['viewed_groups'])) {
            $regs_viewed = explode(",", $_SESSION['viewed_groups']);
        }
        $query2 = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$user_id}' ORDER BY `group`";
        //	5/3/11
        $result2 = mysql_query($query2) or do_error($query2, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        $al_buttons = "";
        while ($row2 = stripslashes_deep(mysql_fetch_assoc($result2))) {
            //	5/3/11
            if (!empty($regs_viewed)) {
                if (in_array($row2['group'], $regs_viewed)) {
                    $al_buttons .= "<DIV style='display: block;'><INPUT TYPE='checkbox' CHECKED name='frm_group[]' VALUE='{$row2['group']}'></INPUT>" . get_groupname($row2['group']) . "&nbsp;&nbsp;</DIV>";
                } else {
                    $al_buttons .= "<DIV style='display: block;'><INPUT TYPE='checkbox' name='frm_group[]' VALUE='{$row2['group']}'></INPUT>" . get_groupname($row2['group']) . "&nbsp;&nbsp;</DIV>";
                }
            } else {
                $al_buttons .= "<DIV style='display: block;'><INPUT TYPE='checkbox' CHECKED name='frm_group[]' VALUE='{$row2['group']}'></INPUT>" . get_groupname($row2['group']) . "&nbsp;&nbsp;</DIV>";
            }
        }
        //		dump($al_buttons);
        return $al_buttons;
    }
    if (get_num_groups() && COUNT(get_allocates(4, $_SESSION['user_id'])) > 1) {
        //	6/10/11
        ?>
	side_bar_html= "";
	side_bar_html+="<TABLE><TR class='heading_2'><TH width = <?php 
        print max(320, intval($_SESSION['scr_width'] * 0.4));
        ?>
 ALIGN='center' COLSPAN='99'>Viewed <?php 
        print get_text("Regions");
        ?>
</TH></TR><TR class='even'><TD COLSPAN=99 CLASS='td_label' ><form name='region_form' METHOD='post' action='main.php'><DIV>";
	side_bar_html += "<?php 
        print get_buttons($_SESSION['user_id']);
        ?>
";
	side_bar_html+="</DIV></form></TD></TR><TR><TD>&nbsp;</TD></TR><TR><TD ALIGN='center'><INPUT TYPE='button' VALUE='Update' onClick='form_validate(document.region_form);'></TD></TR></TABLE>";
	$("region_boxes").innerHTML = side_bar_html;		

<?php 
    }
    ?>

	spe=500;
	NameOfYourTags="mi";
	swi=1;
	na=document.getElementsByName(NameOfYourTags);
	
	doBlink();
	
	function doBlink() {
		if (swi == 1) {
			sho="visible";
			swi=0;
			}
		else {
			sho="hidden";
			swi=1;
			}
	
		for(i=0;i<na.length;i++) {
			na[i].style.visibility=sho;
			}
		setTimeout("doBlink()", spe);
		}
	
	function writeConsole(content) {
		top.consoleRef=window.open('','myconsole',
			'width=800,height=250' +',menubar=0' +',toolbar=0' +',status=0' +',scrollbars=1' +',resizable=1')
	 	top.consoleRef.document.writeln('<html><head><title>Console</title></head>'
			+'<body bgcolor=white onLoad="self.focus()">' +content +'</body></html>'
			)				// end top.consoleRef.document.writeln()
	 	top.consoleRef.document.close();
		}				// end function writeConsole(content)
	

	function isNull(val) {								// checks var stuff = null;
		return val === null;
		}

	function to_session(the_name, the_value) {									// generic session variable writer - 3/8/10, 4/4/10
		function local_handleResult(req) {			// the called-back function
			}			// end function local handleResult

		var params = "f_n=" + the_name;				// 1/20/09
		params += "&f_v=" + the_value;				// 4/4/10
		sendRequest ('do_session_get.php',local_handleResult, params);			// does the work via POST
		}

	function to_server(the_unit, the_status) {							// write unit status data via ajax xfer
		var querystr = "frm_responder_id=" + the_unit;
		querystr += "&frm_status_id=" + the_status;
	
		var url = "as_up_un_status.php?" + querystr;			// 
		var payload = syncAjax(url);						// 
		if (payload.substring(0,1)=="-") {	
			alert ("<?php 
    print __LINE__;
    ?>
: msg failed ");
			return false;
			}
		else {
			parent.frames['upper'].show_msg ('Unit status update applied!')
			return true;
			}				// end if/else (payload.substring(... )
		}		// end function to_server()
	
	function to_server_fac(the_unit, the_status) {		//	3/15/11							// 3/15/11
		var querystr = "frm_responder_id=" + the_unit;
		querystr += "&frm_status_id=" + the_status;
	
		var url = "as_up_fac_status.php?" + querystr;
		var payload = syncAjax(url); 
		if (payload.substring(0,1)=="-") {	
			alert ("<?php 
    print __LINE__;
    ?>
: msg failed ");
			return false;
			}
		else {
			parent.frames['upper'].show_msg ('Facility status update applied!')
			return true;
			}				// end if/else (payload.substring(... )
		}		// end function to_server_fac()

		function syncAjax(strURL) {							// synchronous ajax function
		if (window.XMLHttpRequest) {						 
			AJAX=new XMLHttpRequest();						 
			} 
		else {																 
			AJAX=new ActiveXObject("Microsoft.XMLHTTP");
			}
		if (AJAX) {
			AJAX.open("GET", strURL, false);														 
			AJAX.send(null);							// e
			return AJAX.responseText;																				 
			} 
		else {
			alert ("<?php 
    print __LINE__;
    ?>
: failed");
			return false;
			}																						 
		}		// end function sync Ajax(strURL)

	var starting = false;
	
	function do_mail_win(the_name, the_addrs) {	
		if(starting) {return;}					// dbl-click catcher
		starting=true;
		var url = (isNull(the_name))? "do_unit_mail.php?" : "do_unit_mail.php?name=" + escape(the_name) + "&addrs=" + escape(the_addrs);	//
		newwindow_mail=window.open(url, "mail_edit",  "titlebar, location=0, resizable=1, scrollbars, height=320,width=720,status=0,toolbar=0,menubar=0,location=0, left=100,top=300,screenX=100,screenY=300");
		if (isNull(newwindow_mail)) {
			alert ("Email edit operation requires popups to be enabled -- please adjust your browser options.");
			return;
			}
		newwindow_mail.focus();
		starting = false;
		}		// end function do mail_win()

	function do_fac_mail_win(the_name, the_addrs) {			// 3/8/10
		if(starting) {return;}					// dbl-click catcher
		starting=true;
		var url = (isNull(the_name))? "do_fac_mail.php?" : "do_fac_mail.php?name=" + escape(the_name) + "&addrs=" + escape(the_addrs);	//
		newwindow_mail=window.open(url, "mail_edit",  "titlebar, location=0, resizable=1, scrollbars, height=320,width=720,status=0,toolbar=0,menubar=0,location=0, left=100,top=300,screenX=100,screenY=300");
		if (isNull(newwindow_mail)) {
			alert ("Email edit operation requires popups to be enabled -- please adjust your browser options.");
			return;
			}
		newwindow_mail.focus();
		starting = false;
		}		// end function do mail_win()

	function do_close_tick(the_id) {	//	3/15/11
		if(starting) {return;}					// dbl-click catcher
		starting=true;
		var url = "close_in.php?ticket_id=" + escape(the_id);	//
		newwindow_close = window.open(url, "close_ticket", "titlebar, location=0, resizable=1, scrollbars, height=300, width=700, status=0, toolbar=0, menubar=0, left=100,top=100,screenX=100,screenY=100");
		if (isNull(newwindow_close)) {
			alert ("Close Ticket operation requires popups to be enabled -- please adjust your browser options.");
			return;
			}
		newwindow_close.focus();
		starting = false;
		}

	function to_str(instr) {			// 0-based conversion - 2/13/09
		function ord( string ) {
		    return (string+'').charCodeAt(0);
			}

		function chr( ascii ) {
		    return String.fromCharCode(ascii);
			}
		function to_char(val) {
			return(chr(ord("A")+val));
			}

		var lop = (instr % 26);													// low-order portion, a number
		var hop = ((instr - lop)==0)? "" : to_char(((instr - lop)/26)-1) ;		// high-order portion, a string
		return hop+to_char(lop);
		}

	function sendRequest(url,callback,postData) {								// 2/14/09
		var req = createXMLHTTPObject();
		if (!req) return;
		var method = (postData) ? "POST" : "GET";
		req.open(method,url,true);
		req.setRequestHeader('User-Agent','XMLHTTP/1.0');
		if (postData)
			req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		req.onreadystatechange = function () {
			if (req.readyState != 4) return;
			if (req.status != 200 && req.status != 304) {
<?php 
    if ($istest) {
        print "\t\t\talert('HTTP error ' + req.status + '" . __LINE__ . "');\n";
    }
    ?>
				return;
				}
			callback(req);
			}
		if (req.readyState == 4) return;
		req.send(postData);
		}

	var XMLHttpFactories = [
		function () {return new XMLHttpRequest()	},
		function () {return new ActiveXObject("Msxml2.XMLHTTP")	},
		function () {return new ActiveXObject("Msxml3.XMLHTTP")	},
		function () {return new ActiveXObject("Microsoft.XMLHTTP")	}
		];

	function createXMLHTTPObject() {
		var xmlhttp = false;
		for (var i=0;i<XMLHttpFactories.length;i++) {
			try {
				xmlhttp = XMLHttpFactories[i]();
				}
			catch (e) {
				continue;
				}
			break;
			}
		return xmlhttp;
		}

	function get_chg_disp_tr() {								// 5/5/11, 6/10/11
		var chg_disp_tr ="";
		chg_disp_tr +="\t\t<FORM NAME = 'frm_interval_sel' STYLE = 'display:inline' >\n";
		chg_disp_tr +="\t\t<SELECT NAME = 'frm_interval' onChange = 'do_listtype(this.value);'>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='99' SELECTED><?php 
    print get_text("Change display");
    ?>
</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='0'><?php 
    print get_text("Current situation");
    ?>
</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='1'><?php 
    print $incidents;
    ?>
 closed today</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='2'><?php 
    print $incidents;
    ?>
 closed yesterday+</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='3'><?php 
    print $incidents;
    ?>
 closed this week</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='4'><?php 
    print $incidents;
    ?>
 closed last week</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='5'><?php 
    print $incidents;
    ?>
 closed last week+</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='6'><?php 
    print $incidents;
    ?>
 closed this month</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='7'><?php 
    print $incidents;
    ?>
 closed last month</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='8'><?php 
    print $incidents;
    ?>
 closed this year</OPTION>\n";
		chg_disp_tr +="\t\t<OPTION VALUE='9'><?php 
    print $incidents;
    ?>
 closed last year</OPTION>\n";
		chg_disp_tr +="\t\t</SELECT>\n</FORM>\n";
		chg_disp_tr +="\t\t<SPAN ID = 'btn_go' onClick='document.to_listtype.submit()' CLASS='conf_button' STYLE = 'margin-left: 10px; display:none'><U>Next</U></SPAN>";
		chg_disp_tr +="\t\t<SPAN ID = 'btn_can'  onClick='hide_btns_closed(); hide_btns_scheduled(); ' CLASS='conf_button' STYLE = 'margin-left: 10px; display:none'><U>Cancel</U></SPAN>";

		return chg_disp_tr;
		} 					// end function get chg_disp_tr()


<?php 
    $quick = !is_guest() && intval(get_variable('quick') == 1);
    // 11/27/09
    print $quick ? "var quick = true;\n" : "var quick = false;\n";
    ?>
var tr_id_fixed_part = "tr_id_";		// 3/2/10

	var colors = new Array ('odd', 'even');

	function set_initial_pri_disp() {
		}

	function set_categories() {			//	12/03/10 - checks current session values and sets checkboxes and view states for hide and show.
		}

	function set_fac_categories() {			//	12/03/10 - checks current session values and sets checkboxes and view states for hide and show.
		}


	function show_hide_rows(instr) {				// instr is '' or 'none' - 3/8/10
		for (i = 0; i< rowIds.length; i++) {
			var rowId = rowIds[i];					// row id - 3/3/10
			$(rowId).style.display = instr;			// hide each 'unavailable' row
			}
		}				// end function show_hide_rows()

	function h_handleResult(req) {					// the 'called-back' persist function - hide
		hide_Units();
		}

	var starting = false;

	function checkArray(form, arrayName)	{	//	5/3/11
		var retval = new Array();
		for(var i=0; i < form.elements.length; i++) {
			var el = form.elements[i];
			if(el.type == "checkbox" && el.name == arrayName && el.checked) {
				retval.push(el.value);
			}
		}
	return retval;
	}
	
	function checkForm(form)	{	//	5/3/11
		var errmsg="";
		var itemsChecked = checkArray(form, "frm_group[]");
		if(itemsChecked.length > 0) {
			var params = "f_n=viewed_groups&v_n=" +itemsChecked+ "&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
			var url = "persist3.php";	//	3/15/11	
			sendRequest (url, fvg_handleResult, params);				
//			form.submit();
		} else {
			errmsg+= "\tYou cannot Hide all the regions\n";
			if (errmsg!="") {
				alert ("Please correct the following and re-submit:\n\n" + errmsg);
				return false;
			}
		}
	}
	
	function fvg_handleResult(req) {	// 5/4/11	The persist callback function for viewed groups.
		document.region_form.submit();
		}
		
	function form_validate(theForm) {	//	5/3/11
//		alert("Validating");
		checkForm(theForm);
		}				// end function validate(theForm)	

	function do_mail_fac_win(id) {			// Facility email 9/22/09
		if(starting) {return;}					
		starting=true;	
		var url = "do_fac_mail.php?fac_id=" + id;	
		newwindow_in=window.open (url, 'Email_Window',  'titlebar, resizable=1, scrollbars, height=300,width=600,status=0,toolbar=0,menubar=0,location=0, left=50,top=150,screenX=100,screenY=300');
		if (isNull(newwindow_in)) {
			alert ("This requires popups to be enabled. Please adjust your browser options.");
			return;
			}
		newwindow_in.focus();
		starting = false;
		}

	function s_handleResult(req) {					// the 'called-back' persist function - show
		show_Units();
		}

	function do_sel_update (in_unit, in_val) {							// 12/17/09
		to_server(in_unit, in_val);
		}

	function do_sel_update_fac (in_unit, in_val) {							// 3/15/11
		to_server_fac(in_unit, in_val);
		}

	function do_sidebar_unit (instr, id, sym, myclass, tip_str) {		// sidebar_string, sidebar_index, row_class, icon_info, mouseover_str - 1/7/09
		var tr_id = tr_id_fixed_part + id;
		if (isNull(tip_str)) {
			side_bar_html += "<TR ID = '" + tr_id + "' CLASS='" + colors[(id)%2] +"'><TD CLASS='" + myclass + "' onClick = myclick(" + id + "); ALIGN = 'left'>" + (sym) + "</TD>"+ instr +"</TR>\n";		// 2/6/10 moved onclick to TD
			}
		else {
			side_bar_html += "<TR ID =  '" + tr_id + "' onMouseover=\"Tip('" + tip_str + "');\" onmouseout=\"UnTip();\" CLASS='" + colors[(id+1)%2] +"'><TD CLASS='" + myclass + "' onClick = myclick(" + id + "); ALIGN = 'left'>" + (sym) + "</TD>"+ instr +"</TR>\n";		// 1/3/10 added tip param		
			}
		}		// end function do sidebar_unit ()

<?php 
    $js_func = $can_edit ? "myclick_ed_tick" : "open_tick_window";
    // 4/28/11
    ?>
	
	function open_tick_window (id) {				// 5/2/10
		var url = "single.php?ticket_id="+ id;
		var tickWindow = window.open(url, 'mailWindow', 'resizable=1, scrollbars, height=600, width=650, left=100,top=100,screenX=100,screenY=100');
		tickWindow.focus();
		}	

	function do_patient(id) {			// patient edit 6/23/11
		if(starting) {return;}					
		starting=true;	
		var url = "patient_w.php?action=list&ticket_id=" + id;	
		newwindow=window.open (url, 'Patient_Window', 'titlebar, resizable=1, scrollbars, height=300,width=550,status=0,toolbar=0,menubar=0,location=0, left=50,top=150,screenX=50,screenY=150');
		if (isNull(newwindow)) {
			alert ("This requires popups to be enabled. Please adjust your browser options.");
			return;
			}
		newwindow.focus();
		starting = false;
		}

	function myclick(id) {					// Responds to sidebar click, then triggers listener above -  note [i]
//		GEvent.trigger(gmarkers[id], "click");
		location.href = "#top";
		}

	function do_sidebar (instr, id, sym, myclass, tip_str) {		// sidebar_string, sidebar_index, row_class, icon_info, mouseover_str - 1/7/09
//		alert(<?php 
    echo __LINE__;
    ?>
);
		var tr_id = tr_id_fixed_part + id;
		side_bar_html += "<TR onClick = 'onclick_do_unit(" + id + ");' ID =  '" + tr_id + "' onMouseover=\"Tip('" + tip_str + "');\" onmouseout=\"UnTip();\" CLASS='" + colors[id%2] +"'>";
		side_bar_html += "<TD WIDTH='5%' CLASS='" + myclass + "' ALIGN = 'left'>" + (sym) + "</TD>"+ instr +"</TR>\n";		// 1/3/10 added tip param		
		}		// end function do sidebar ()

	function do_sidebar_t_ed (instr, line_no, rcd_id, letter, tip_str) {		// ticket edit, tip str added 1/3/10
		side_bar_html += "<TR onMouseover=\"Tip('" + tip_str.replace("'", "") + "');\" onmouseout=\"UnTip();\" CLASS='" + colors[(line_no+1)%2] +"'>";		
		side_bar_html += "<TD WIDTH='5%'>" + letter + "</TD>" + instr +"</TR>\n";		// 2/13/09, 10/29/09 removed period
		}
	function do_sidebar_u_iw (instr, id, sym, myclass) {						// constructs unit incident sidebar row - 1/7/09
		var tr_id = tr_id_fixed_part + id;
		side_bar_html += "<TR ID = '" + tr_id + "' CLASS='" + colors[id%2] +"' onClick = myclick(" + id + ");><TD CLASS='" + myclass + "'>" + (sym) + "</TD>"+ instr +"</TR>\n";		// 10/30/09 removed period
		}		// end function do sidebar ()

		
	function myclick_ed_tick(id) {				// Responds to sidebar click - edit ticket data

<?php 
    $the_action = is_guest() ? "main.php" : "edit.php";
    2 / 27 / 10;
    ?>
	
		document.tick_form.id.value=id;			// 11/27/09
		document.tick_form.action='<?php 
    print $the_action;
    ?>
';			// 11/27/09
		document.tick_form.submit();
		}
		
	function do_sidebar_u_ed (sidebar, line_no, on_click, letter) {					// unit edit 
		var tr_id = tr_id_fixed_part + line_no;
		side_bar_html += "<TR ID = '" + tr_id + "'  CLASS='" + colors[(line_no+1)%2] +"'>";
		side_bar_html += "<TD onClick = '" + on_click+ "' CLASS='td_data'>" + letter + "</TD>" + sidebar +"</TR>\n";		// 2/13/09, 10/29/09 removed period
		}

	function onclick_do_unit(id) {				// Responds to sidebar click - view/edit responder data
		document.unit_form.id.value=id;			// 11/27/09
<?php 
    $the_func = $can_edit ? "edit" : "view";
    // 4/30/11
    ?>
		document.unit_form.<?php 
    print $the_func;
    ?>
.value="true";
		document.unit_form.submit();
		}

	function do_sidebar_fac_ed (fac_instr, fac_id, fac_sym, myclass, line_no) {					// constructs facilities sidebar row 9/22/09
		side_bar_html += "<TR CLASS='" + colors[line_no%2] +"'>";
		side_bar_html += "<TD  onClick = fac_click_ed(" + fac_id + ");>" + (fac_sym) + "</TD>";
		side_bar_html += fac_instr +"</TR>\n";		// 10/30/09 removed period
		location.href = "#top";
		}		// end function do sidebar_fac_iw ()

	function do_sidebar_fac_iw (fac_instr, fac_id, fac_sym, myclass) {					// constructs facilities sidebar row 9/22/09
		side_bar_html += "<TR CLASS='" + colors[fac_id%2] +"' WIDTH = '100%';>"
		side_bar_html += "<TD CLASS='" + myclass + "'>" + (fac_sym) + "</TD>";
		side_bar_html += fac_instr +"</TR>\n";		// 10/30/09 removed period
		location.href = "#top";
		}		// end function do sidebar_fac ()

	function fac_click_iw(fac_id) {						// Responds to facilities sidebar click, triggers listener above 9/22/09
		GEvent.trigger(fmarkers[fac_id], "click");
		location.href = "#top";
		}

	function fac_click_ed(id) {							// Responds to facility sidebar click - edit data
		document.facy_form.id.value=id;					// 11/27/09
		if (quick) {
			document.facy_form.edit.value="true";
			}
		else {
			document.facy_form.view.value="true";
			}
		document.facy_form.submit();
		}

	function fac_click_vw(id) {							// Responds to facility sidebar click - view data
		document.facy_form.id.value=id;					// 11/27/09
		document.facy_form.view.value="true";
		document.facy_form.submit();
		}

	var points = false;

function do_add_note (id) {				// 8/12/09
	var url = "add_note.php?ticket_id="+ id;
	var noteWindow = window.open(url, 'mailWindow', 'resizable=1, scrollbars, height=240, width=600, left=100,top=100,screenX=100,screenY=100');
	noteWindow.focus();
	}
	
function do_sort_sub(sort_by){				// 6/11/10
	document.sort_form.order.value = sort_by;
	document.sort_form.submit();
	}
	
function do_fac_sort_sub(sort_by){				// 3/15/11
	document.fac_sort_form.forder.value = sort_by;
	document.fac_sort_form.submit();
	}

function do_sched_jobs(choice) {		// 11/29/10 - added Scheduled tickets to menu. 12/02/10 Added persistance for the list view
	var params = "f_n=list_type&v_n=" + choice + "&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";					// flag 1, value h
	var url = "persist.php";
	sendRequest (url, cs_handleResult, params);	// ($to_str, $text, $ticket_id)
	document.to_listtype.func.value=choice;
	}				// end function do_listtype()

function do_curr_jobs(choice) {		// 11/29/10 - added Scheduled tickets to menu. 12/02/10 Added persistance for the list view
	var params = "f_n=list_type&v_n=" + choice + "&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";					// flag 1, value h
	var url = "persist.php";
	sendRequest (url, cs_handleResult, params);	// ($to_str, $text, $ticket_id)
	document.to_listtype.func.value=choice;
	}				// end function do_listtype()

function do_listtype(choice) {		// 11/29/10 - added Scheduled tickets to menu. 12/02/10 Added persistance for the list view
	var params = "f_n=list_type&v_n=" + choice + "&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";					// flag 1, value h
	var url = "persist.php";
	sendRequest (url, l_handleResult, params);	// ($to_str, $text, $ticket_id)
	document.to_listtype.func.value=choice;
	show_btns_closed()
	}				// end function do_listtype()
	
function l_handleResult(req) {					// the 'called-back' persist function - nill content for the tickets list type persistance
	}

function cs_handleResult(req) {					// the 'called-back' function for show current or scheduled
	document.to_listtype.submit();	
	}	
 
	var side_bar_html_hdr = "<TABLE border=0 CLASS='sidebar' WIDTH = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.38));
    ?>
 >\n";<?php 
    if ($any_open_tickets) {
        // 1/18/11
        ?>
		
	side_bar_html_hdr += "<TR class='even' STYLE = 'height:20px; width: 100%;' VALIGN='baseline'><TD colspan=99 align='center'<I>Click/Mouse-over for information</I> ";	
	
<?php 
    }
    // end if ($any_open_tickets)
    $query_sched = "SELECT * FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE `status`='{$GLOBALS['STATUS_SCHEDULED']}'";
    //	11/29/10
    $result_sched = mysql_query($query_sched) or do_error($query_sched, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    //	11/29/10
    $num_sched = mysql_num_rows($result_sched);
    //	11/29/10
    if ($num_sched != 0 && $func != 10) {
        //	11/29/10
        $scheduled_link = $num_sched >= 2 ? "&nbsp;&nbsp;&nbsp;&raquo;&nbsp;<U>Scheduled: ({$num_sched}) </U>  " : "&nbsp;&nbsp;&nbsp;&nbsp;Scheduled: ({$num_sched})";
        $order_by = !empty($get_sortby) ? $get_sortby : $_SESSION['sortorder'];
        // use default sort order?
        ?>
		side_bar_html_hdr +="\t\t<SPAN class='scheduled' onClick='do_sched_jobs(10);'><?php 
        print $scheduled_link;
        ?>
</SPAN>\n";
<?php 
    }
    //	11/29/10
    if ($num_sched != 0 && $func == 10) {
        //	11/29/10
        ?>
		side_bar_html_hdr +="\t\t<SPAN class='scheduled' onClick='do_curr_jobs(0);'>&raquo;&nbsp;View current situation</SPAN>\n";

<?php 
    }
    //	11/29/10
    ?>
	side_bar_html_hdr += get_chg_disp_tr();		// adds the "Chg display' row at top of tickets list - 5/6/11
	side_bar_html_hdr +="<br /><br /></TD></TR>\n";	
	side_bar_html_hdr += "<TR class='odd'><TD align='left' width='5%'><B>ID</B></TD><TD align='left' width='15%'><B><?php 
    print $incident;
    ?>
</B></TD><TD align='left' width='15%'><B>Address</B></TD><TD align='left' width='15%'><B><?php 
    print $nature;
    ?>
</B></TD><TD align='left' width='15%'><B>Comments</B></TD><TD align='left' width='15%'><B>Description</B></TD><TD align='left' width='2%'><B>P</B></TD><TD align='left' width='2%'><B>A</B></TD><TD align='left' width='2%'><B>U</B></TD><TD align='center' width='14%'><B>As of</B></TD></TR>";
	side_bar_html_hdr += "</TABLE>";
		
	var rowIds = [];		// 3/8/10
	var which;
	var i = 0;			// sidebar/icon index
	
	var side_bar_html = "<TABLE border=0 CLASS='sidebar' WIDTH = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.38));
    ?>
 >\n";	

<?php 
    $order_by = !empty($get_sortby) ? $get_sortby : $_SESSION['sortorder'];
    // use default sort order?
    //fix limits according to setting "ticket_per_page"
    $limit = "";
    if ($_SESSION['ticket_per_page'] && check_for_rows("SELECT id FROM `{$GLOBALS['mysql_prefix']}ticket`") > $_SESSION['ticket_per_page']) {
        if ($_GET['offset']) {
            $limit = "LIMIT {$_GET['offset']},{$_SESSION['ticket_per_page']}";
        } else {
            $limit = "LIMIT 0,{$_SESSION['ticket_per_page']}";
        }
    }
    $restrict_ticket = "";
    //	$restrict_ticket = (get_variable('restrict_user_tickets') && !(is_administrator()))? " AND owner=$_SESSION[user_id]" : "";
    $time_back = mysql_format_date(time() - get_variable('delta_mins') * 60 - $cwi * 3600);
    if (isset($_SESSION['viewed_groups'])) {
        //	5/4/11
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    }
    if (!isset($curr_viewed)) {
        //	5/4/11
        $x = 0;
        $where2 = "AND (";
        foreach ($al_groups as $grp) {
            $where3 = count($al_groups) > $x + 1 ? " OR " : ")";
            $where2 .= "`{$GLOBALS['mysql_prefix']}allocates`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    } else {
        $x = 0;
        $where2 = "AND (";
        foreach ($curr_viewed as $grp) {
            $where3 = count($curr_viewed) > $x + 1 ? " OR " : ")";
            $where2 .= "`{$GLOBALS['mysql_prefix']}allocates`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    }
    switch ($func) {
        case 0:
            $where = "WHERE (`{$GLOBALS['mysql_prefix']}ticket`.`status`='{$GLOBALS['STATUS_OPEN']}' OR (`{$GLOBALS['mysql_prefix']}ticket`.`status`='{$GLOBALS['STATUS_SCHEDULED']}' AND `{$GLOBALS['mysql_prefix']}ticket`.`booked_date` <= (NOW() + INTERVAL 2 DAY)) OR \n\t\t\t\t(`{$GLOBALS['mysql_prefix']}ticket`.`status`='{$GLOBALS['STATUS_CLOSED']}'  AND `{$GLOBALS['mysql_prefix']}ticket`.`problemend` >= '{$time_back}')){$where2}";
            //	11/29/10, 4/18/11, 4/18/11
            break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
            $the_start = get_start($func);
            // mysql timestamp format
            $the_end = get_end($func);
            $where = " WHERE (`{$GLOBALS['mysql_prefix']}ticket`.`status`='{$GLOBALS['STATUS_CLOSED']}' AND `{$GLOBALS['mysql_prefix']}ticket`.`problemend` BETWEEN '{$the_start}' AND '{$the_end}') {$where2} ";
            //	4/18/11, 4/18/11
            break;
        case 10:
            $where = "WHERE (`{$GLOBALS['mysql_prefix']}ticket`.`status`='{$GLOBALS['STATUS_SCHEDULED']}' AND `{$GLOBALS['mysql_prefix']}ticket`.`booked_date` >= (NOW() + INTERVAL 2 DAY)) {$where2}";
            //	11/29/10, 4/18/11, 4/18/11
            break;
        default:
            print "error - error - error - error " . __LINE__;
    }
    // end switch($func)
    if ($sort_by_field && $sort_value) {
        //sort by field?, updated 4/18/11 to support regional operation
        $query = "SELECT *,UNIX_TIMESTAMP(problemstart) AS problemstart,UNIX_TIMESTAMP(problemend) AS problemend,\n\t\t\tUNIX_TIMESTAMP(date) AS date,UNIX_TIMESTAMP(updated) AS updated, \n\t\t\tin_types.type AS `type`, in_types.id AS `t_id` \n\t\t\tFROM `{$GLOBALS['mysql_prefix']}allocates`\n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` ON `{$GLOBALS['mysql_prefix']}allocates`.`resource_id`=`{$GLOBALS['mysql_prefix']}ticket`.`id` \t\t\t\n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}in_types` ON `{$GLOBALS['mysql_prefix']}ticket`.`in_types_id`=`{$GLOBALS['mysql_prefix']}in_types`.`in_types.id` \n\t\t\tWHERE {$sort_by_field}='{$sort_value}' {$restrict_ticket} AND `{$GLOBALS['mysql_prefix']}allocates`.`type` = 1 ORDER BY {$order_by}";
    } else {
        // 2/2/09, 8/12/09, 1/30/11, 6/10/11
        $query = "SELECT *,UNIX_TIMESTAMP(problemstart) AS problemstart,\n\t\t\tUNIX_TIMESTAMP(problemend) AS problemend,\n\t\t\tUNIX_TIMESTAMP(booked_date) AS booked_date,\t\n\t\t\tUNIX_TIMESTAMP(date) AS date, \n\t\t\t(`{$GLOBALS['mysql_prefix']}ticket`.`street`) AS ticket_street, \n\t\t\t(`{$GLOBALS['mysql_prefix']}ticket`.`state`) AS ticket_city, \n\t\t\t(`{$GLOBALS['mysql_prefix']}ticket`.`city`) AS ticket_state,\n\t\t\tUNIX_TIMESTAMP(`{$GLOBALS['mysql_prefix']}ticket`.updated) AS updated,\n\t\t\t`{$GLOBALS['mysql_prefix']}ticket`.`id` AS `tick_id`,\n\t\t\t`{$GLOBALS['mysql_prefix']}in_types`.type AS `type`, \n\t\t\t`{$GLOBALS['mysql_prefix']}in_types`.`id` AS `t_id`,\n\t\t\t`{$GLOBALS['mysql_prefix']}ticket`.`description` AS `tick_descr`, \n\t\t\t`{$GLOBALS['mysql_prefix']}ticket`.lat AS `lat`,\n\t\t\t`{$GLOBALS['mysql_prefix']}ticket`.lng AS `lng`, \n\t\t\t`{$GLOBALS['mysql_prefix']}facilities`.lat AS `fac_lat`,\n\t\t\t`{$GLOBALS['mysql_prefix']}facilities`.lng AS `fac_lng`, \n\t\t\t`{$GLOBALS['mysql_prefix']}facilities`.`name` AS `fac_name`, \n\t\t\t(SELECT  COUNT(*) as numfound FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\t\t\tWHERE `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id` = `{$GLOBALS['mysql_prefix']}ticket`.`id`  \n\t\t\t\tAND `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' ) \n\t\t\t\tAS `units_assigned`\t\t\t\n\t\t\tFROM `{$GLOBALS['mysql_prefix']}ticket`\t\t\t\n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` \n\t\t\t\tON `{$GLOBALS['mysql_prefix']}ticket`.id=`{$GLOBALS['mysql_prefix']}allocates`.`resource_id`\t\t\t\n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}in_types` \n\t\t\t\tON `{$GLOBALS['mysql_prefix']}ticket`.in_types_id=`{$GLOBALS['mysql_prefix']}in_types`.`id` \n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}facilities` \n\t\t\t\tON `{$GLOBALS['mysql_prefix']}ticket`.rec_facility=`{$GLOBALS['mysql_prefix']}facilities`.`id` \n\t\t\t{$where} {$restrict_ticket} \n\t\t\t GROUP BY tick_id ORDER BY `status` DESC, `booked_date` ASC, `severity` DESC,`{$GLOBALS['mysql_prefix']}ticket`.`id` ASC\n\t\t\tLIMIT 1000 OFFSET {$my_offset}";
        // 2/2/09, 10/28/09, 2/21/10
        //			print $query;
    }
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $the_offset = isset($_GET['frm_offset']) ? (int) $_GET['frm_offset'] : 0;
    $sb_indx = 0;
    // note zero base!
    $acts_ary = $pats_ary = array();
    // 6/2/10
    $query = "SELECT `ticket_id`, COUNT(*) AS `the_count` FROM `{$GLOBALS['mysql_prefix']}action` GROUP BY `ticket_id`";
    $result_temp = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row = stripslashes_deep(mysql_fetch_assoc($result_temp))) {
        $acts_ary[$row['ticket_id']] = $row['the_count'];
    }
    $query = "SELECT `ticket_id`, COUNT(*) AS `the_count` FROM `{$GLOBALS['mysql_prefix']}patient` GROUP BY `ticket_id`";
    $result_temp = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row = stripslashes_deep(mysql_fetch_assoc($result_temp))) {
        $pats_ary[$row['ticket_id']] = $row['the_count'];
    }
    $line_limit = 25;
    // 5/5/11
    $col_width = (int) floor($_SESSION['scr_width'] * 0.013);
    $use_quick = (int) $func == 0 || (int) $func == 10 ? FALSE : TRUE;
    //	11/29/10
    if ($use_quick) {
        $js_func = "open_tick_window";
    } elseif ($quick && !is_guest()) {
        $js_func = "myclick_ed_tick";
    } else {
        $js_func = "myclick_ed_tick";
    }
    // ===========================  begin major while() for tickets==========
    $temp = (string) round(microtime(true) - $time, 3);
    //	snap (__LINE__, $temp );
    ?>
		var incs_array = [];
		var incs_groups = [];		
		var i = 0;
<?php 
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // 7/7/10
        $tick_gps = get_allocates(1, $row['tick_id']);
        //	5/4/11
        $grp_names = "Groups Assigned: ";
        //	5/4/11
        $y = 0;
        //	5/4/11
        foreach ($tick_gps as $value) {
            //	5/4/11
            $counter = count($tick_gps) > $y + 1 ? ", " : "";
            $grp_names .= get_groupname($value);
            $grp_names .= $counter;
            $y++;
        }
        $onclick_str = "onClick = '{$js_func}({$row['tick_id']});'";
        // onClick = to_wherever(999);  -6/23/11
        $by_severity[$row['severity']]++;
        // 5/2/10
        if ($func > 0) {
            // closed? - 5/16/10
            $onclick = " open_tick_window({$row['tick_id']})";
        } else {
            $onclick = $quick ? " myclick_ed_tick({$row['tick_id']}) " : "myclick({$sb_indx})";
            // 1/2/10
        }
        if ($do_blink && $row['units_assigned'] == 0 && $row['status'] == $GLOBALS['STATUS_OPEN']) {
            // 4/11/10
            $blinkst = "<blink>";
            $blinkend = "</blink>";
        } else {
            $blinkst = $blinkend = "";
        }
        $tip = str_replace("'", "`", $grp_names . " / " . $row['contact'] . "/" . $row['ticket_street'] . "/" . $row['ticket_city'] . "/" . $row['ticket_state'] . "/" . $row['phone'] . "/" . $row['scope']);
        // tooltip string - 1/3/10, 4/18/11
        $sp = $row['status'] == $GLOBALS['STATUS_SCHEDULED'] && $func != 10 ? "*" : "";
        print "\t\tvar scheduled = '{$sp}';\n";
        ?>
		var sym = (<?php 
        print addslashes($sb_indx);
        ?>
+1).toString();						// for sidebar
		var sym2= scheduled + (<?php 
        print $sb_indx;
        ?>
+1).toString();			// for icon
	
<?php 
        $the_id = $row['tick_id'];
        // 11/27/09
        if ($row['tick_descr'] == '') {
            $row['tick_descr'] = '[no description]';
        }
        // 8/12/09
        if ($row['comments'] == '') {
            $row['comments'] = '[no comments]';
        }
        // 8/12/09
        if (get_variable('abbreviate_description')) {
            //do abbreviations on description, affected if neccesary
            if (strlen($row['tick_descr']) > get_variable('abbreviate_description')) {
                $row['tick_descr'] = substr($row['tick_descr'], 0, get_variable('abbreviate_description')) . '...';
            }
        }
        if (get_variable('abbreviate_affected')) {
            if (strlen($row['affected']) > get_variable('abbreviate_affected')) {
                $row['affected'] = substr($row['affected'], 0, get_variable('abbreviate_affected')) . '...';
            }
        }
        switch ($row['severity']) {
            //color tickets by severity
            case $GLOBALS['SEVERITY_MEDIUM']:
                $severityclass = 'severity_medium';
                break;
            case $GLOBALS['SEVERITY_HIGH']:
                $severityclass = 'severity_high';
                break;
            default:
                $severityclass = 'severity_normal';
                break;
        }
        $A = array_key_exists($the_id, $acts_ary) ? $acts_ary[$the_id] : 0;
        // 6/2/10
        $P = array_key_exists($the_id, $pats_ary) ? $pats_ary[$the_id] : 0;
        if ($row['status'] == $GLOBALS['STATUS_CLOSED']) {
            $strike = "<strike>";
            $strikend = "</strike>";
        } else {
            $strike = $strikend = "";
        }
        $address_street = $row['ticket_street'] . " " . $row['ticket_city'];
        $address_street = $address_street == " " ? "[No Address]" : $address_street;
        $sidebar_line = "<TD ALIGN='left' WIDTH='15%' CLASS='{$severityclass}' {$onclick_str}><NOBR>{$strike}" . $sp . shorten($row['scope'], $col_width) . " {$strikend}</NOBR></TD>";
        //10/27/09
        $sidebar_line .= "<TD ALIGN='left' WIDTH='15%' CLASS='{$severityclass}' {$onclick_str}><NOBR>{$strike}" . shorten($address_street, $col_width) . " {$strikend}</NOBR>&nbsp;</TD>";
        // 8/2/10
        $sidebar_line .= "<TD ALIGN='left' WIDTH='15%' CLASS='{$severityclass}' {$onclick_str}><NOBR>{$strike}" . shorten($row['type'], $col_width) . " {$strikend}</NOBR></TD>";
        $sidebar_line .= "<TD ALIGN='left' WIDTH='15%' CLASS='{$severityclass}' {$onclick_str}><NOBR>{$strike}" . shorten(remove_nls($row['comments']), $col_width) . " {$strikend}</NOBR></TD>";
        $sidebar_line .= "<TD ALIGN='left' WIDTH='15%' CLASS='{$severityclass}' {$onclick_str}><NOBR>{$strike}" . shorten(remove_nls($row['tick_descr']), $col_width) . " {$strikend}</NOBR></TD>";
        if ($P == 0) {
            $sidebar_line .= "<TD ALIGN='left' WIDTH='2%'>&nbsp;</TD>";
        } else {
            $pat_onclick_str = "onClick = 'do_patient({$row['tick_id']});'";
            $sidebar_line .= "<TD ALIGN='left' WIDTH='2%' CLASS='disp_stat' {$pat_onclick_str}><NOBR>&nbsp;<B>{$P}</B>&nbsp;</TD>";
        }
        $sidebar_line .= "<TD ALIGN='left' WIDTH='2%' {$onclick_str}>{$A}</TD>";
        $sidebar_line .= "<TD ALIGN='left' WIDTH='2%' {$onclick_str}>{$blinkst}{$row['units_assigned']}{$blinkend}</TD>";
        $_date = $row['status'] == $GLOBALS['STATUS_SCHEDULED'] ? $row['booked_date'] : $row['updated'];
        // 1/30/11
        $sidebar_line .= "<TD ALIGN='left' WIDTH='14%' {$onclick_str}><NOBR> " . format_sb_date($_date) . "</NOBR></TD>";
        $street = empty($row['ticket_street']) ? "" : $row['ticket_street'] . "<BR/>" . $row['ticket_city'] . " " . $row['ticket_state'];
        $todisp = is_guest() ? "" : "&nbsp;<A HREF='routes.php?ticket_id={$the_id}'><U>Dispatch</U></A>";
        // 8/2/08
        $rand = $istest ? "&rand=" . chr(rand(65, 90)) : "";
        // 10/21/08
        ?>
		var the_class = "emph";
<?php 
        if ($quick || (int) $func > 0) {
            // 5/18/10
            print "\t\t\tdo_sidebar_t_ed (\"{$sidebar_line}\", ({$the_offset} + {$sb_indx}), {$row['tick_id']}, sym, \"{$tip}\");\n";
        } else {
            print "\t\t\tdo_sidebar_t_ed (\"{$sidebar_line}\", ({$the_offset} + {$sb_indx}), {$row['tick_id']}, sym, \"{$tip}\");\n";
        }
        $sb_indx++;
    }
    // end tickets while ($row = ...)
    //		if ($any_closed_tickets) {				// 1/28/11
    //		}		// end if ($any_closed_tickets)
    if ($sb_indx == 0) {
        $txt_str = $func > 0 ? "closed tickets this period!" : "current tickets!";
        print "\n\t\tside_bar_html += \"<TR CLASS='even'><TD COLSPAN='99' ALIGN='center'><I><B>No {$txt_str}</B></I></TD></TR>\";";
        print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TD COLSPAN='99' ><BR /><BR /></TD></TR>\";";
    }
    $limit = 1000;
    $link_str = "";
    $query = "SELECT `id` FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE `status` = '{$GLOBALS['STATUS_CLOSED']}'";
    $result_cl = mysql_query($query) or do_error($query, 'mysql_query', mysql_error(), basename(__FILE__), __LINE__);
    if (mysql_affected_rows() > $limit) {
        $sep = ", ";
        $rcds = mysql_affected_rows();
        for ($j = 0; $j < ceil($rcds / $limit); $j++) {
            $sep = $j == ceil($rcds / $limit) - 1 ? "" : ", ";
            $temp = (string) ($j * $limit);
            $link_str .= "<SPAN onClick = 'document.to_closed.frm_offset.value={$temp}; document.to_closed.submit();'><U>" . ($j + 1) . "K</U></SPAN>{$sep}";
        }
    }
    //		$sev_string = "Severities: normal ({$by_severity[$GLOBALS['SEVERITY_NORMAL']]}), Medium ({$by_severity[$GLOBALS['SEVERITY_MEDIUM']]}), High ({$by_severity[$GLOBALS['SEVERITY_HIGH']]})";
    $sev_string = "Severities: <SPAN CLASS='severity_normal'>Normal ({$by_severity[$GLOBALS['SEVERITY_NORMAL']]})</SPAN>,&nbsp;&nbsp;<SPAN CLASS='severity_medium'>Medium ({$by_severity[$GLOBALS['SEVERITY_MEDIUM']]})</SPAN>,&nbsp;&nbsp;<SPAN CLASS='severity_high'>High ({$by_severity[$GLOBALS['SEVERITY_HIGH']]})</SPAN>";
    unset($acts_ary, $pats_ary, $result_temp, $result_cl);
    ?>
			

	side_bar_html +="</TABLE>\n";
	$("side_bar_header").innerHTML = side_bar_html_hdr;				// side_bar_html to incidents div 	
	$("side_bar").innerHTML = side_bar_html;				// side_bar_html to incidents div 
	$('sev_counts').innerHTML = "<?php 
    print $sev_string;
    ?>
";			// 5/2/10
	

// ==========================================      RESPONDER start    ================================================

	side_bar_html ="<TABLE border=0 CLASS='sidebar' WIDTH = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.38));
    ?>
 >\n";		// initialize units sidebar string
	side_bar_html += "<TR CLASS = 'spacer'><TD CLASS='spacer' COLSPAN=99>&nbsp;</TD></TR>";	//	3/15/11
	points = false;
	i++;
	var j=0;

<?php 
    $u_types = array();
    // 1/1/09
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}unit_types` ORDER BY `id`";
    // types in use
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        $u_types[$row['id']] = array($row['name'], $row['icon']);
        // name, index, aprs - 1/5/09, 1/21/09
    }
    unset($result);
    $assigns = array();
    // 8/3/08
    $tickets = array();
    // ticket id's
    $query = "SELECT `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`, \n\t\t`{$GLOBALS['mysql_prefix']}assigns`.`responder_id`, \n\t\t`{$GLOBALS['mysql_prefix']}ticket`.`scope` AS `ticket` \n\t\tFROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` ON `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`=`{$GLOBALS['mysql_prefix']}ticket`.`id`";
    $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_as = stripslashes_deep(mysql_fetch_array($result_as))) {
        $assigns[$row_as['responder_id']] = $row_as['ticket'];
        $tickets[$row_as['responder_id']] = $row_as['ticket_id'];
    }
    unset($result_as);
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    $status_vals = array();
    // build array of $status_vals
    $status_vals[''] = $status_vals['0'] = "TBD";
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}un_status` ORDER BY `id`";
    $result_st = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_st = stripslashes_deep(mysql_fetch_array($result_st))) {
        $temp = $row_st['id'];
        $status_vals[$temp] = $row_st['status_val'];
        $status_hide[$temp] = $row_st['hide'];
    }
    unset($result_st);
    $assigns_ary = array();
    // construct array of responder_id's on active calls
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` WHERE ((`clear` IS  NULL) OR (DATE_FORMAT(`clear`,'%y') = '00')) ";
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        $assigns_ary[$row['responder_id']] = TRUE;
    }
    $order_values = array(1 => "`nr_assigned` DESC,  `handle` ASC, `r`.`name` ASC", 2 => "`type_descr` ASC, `handle` ASC", 3 => "`stat_descr` ASC, `handle` ASC", 4 => "`handle` ASC");
    // 6/24/10
    if (!empty($_POST)) {
        $_SESSION['unit_flag_2'] = $_POST['order'];
    } elseif (empty($_SESSION['unit_flag_2'])) {
        $_SESSION['unit_flag_2'] = 1;
    }
    $order_str = $order_values[$_SESSION['unit_flag_2']];
    // 6/11/10
    // 6/25/10
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}';";
    // 4/18/11
    $result = mysql_query($query);
    // 4/18/11
    $al_groups = array();
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        // 4/18/11
        $al_groups[] = $row['group'];
    }
    if (isset($_SESSION['viewed_groups'])) {
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    }
    if (!isset($curr_viewed)) {
        $x = 0;
        //	4/18/11
        $where2 = "WHERE (";
        //	4/18/11
        foreach ($al_groups as $grp) {
            //	4/18/11
            $where3 = count($al_groups) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    } else {
        $x = 0;
        //	4/18/11
        $where2 = "WHERE (";
        //	4/18/11
        foreach ($curr_viewed as $grp) {
            //	4/18/11
            $where3 = count($curr_viewed) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    }
    $where2 .= "AND `a`.`type` = 2";
    $query = "SELECT *, UNIX_TIMESTAMP(updated) AS `updated`, `t`.`id` AS `type_id`, `r`.`id` AS `unit_id`, `r`.`name` AS `name`,\n\t\t`s`.`description` AS `stat_descr`,  `r`.`description` AS `unit_descr`, `t`.`description` AS `type_descr`,\n\t\t(SELECT  COUNT(*) as numfound FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\tWHERE `{$GLOBALS['mysql_prefix']}assigns`.`responder_id` = unit_id \tAND ( `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' )) AS `nr_assigned` \n\t\tFROM `{$GLOBALS['mysql_prefix']}responder` `r` \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON ( `r`.`id` = a.resource_id )\t\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}unit_types` `t` ON ( `r`.`type` = t.id )\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}un_status` `s` ON ( `r`.`un_status_id` = s.id ) \t\t\n\t\t{$where2}  GROUP BY unit_id ORDER BY {$order_str}";
    // 2/1/10, 3/8/10, 6/11/10
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $units_ct = mysql_affected_rows();
    // 1/4/10
    if ($units_ct == 0) {
        print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TH></TH><TH ALIGN='center' COLSPAN=99><I><B>No units!</I></B></TH></TR>\"\n";
    } else {
        $checked = array("", "", "", "");
        $checked[$_SESSION['unit_flag_2']] = " CHECKED";
        ?>
	
	side_bar_html += "<TR CLASS = 'even' VALIGN='baseline'><TD COLSPAN=99 ALIGN='center' STYLE = 'height:20px;'>";
	side_bar_html += "<I>Sort:&nbsp;&nbsp;&nbsp;&nbsp;";
	side_bar_html += "Unit &raquo; 	<input type = radio name = 'frm_order' value = 1 <?php 
        print $checked[1];
        ?>
 onClick = 'do_sort_sub(this.value);' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	side_bar_html += "Type &raquo; 	<input type = radio name = 'frm_order' value = 2 <?php 
        print $checked[2];
        ?>
 onClick = 'do_sort_sub(this.value);' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	side_bar_html += "Status &raquo; <input type = radio name = 'frm_order' value = 3 <?php 
        print $checked[3];
        ?>
 onClick = 'do_sort_sub(this.value);' />";
	side_bar_html += "</I></TD></TR>";
<?php 
        print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TD></TD><TD>&nbsp;<B>Unit</B> ({$units_ct}) </TD>\t<TD onClick = 'do_mail_win(null, null); ' ALIGN = 'center'><IMG SRC='mail_red.png' /></TD><TD>&nbsp; <B>Status</B></TD><TD COLSPAN=2><B>" . $incident . "</B></TD><TD><B>&nbsp;As of</B></TD></TR>\"\n";
    }
    $aprs = $instam = $locatea = $gtrack = $glat = $t_tracker = $ogts = FALSE;
    //7/23/09, 5/11/11
    $utc = gmdate("U");
    // 3/25/09
    // ===========================  begin major while() for RESPONDER ==========
    $chgd_unit = $_SESSION['unit_flag_1'];
    // possibly 0 - 4/8/10
    $_SESSION['unit_flag_1'] = 0;
    // one-time only - 4/11/10
    while ($row = stripslashes_deep(mysql_fetch_array($result))) {
        $resp_gps = get_allocates(2, $row['unit_id']);
        //	5/4/11
        $grp_names = "Groups Assigned: ";
        //	5/4/11
        $y = 0;
        //	5/4/11
        foreach ($resp_gps as $value) {
            //	5/4/11
            $counter = count($resp_gps) > $y + 1 ? ", " : "";
            $grp_names .= get_groupname($value);
            $grp_names .= $counter;
            $y++;
        }
        $latitude = $row['lat'];
        // 7/18/10
        $longitude = $row['lng'];
        // 7/18/10
        $on_click = !my_is_float($row['lat']) || $quick ? " myclick_nm({$row['unit_id']}) " : "myclick({$sb_indx})";
        // 1/2/10
        $got_point = FALSE;
        $name = $row['handle'];
        //	10/8/09
        $index = addslashes($row['icon_str']);
        // 3/19/11
        print "\t\tvar sym = '{$index}';\n";
        // for sidebar and icon 10/8/09
        // 2/13/09
        $todisp = is_guest() ? "" : "&nbsp;&nbsp;<A HREF='units_nm.php?func=responder&view=true&disp=true&id=" . $row['unit_id'] . "'><U>Dispatch</U></A>&nbsp;&nbsp;";
        // 08/8/02
        $toedit = is_guest() || is_user() ? "" : "&nbsp;&nbsp;<A HREF='units_nm.php?func=responder&edit=true&id=" . $row['unit_id'] . "'><U>Edit</U></A>&nbsp;&nbsp;";
        // 5/11/10
        $hide_unit = $row['hide'] == "y" ? "1" : "0";
        // 3/8/10
        $update_error = strtotime('now - 6 hours');
        // set the time for silent setting
        // NAME
        $the_bg_color = $GLOBALS['UNIT_TYPES_BG'][$row['icon']];
        // 2/1/10
        $the_text_color = $GLOBALS['UNIT_TYPES_TEXT'][$row['icon']];
        $arrow = $chgd_unit == $row['unit_id'] ? "<IMG SRC='rtarrow.gif' />" : "";
        // 4/8/10
        $on_click = " onclick_do_unit({$row['unit_id']}) ";
        // 1/2/10
        $sidebar_line = "<TD onClick = '{$on_click}'>{$arrow}<SPAN STYLE='background-color:{$the_bg_color};  opacity: .7; color:{$the_text_color};'>  {$row['handle']}</B></U></SPAN></TD>";
        // MAIL
        if (!is_guest() && is_email($row['contact_via'])) {
            // 2/1/10
            $mail_link = "\t<TD  CLASS='mylink' ALIGN='center'>" . "&nbsp; <IMG SRC='mail.png' BORDER=0 TITLE = 'click to email unit {$name}'" . " onclick = 'do_mail_win(\\\"{$name},{$row['contact_via']}\\\");'> " . "&nbsp;</TD>";
            // 4/26/09
        } else {
            $mail_link = "\t<TD ALIGN='center'>na</TD>";
        }
        $sidebar_line .= $mail_link;
        // STATUS
        $sidebar_line .= "<TD>" . get_status_sel($row['unit_id'], $row['un_status_id'], "u") . "</TD>";
        // status
        // DISPATCHES 3/16/09
        if (!array_key_exists($row['unit_id'], $assigns_ary)) {
            // this unit assigned? - 6/4/10
            $row_assign = FALSE;
        } else {
            // 6/25/10
            $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns`  \n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` t ON ({$GLOBALS['mysql_prefix']}assigns.ticket_id = t.id)\n\t\t\t\tWHERE `responder_id` = '{$row['unit_id']}' AND ( `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' )";
            $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
            $row_assign = mysql_affected_rows() == 0 ? FALSE : stripslashes_deep(mysql_fetch_assoc($result_as));
            unset($result_as);
        }
        $tip = !$row_assign ? "" : str_replace("'", "`", "{$row_assign['contact']}/{$row_assign['street']}/{$row_assign['city']}/{$row_assign['phone']}/{$row_assign['scope']}   ");
        switch ($row_assign['severity']) {
            //color tickets by severity
            case $GLOBALS['SEVERITY_MEDIUM']:
                $severityclass = 'severity_medium';
                break;
            case $GLOBALS['SEVERITY_HIGH']:
                $severityclass = 'severity_high';
                break;
            default:
                $severityclass = 'severity_normal';
                break;
        }
        //		$tick_ct = (mysql_affected_rows()>1)? " (" . mysql_affected_rows() . ")": "";	// active dispatches
        switch (mysql_affected_rows()) {
            // 8/30/10
            case 0:
                $the_disp_stat = "";
                break;
            case 1:
                $the_disp_stat = get_disp_status($row_assign) . "&nbsp;";
                break;
            default:
                // multiples
                $the_disp_stat = "<SPAN CLASS='disp_stat'>&nbsp;" . mysql_affected_rows() . "&nbsp;</SPAN>&nbsp;";
                break;
        }
        // end switch()
        $ass_td = mysql_affected_rows() > 0 ? "<TD ALIGN='left' onMouseover=\\\"Tip('{$tip}')\\\" onmouseout=\\\"UnTip()\\\" onClick = '{$on_click}' COLSPAN=2 CLASS='{$severityclass}' >{$the_disp_stat}" . shorten($row_assign['scope'], 20) . "</TD>" : "<TD onClick = '{$on_click}' > na </TD>";
        $sidebar_line .= $row_assign ? $ass_td : "<TD COLSPAN=2>na</TD>";
        // AS OF
        $strike = $strike_end = "";
        // any remote source?
        $the_time = $row['updated'];
        //		$the_class = "td_data";
        $the_class = "";
        if (abs($utc - $the_time) > $GLOBALS['TOLERANCE']) {
            // attempt to identify  non-current values
            $strike = "<STRIKE>";
            $strike_end = "</STRIKE>";
        } else {
            $strike = $strike_end = "";
        }
        $sidebar_line .= "<TD onClick = '{$on_click}' CLASS='{$the_class}'> {$strike}" . format_sb_date($the_time) . "{$strike_end} </TD>";
        // 6/17/08
        $resp_cat = get_category($row['unit_id']);
        print "\t\tdo_sidebar_u_ed (\"{$sidebar_line}\",  {$sb_indx}, '{$on_click}', sym, \"{$tip}\", \"{$resp_cat}\");\n";
        // (sidebar, line_no, on_click, letter)
        if ($row['hide'] == "y") {
            // 3/8/10
            ?>
		var rowId = tr_id_fixed_part + <?php 
            print $sb_indx;
            ?>
;			// row index for row hide/show - 3/2/10
		rowIds.push(rowId);													// form is "tr_id_??" where ?? is the row no.
<?php 
        }
        // end if ($row['hide']=="y")
        $sb_indx++;
        // zero-based
    }
    // end  ==========  while() for RESPONDER ==========
    $source_legend = $aprs || $instam || $gtrack || $locatea || $glat || $t_tracker || $ogts ? "<TD CLASS='emph' ALIGN='left'>Source time</TD>" : "<TD>&nbsp;</TD>";
    // if any remote data/time 3/24/09
    print "\n\tside_bar_html+= \"<TR CLASS='\" + colors[i%2] +\"'><TD COLSPAN=99 ALIGN='center'>{$source_legend}</TD></TR>\";\n";
    ?>
	var legends = "<TR class='even'><TD ALIGN='center' COLSPAN='99'><TABLE ALIGN='center' WIDTH = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.4));
    ?>
 >";	//	3/15/11
	legends += "<TR CLASS='spacer'><TD CLASS='spacer' COLSPAN='99' ALIGN='center'>&nbsp;</TD></TR><TR class='even'><TD ALIGN='center' COLSPAN='99'><B>Responders Legend</B></TD></TR>";	//	3/15/11
	legends += "<TR CLASS='even'><TD COLSPAN='99' ALIGN='center'>&nbsp;&nbsp;<B>M</B>obility:&nbsp;&nbsp; stopped: <FONT COLOR='red'>&bull;</FONT>&nbsp;&nbsp;&nbsp;moving: <FONT COLOR='green'>&bull;</FONT>&nbsp;&nbsp;&nbsp;fast: <FONT COLOR='white'>&bull;</FONT>&nbsp;&nbsp;&nbsp;silent: <FONT COLOR='black'>&bull;</FONT>&nbsp;&nbsp;</TD></TR>";	//	3/15/11
	legends += "<TR CLASS='" + colors[(i)%2] +"'><TD COLSPAN='99' ALIGN='center'><?php 
    print get_units_legend();
    ?>
</TD></TR></TABLE>";	//	3/15/11

	$("side_bar_r").innerHTML = side_bar_html;										// side_bar_html to responders div		
	$("side_bar_rl").innerHTML = legends + "</TABLE>";		//	12/03/10
	side_bar_html= "";		//	12/03/10	
	side_bar_html+="<TABLE><TR class='heading_2'><TH width = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.4));
    ?>
 ALIGN='center' COLSPAN='99'>Units</TH></TR><TR class='even'><TD COLSPAN=99 CLASS='td_label' ><form action='#'>";			//	12/03/10, 3/15/11

	
// ====================================  Add Facilities to Map 8/1/09 ================================================
//	side_bar_html ="<TABLE border=0 CLASS='sidebar' WIDTH = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.4));
    ?>
 >\n";
	side_bar_html ="<TABLE border=0 CLASS='sidebar' >\n";

	var icons=[];	
	var g=0;

<?php 
    $fac_order_values = array(1 => "`handle`,`fac_type_name` ASC", 2 => "`fac_type_name`,`handle` ASC", 3 => "`fac_status_val`,`fac_type_name` ASC");
    // 3/15/11
    if (array_key_exists('forder', $_POST)) {
        $_SESSION['fac_flag_2'] = $_POST['forder'];
    } elseif (empty($_SESSION['fac_flag_2'])) {
        $_SESSION['fac_flag_2'] = 2;
    }
    // 3/15/11
    $fac_order_str = $fac_order_values[$_SESSION['fac_flag_2']];
    // 3/15/11
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}';";
    //	5/4/11
    $result = mysql_query($query);
    //	5/4/11
    $al_groups = array();
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        //	5/4/11
        $al_groups[] = $row['group'];
    }
    if (isset($_SESSION['viewed_groups'])) {
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    }
    if (!isset($curr_viewed)) {
        $x = 0;
        //	5/4/11
        $where2 = "WHERE (";
        //	5/4/11
        foreach ($al_groups as $grp) {
            //	5/4/11
            $where3 = count($al_groups) > $x + 1 ? " OR " : ")";
            $where2 .= "`{$GLOBALS['mysql_prefix']}allocates`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    } else {
        $x = 0;
        //	5/4/11
        $where2 = "WHERE (";
        //	5/4/11
        foreach ($curr_viewed as $grp) {
            //	5/4/11
            $where3 = count($curr_viewed) > $x + 1 ? " OR " : ")";
            $where2 .= "`{$GLOBALS['mysql_prefix']}allocates`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    }
    $where2 .= "AND `{$GLOBALS['mysql_prefix']}allocates`.`type` = 3";
    //	5/4/11
    $query_fac = "SELECT *,UNIX_TIMESTAMP(updated) AS updated, \n\t\t`{$GLOBALS['mysql_prefix']}facilities`.id AS `fac_id`, \n\t\t`{$GLOBALS['mysql_prefix']}facilities`.description AS `facility_description`,\n\t\t`{$GLOBALS['mysql_prefix']}fac_types`.name AS `fac_type_name`, \n\t\t`{$GLOBALS['mysql_prefix']}facilities`.name AS `facility_name`,\n\t\t`{$GLOBALS['mysql_prefix']}fac_status`.status_val AS fac_status_val, \n\t\t`{$GLOBALS['mysql_prefix']}facilities`.status_id AS fac_status_id\n\t\tFROM `{$GLOBALS['mysql_prefix']}facilities` \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` ON ( `{$GLOBALS['mysql_prefix']}facilities`.`id` = `{$GLOBALS['mysql_prefix']}allocates`.resource_id )\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}fac_types` ON `{$GLOBALS['mysql_prefix']}facilities`.type = `{$GLOBALS['mysql_prefix']}fac_types`.id \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}fac_status` ON `{$GLOBALS['mysql_prefix']}facilities`.status_id = `{$GLOBALS['mysql_prefix']}fac_status`.id \n\t\t{$where2} \n\t\tGROUP BY fac_id ORDER BY {$fac_order_str}";
    $result_fac = mysql_query($query_fac) or do_error($query_fac, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $mail_str = may_email() ? "do_fac_mail_win();" : "";
    // 7/2/10
    $temp = max(320, intval($_SESSION['scr_width'] * 0.4));
    $facs_ct = mysql_affected_rows();
    // 1/4/10
    if ($facs_ct == 0) {
        print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TH COLSPAN=99 ALIGN='center'><I><B>No Facilities!</I></B></TH></TR>\"\n";
        //	3/15/11
    } else {
        $fs_checked = array("", "", "", "");
        $fs_checked[$_SESSION['fac_flag_2']] = " CHECKED";
        ?>
		side_bar_html += "<TR CLASS = 'even'><TD COLSPAN=99 ALIGN='center'>";	//	3/15/11
		side_bar_html += "<I><B>Sort</B>:&nbsp;&nbsp;&nbsp;&nbsp;";
		side_bar_html += "Name&raquo; 	<input type = radio name = 'frm_order' value = 1 <?php 
        print $fs_checked[1];
        ?>
 onClick = 'do_fac_sort_sub(this.value);' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";	//	3/15/11, 5/3/11
		side_bar_html += "Type &raquo; 	<input type = radio name = 'frm_order' value = 2 <?php 
        print $fs_checked[2];
        ?>
 onClick = 'do_fac_sort_sub(this.value);' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";	//	3/15/11, 5/3/11
		side_bar_html += "Status &raquo; <input type = radio name = 'frm_order' value = 3 <?php 
        print $fs_checked[3];
        ?>
 onClick = 'do_fac_sort_sub(this.value);' />";	//	3/15/11, 5/3/11
		side_bar_html += "</I></TD></TR>";	//	3/15/11
<?php 
        print "\n\t\tside_bar_html += \"<TR CLASS='odd'><TD>&nbsp</TD><TD ALIGN='left'><B>Facility</B> ({$facs_ct}) </TD><TD ALIGN='left'><IMG SRC='mail_red.png' BORDER=0 onClick = '{$mail_str}'/></TD><TD>&nbsp;<B>Status</B></TD><TD ALIGN='left'><B>Type</B></TD><TD ALIGN='left'><B>&nbsp;As of</B></TD></TR>\"\n";
        // 7/2/10, 3/15/11
    }
    //  ===========================  begin major while() for FACILITIES ==========
    $quick = !is_guest() && intval(get_variable('quick') == 1);
    // 11/27/09
    $sb_indx = 0;
    // for fac's only 8/5/10
    while ($row_fac = mysql_fetch_assoc($result_fac)) {
        // 7/7/10
        $fac_gps = get_allocates(3, $row_fac['fac_id']);
        //	5/4/11
        $grp_names = "Groups Assigned: ";
        //	5/4/11
        $y = 0;
        //	5/4/11
        foreach ($fac_gps as $value) {
            //	5/4/11
            $counter = count($fac_gps) > $y + 1 ? ", " : "";
            $grp_names .= get_groupname($value);
            $grp_names .= $counter;
            $y++;
        }
        $grp_names .= " / ";
        $fac_id = $row_fac['fac_id'];
        $fac_type = $row_fac['icon'];
        $fac_type_name = $row_fac['fac_type_name'];
        $fac_region = get_first_group(3, $fac_id);
        $fac_name = addslashes($row_fac['facility_name']);
        //		10/8/09
        $fac_handle = addslashes($row_fac['handle']);
        //		10/8/09
        $fac_index = addslashes($row_fac['icon_str']);
        $on_click = $can_edit ? "fac_click_ed({$fac_id})" : "fac_click_vw({$fac_id})";
        // 8/24/10
        print "\t\tvar fac_sym = '" . addslashes($fac_index) . "';\n";
        //	 for sidebar and icon 10/8/09 - 4/27/11
        $facility_display_name = $f_disp_name = $row_fac['handle'];
        $the_bg_color = $GLOBALS['FACY_TYPES_BG'][$row_fac['icon']];
        // 2/8/10
        $the_text_color = $GLOBALS['FACY_TYPES_TEXT'][$row_fac['icon']];
        // 2/8/10
        $sidebar_fac_line = "<TD onClick = '{$on_click}' TITLE = '{$fac_name}' ALIGN='left'><SPAN STYLE='background-color:{$the_bg_color};  opacity: .7; color:{$the_text_color};' >{$fac_handle}</SPAN></TD>";
        // MAIL
        if (may_email() && (is_email($row_fac['contact_email']) || is_email($row_fac['security_email']))) {
            // 7/2/10
            $mail_link = "\t<TD CLASS='mylink' ALIGN='center'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . "<IMG SRC='mail.png' BORDER=0 TITLE = 'click to email facility {$fac_handle}'" . " onclick = 'do_mail_win(\\\"{$fac_handle},{$row_fac['contact_email']}\\\");'> " . "</TD>";
            // 4/26/09
        } else {
            $mail_link = "\t<TD ALIGN='center'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>na</b></TD>";
        }
        $sidebar_fac_line .= $mail_link;
        $sidebar_fac_line .= "<TD ALIGN='left'  onClick = '{$on_click};' >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . addslashes(shorten($row_fac['fac_type_name'], $col_width)) . "</TD>";
        $sidebar_fac_line .= "<TD ALIGN='left'  onClick = '{$on_click};' >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . addslashes($row_fac['status_val']) . "</TD>";
        $sidebar_fac_line .= "<TD onClick = '{$on_click};' >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . format_sb_date($row_fac['updated']) . "</TD>";
        ?>
		var fac_icon = "td_label";
		do_sidebar_fac_ed ("<?php 
        print $sidebar_fac_line;
        ?>
", <?php 
        print $row_fac['fac_id'];
        ?>
, fac_sym, fac_icon, g);		
		g++;
<?php 
        $sb_indx++;
        // zero-based - 6/30/10
    }
    // end while
    ?>
	side_bar_html += "</TD></TR>\n";

	<?php 
    // =====================================End of functions to show facilities========================================================================
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE `status` = 1 ";
    // 10/21/09
    $result_ct = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $num_closed = mysql_num_rows($result_ct);
    unset($result_ct);
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}ticket` WHERE `status` = 3 ";
    // 10/21/09
    $result_scheduled = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $num_scheduled = mysql_num_rows($result_scheduled);
    unset($result_scheduled);
    ?>
	side_bar_html +="<TR><TD COLSPAN='99'></TD></TR></TABLE>";
	var fac_legends = "";
<?php 
    if ($any_facilities) {
        ?>
	var fac_legends ="<TABLE border='0' VALIGN='top' ALIGN='center' CLASS='sidebar' WIDTH = <?php 
        print max(320, intval($_SESSION['scr_width'] * 0.4));
        ?>
 >";	//	11/29/10, 3/15/11
	fac_legends +="<TR CLASS='spacer'><TD CLASS='spacer' COLSPAN='99' ALIGN='center'>&nbsp;</TD></TR>";	//	11/29/10, 3/15/11
	fac_legends +="<TR class='even'><TD ALIGN='center' COLSPAN=99><B>Facilities Legend</B></TD></TR>";		// legend row, 11/29/10, 3/15/11
	fac_legends +="<TR class='even'><TD ALIGN='center' COLSPAN=99><?php 
        print get_facilities_legend();
        ?>
</TD></TR></TABLE>\n";	//	3/15/11
<?php 
    }
    ?>
		
	side_bar_html +="</TABLE></TD></TR></TABLE>\n";
	$("side_bar_f").innerHTML = side_bar_html;	//side_bar_html to facilities div
	$("facs_legend").innerHTML = fac_legends;	//side_bar_html to facilities div
	side_bar_html = "";


</SCRIPT>
<?php 
    echo "Time Elapsed: " . round(microtime(true) - $time, 3) . "s";
}
function list_responders($addon = '', $start)
{
    //	global {$_SESSION['fip']}, $fmp, {$_SESSION['editfile']}, {$_SESSION['addfile']}, {$_SESSION['unitsfile']}, {$_SESSION['facilitiesfile']}, {$_SESSION['routesfile']},	{$_SESSION['facroutesfile']};
    global $iw_width, $u_types, $tolerance;
    $assigns = array();
    // 08/8/3
    $tickets = array();
    // ticket id's
    $query = "SELECT `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`, `{$GLOBALS['mysql_prefix']}assigns`.`responder_id`,\n\t\t`{$GLOBALS['mysql_prefix']}ticket`.`scope` AS `ticket` \n\t\tFROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` ON `{$GLOBALS['mysql_prefix']}assigns`.`ticket_id`=`{$GLOBALS['mysql_prefix']}ticket`.`id`\n\t\tWHERE ( `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' )";
    $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_as = stripslashes_deep(mysql_fetch_array($result_as))) {
        $assigns[$row_as['responder_id']] = $row_as['ticket'];
        $tickets[$row_as['responder_id']] = $row_as['ticket_id'];
    }
    unset($result_as);
    $calls = array();
    // 6/17/08
    $calls_nr = array();
    ?>

<SCRIPT >

var color=0;
	var colors = new Array ('odd', 'even');

	function hideDiv(div_area, hide_cont, show_cont) {	//	3/15/11
		if (div_area == "buttons_sh") {
			var controlarea = "hide_controls";
			}
		if (div_area == "resp_list_sh") {
			var controlarea = "resp_list";
			}
		if (div_area == "facs_list_sh") {
			var controlarea = "facs_list";
			}
		if (div_area == "incs_list_sh") {
			var controlarea = "incs_list";
			}
		if (div_area == "region_boxes") {
			var controlarea = "region_boxes";
			}			
		var divarea = div_area 
		var hide_cont = hide_cont 
		var show_cont = show_cont 
		if($(divarea)) {
			$(divarea).style.display = 'none';
			$(hide_cont).style.display = 'none';
			$(show_cont).style.display = '';
			} 
		var params = "f_n=" +controlarea+ "&v_n=h&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";
		var url = "persist2.php";
		sendRequest (url, gb_handleResult, params);			
		} 

	function showDiv(div_area, hide_cont, show_cont) {	//	3/15/11
		if (div_area == "buttons_sh") {
			var controlarea = "hide_controls";
			}
		if (div_area == "resp_list_sh") {
			var controlarea = "resp_list";
			}
		if (div_area == "facs_list_sh") {
			var controlarea = "facs_list";
			}
		if (div_area == "incs_list_sh") {
			var controlarea = "incs_list";
			}
		if (div_area == "region_boxes") {
			var controlarea = "region_boxes";
			}				
		var divarea = div_area
		var hide_cont = hide_cont 
		var show_cont = show_cont 
		if($(divarea)) {
			$(divarea).style.display = '';
			$(hide_cont).style.display = '';
			$(show_cont).style.display = 'none';
			}
		var params = "f_n=" +controlarea+ "&v_n=s&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";
		var url = "persist2.php";
		sendRequest (url, gb_handleResult, params);					
		} 	

	function checkArray(form, arrayName)	{	//	5/3/11
		var retval = new Array();
		for(var i=0; i < form.elements.length; i++) {
			var el = form.elements[i];
			if(el.type == "checkbox" && el.name == arrayName && el.checked) {
				retval.push(el.value);
			}
		}
	return retval;
	}		
		
	function checkForm(form)	{	//	6/10/11
		var errmsg="";
		var itemsChecked = checkArray(form, "frm_group[]");
		if(itemsChecked.length > 0) {
			var params = "f_n=viewed_groups&v_n=" +itemsChecked+ "&sess_id=<?php 
    print get_sess_key(__LINE__);
    ?>
";	//	3/15/11
			var url = "persist3.php";	//	3/15/11	
			sendRequest (url, fvg_handleResult, params);				
//			form.submit();
		} else {
			errmsg+= "\tYou cannot Hide all the regions\n";
			if (errmsg!="") {
				alert ("Please correct the following and re-submit:\n\n" + errmsg);
				return false;
			}
		}
	}
	
	function fvg_handleResult(req) {	// 6/10/11	The persist callback function for viewed groups.
		document.region_form.submit();
		}
		
	function form_validate(theForm) {	//	5/3/11
//		alert("Validating");
		checkForm(theForm);
		}				// end function validate(theForm)			

	function do_sidebar (sidebar, id, the_class, unit_id, index) {
		var unit_id = unit_id;
		side_bar_html += "<TR CLASS='" + colors[(id)%2] +"' >";		
		side_bar_html += "<TD CLASS='" + the_class + "' onClick = 'myclick(" + unit_id + ");'>" + index + "</TD>" + sidebar +"</TD></TR>\n";	// 1/5/09, 3/4/09, 10/29/09 removed period
		}

	function myclick(unit_id) {				// Responds to sidebar click - view responder data
		document.view_form.id.value=unit_id;
		document.view_form.submit();
		}
		
	function myclick_nm(v_id) {				// Responds to sidebar click - view responder data
		document.view_form.id.value=v_id;
		document.view_form.submit();
		}

<?php 
    $dzf = get_variable('def_zoom_fixed');
    print "\tvar map_is_fixed = ";
    print my_is_int($dzf) && $dzf == 2 || my_is_int($dzf) && $dzf == 3 ? "true;\n" : "false;\n";
    ?>
	var side_bar_html = "<TABLE border=0 CLASS='sidebar' WIDTH = <?php 
    print max(320, intval($_SESSION['scr_width'] * 0.6));
    ?>
 >";
	side_bar_html += "<TR class='even'>	<TD></TD><TD ALIGN='left'><B>Unit</B></TD><TD ALIGN='left'><B>Handle</B></TD><TD ALIGN='left'><B>Dispatch</B></TD><TD ALIGN='left'><B>Status</B></TD><TD ALIGN='left'><B>M</B></TD><TD ALIGN='left'><B>As of</B></TD></TR>";
	var which;
	var i = <?php 
    print $start;
    ?>
;					// sidebar/icon index
	var points = false;								// none

<?php 
    function can_do_dispatch($the_row)
    {
        if (intval($the_row['multi']) == 1) {
            return TRUE;
        }
        $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` WHERE `responder_id` = {$the_row['id']}";
        // all dispatches this unit
        $result_temp = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        while ($row_temp = stripslashes_deep(mysql_fetch_array($result_temp))) {
            // check any open runs this unit
            if (!is_date($row_temp['clear'])) {
                // if  clear is empty, then NOT dispatch-able
                unset($result_temp, $row_temp);
                return FALSE;
            }
        }
        // end while ($row_temp ...)
        unset($result_temp, $row_temp);
        return TRUE;
        // none found, can dispatch
    }
    // end function can_do_dispatch()
    $eols = array("\r\n", "\n", "\r");
    // all flavors of eol
    $bulls = array(0 => "", 1 => "red", 2 => "green", 3 => "white", 4 => "black");
    $status_vals = array();
    // build array of $status_vals
    $status_vals[''] = $status_vals['0'] = "TBD";
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}un_status` ORDER BY `id`";
    $result_st = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    while ($row_st = stripslashes_deep(mysql_fetch_array($result_st))) {
        $temp = $row_st['id'];
        $status_vals[$temp] = $row_st['status_val'];
    }
    unset($result_st);
    $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}allocates` WHERE `type`= 4 AND `resource_id` = '{$_SESSION['user_id']}';";
    //	6/10/11
    $result = mysql_query($query);
    // 4/13/11
    $al_groups = array();
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        //	6/10/11
        $al_groups[] = $row['group'];
    }
    if (isset($_SESSION['viewed_groups'])) {
        //	6/10/11
        $curr_viewed = explode(",", $_SESSION['viewed_groups']);
    }
    if (!isset($curr_viewed)) {
        $x = 0;
        //	6/10/11
        $where2 = "WHERE (";
        //	6/10/11
        foreach ($al_groups as $grp) {
            //	6/10/11
            $where3 = count($al_groups) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    } else {
        $x = 0;
        //	6/10/11
        $where2 = "WHERE (";
        //	6/10/11
        foreach ($curr_viewed as $grp) {
            //	6/10/11
            $where3 = count($curr_viewed) > $x + 1 ? " OR " : ")";
            $where2 .= "`a`.`group` = '{$grp}'";
            $where2 .= $where3;
            $x++;
        }
    }
    $where2 .= "AND `a`.`type` = 2";
    //	6/10/11
    $query = "SELECT *, UNIX_TIMESTAMP(updated) AS `updated`,\n\t\t`t`.`id` AS `type_id`,\n\t\t`r`.`id` AS `unit_id`,\n\t\t`r`.`name` AS `name`,\n\t\t`s`.`description` AS `stat_descr`,\n\t\t`r`.`description` AS `unit_descr`, \n\t\t(SELECT  COUNT(*) as numfound FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\tWHERE `{$GLOBALS['mysql_prefix']}assigns`.`responder_id` = unit_id  AND `clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' ) AS `nr_assigned` \n\t\tFROM `{$GLOBALS['mysql_prefix']}responder` `r` \n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}allocates` `a` ON ( `r`.`id` = a.resource_id )\t\t\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}unit_types` `t` ON ( `r`.`type` = t.id )\t\n\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}un_status` `s` ON ( `r`.`un_status_id` = s.id ) \t\t\n\t\t{$where2}  GROUP BY unit_id ORDER BY `nr_assigned` DESC,  `handle` ASC, `r`.`name` ASC ";
    // 2/1/10, 3/15/10, 6/10/11
    $result = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
    $num_units = mysql_affected_rows();
    $aprs = FALSE;
    $instam = FALSE;
    $locatea = FALSE;
    // 7/23/09
    $gtrack = FALSE;
    // 7/23/09
    $glat = FALSE;
    // 7/23/09
    $i = 0;
    // counter
    // =============================================================================
    $bulls = array(0 => "", 1 => "red", 2 => "green", 3 => "white", 4 => "black");
    $utc = gmdate("U");
    //									 ==========  major while() for RESPONDER ==========
    while ($row = stripslashes_deep(mysql_fetch_assoc($result))) {
        $resp_gps = get_allocates(2, $row['unit_id']);
        //	6/10/11
        $grp_names = "Groups Assigned: ";
        //	6/10/11
        $y = 0;
        //	6/10/11
        foreach ($resp_gps as $value) {
            //	6/10/11
            $counter = count($resp_gps) > $y + 1 ? ", " : "";
            $grp_names .= get_groupname($value);
            $grp_names .= $counter;
            $y++;
        }
        $grp_names .= " / ";
        $aprs = $instam = $locatea = $gtrack = $glat = $t_tracker = FALSE;
        // all trackers off, 5/11/11 added internal Tickets Tracker
        $temp = explode("/", $row['name']);
        $index = substr($temp[count($temp) - 1], -6, strlen($temp[count($temp) - 1]));
        // 3/19/11
        $the_on_click = my_is_float($row['lat']) ? " onClick = myclick({$row['unit_id']}); " : " onClick = myclick_nm({$row['unit_id']}); ";
        $the_bg_color = $GLOBALS['UNIT_TYPES_BG'][$row['icon']];
        // 2/1/10
        $the_text_color = $GLOBALS['UNIT_TYPES_TEXT'][$row['icon']];
        // 2/1/10
        $index = $row['icon_str'];
        // 4/28/11
        $track_type = get_remote_type($row);
        // 7/6/11
        $do_dispatch = can_do_dispatch($row);
        // 11/17/09
        $got_point = FALSE;
        print "\n\t\tvar i={$i};\n";
        $tofac = is_guest() ? "" : "&nbsp;&nbsp;<A HREF='{units_nm.php?func=responder&view=true&dispfac=true&id=" . $row['unit_id'] . "'><U>To Facility</U></A>&nbsp;&nbsp;";
        // 10/6/09
        $todisp = is_guest() || !can_do_dispatch($row) ? "" : "&nbsp;&nbsp;<A HREF='" . basename(__FILE__) . "?func=responder&view=true&disp=true&id=" . $row['unit_id'] . "'><U>Dispatch</U></A>&nbsp;&nbsp;&nbsp;";
        // 08/8/02, 9/19/09
        $toedit = is_guest() ? "" : "&nbsp;&nbsp;<A HREF='" . basename(__FILE__) . "?func=responder&edit=true&id=" . $row['unit_id'] . "'><U>Edit</U></A>&nbsp;&nbsp;&nbsp;&nbsp;";
        // 10/8/08
        $temp = $row['un_status_id'];
        // 2/24/09
        $the_status = array_key_exists($temp, $status_vals) ? $status_vals[$temp] : "??";
        // 2/2/09
        $the_bull = "";
        // define the bullet
        $update_error = strtotime('now - 6 hours');
        // set the time for silent setting
        if ($track_type > 0) {
            // get most recent position data
            $do_legend = TRUE;
        }
        // name, handle
        $name = addslashes(shorten($row['name'], 40));
        //	10/8/09
        $handle = addslashes($row['handle']);
        $sidebar_line = "<TD TITLE = '{$handle}' {$the_on_click}><U><SPAN STYLE='background-color:{$the_bg_color};  opacity: .7; color:{$the_text_color};'>{$handle}</SPAN></U></TD>";
        // 10/8/09
        $sidebar_line .= "<TD TITLE = '" . addslashes($row['name']) . "' {$the_on_click}><U>{$name}</TD>";
        // 10/8/09
        // assignments 3/16/09, 3/15/10
        $query = "SELECT * FROM `{$GLOBALS['mysql_prefix']}assigns` \n\t\t\tLEFT JOIN `{$GLOBALS['mysql_prefix']}ticket` `t` ON (`{$GLOBALS['mysql_prefix']}assigns`.`ticket_id` = `t`.`id`)\n\t\t\tWHERE `responder_id` = '{$row['unit_id']}' AND (`clear` IS NULL OR DATE_FORMAT(`clear`,'%y') = '00' )";
        $result_as = mysql_query($query) or do_error($query, 'mysql query failed', mysql_error(), basename(__FILE__), __LINE__);
        $row_assign = mysql_affected_rows() == 0 ? FALSE : stripslashes_deep(mysql_fetch_assoc($result_as));
        switch ($row_assign['severity']) {
            //color tickets by severity
            case $GLOBALS['SEVERITY_MEDIUM']:
                $severityclass = 'severity_medium';
                break;
            case $GLOBALS['SEVERITY_HIGH']:
                $severityclass = 'severity_high';
                break;
            default:
                $severityclass = 'severity_normal';
                break;
        }
        switch (mysql_num_rows($result_as)) {
            // 10/4/10
            case 0:
                $the_disp_stat = "";
                break;
            case 1:
                $the_disp_stat = get_disp_status($row_assign) . "&nbsp;";
                break;
            default:
                // multiples
                $the_disp_stat = "<SPAN CLASS='disp_stat'>&nbsp;" . mysql_affected_rows() . "&nbsp;</SPAN>&nbsp;";
                break;
        }
        // end switch()
        $tick_ct = mysql_affected_rows() > 1 ? "(" . mysql_num_rows($result_as) . ") " : "";
        $ass_td = mysql_affected_rows() > 0 ? "<TD CLASS='{$severityclass}' TITLE = '{$row_assign['scope']}' STYLE = 'white-space:nowrap;' >{$the_disp_stat}" . shorten($row_assign['scope'], 24) . "</TD>" : "<TD>na</TD>";
        $sidebar_line .= $row_assign ? $ass_td : "<TD>na</TD>";
        // status, mobility  - 9/11/10
        $sidebar_line .= "<TD TITLE = '" . addslashes($the_status) . "'> " . get_status_sel($row['unit_id'], $row['un_status_id'], "u") . "</TD>";
        $sidebar_line .= "<TD TITLE ='{$row['callsign']}'>&nbsp;{$GLOBALS['TRACK_2L'][$track_type]}&nbsp;{$the_bull}</TD>";
        // 4/14/10
        // as of
        $strike = $strike_end = "";
        $the_time = $row['updated'];
        // 7/6/11
        $the_class = "";
        if ($row['mobile'] == 1 && abs($utc - $the_time) > $GLOBALS['TOLERANCE']) {
            // identify  non-current values
            $strike = "<STRIKE>";
            $strike_end = "</STRIKE>";
        }
        $sidebar_line .= "<TD CLASS='{$the_class}'> {$strike}" . format_sb_date($the_time) . "{$strike_end}</TD>";
        // 6/17/08
        ?>
		var unit_id = "<?php 
        print $index;
        ?>
";	//	10/8/09
	
		var the_class = "td_label";		// 4/3/09
		var handle = "<?php 
        print substr($row['handle'], 1);
        ?>
";
		var longhandle = "<?php 
        print $row['handle'];
        ?>
";
<?php 
        print "\tdo_sidebar(\" {$sidebar_line} \" , i, {$row['id']}, {$row['unit_id']}, unit_id);\n";
        // sidebar only - no map, 11/11/09
        $i++;
        // zero-based
    }
    // end  ==========  while() for RESPONDER ==========
    $source_legend = isset($do_legend) ? "<TD CLASS='emph' ALIGN='left'>Source time</TD>" : "<TD></TD>";
    // if any remote data/time 3/24/09
    ?>
	side_bar_html+= "<TR CLASS='" + colors[i%2] +"'><TD COLSPAN=5>&nbsp;</TD><?php 
    print $source_legend;
    ?>
</TR>";
<?php 
    if (!empty($addon)) {
        print "\n\tside_bar_html +=\"" . $addon . "\"\n";
    }
    ?>
	side_bar_html +="</TABLE>\n";
	$("side_bar").innerHTML += side_bar_html;	// append the assembled side_bar_html contents to the side bar div
	$("num_units").innerHTML = <?php 
    print $num_units;
    ?>
;			

</SCRIPT>

<?php 
}