<?php

/**
 * Checks is some switch id linked with
 * 
 * @param array $alllinks  Array of id=>parentid
 * @param int  $traceid    Switch ID wich will be traced
 * @param int  $checkid    Switch ID to check
 * 
 * @return bool
 */
function sm_MapIsLinked($alllinks, $traceid, $checkid) {
    $road = array();
    $road[] = $traceid;
    $x = $traceid;


    while (!empty($x)) {
        foreach ($alllinks as $id => $parentid) {
            if ($x == $id) {
                $road[] = $parentid;
                $x = $parentid;
            }
        }
    }

    if (in_array($checkid, $road)) {
        $result = true;
    } else {
        $result = false;
    }
    return ($result);
}

/**
 * Returns array of switch parent switches with himself
 * 
 * @param array $alllinks all switches links
 * @param int $traceid switch name to trace
 * 
 * @return array
 */
function zb_SwitchGetParents($alllinks, $traceid) {
    $road = array();
    $road[] = $traceid;
    $x = $traceid;


    while (!empty($x)) {
        foreach ($alllinks as $id => $parentid) {
            if ($x == $id) {
                $road[] = $parentid;
                $x = $parentid;
            }
        }
    }

    $result = $road;
    return ($result);
}

/**
 * Checks is loop possible after setting for switchId something as parent device
 * 
 * @param array $alllinks
 * @param int $switchId
 * @param int $setParent
 * 
 * @return bool
 */
function sm_CheckLoop($alllinks, $switchId, $setParent) {
    $result = false;
    if (!empty($switchId)) {
        if (sm_MapIsLinked($alllinks, $setParent, $switchId)) {
            $result = false;
        } else {
            $result = true;
        }
    } else {
        $result = true;
    }
    return ($result);
}

/**
 * Returns full map of switch links
 * 
 * @param int $traceid switch ID to trace uplinks
 * 
 * @return string
 */
function sm_MapDrawSwitchUplinks($traceid = '') {
    global $ubillingConfig;
    
    $query = "SELECT * from `switches`";
    $tmpSwitches = simple_queryall($query);
    $allswitches = array();
    $alllinks = array();
    $result = '';
    //dead switches detection
    $dead_raw = zb_StorageGet('SWDEAD');
    $deadarr = array();
    if ($dead_raw) {
        $deadarr = unserialize($dead_raw);
    }


    if (!empty($tmpSwitches)) {
        //transform array to id=>switchdata
        foreach ($tmpSwitches as $io => $each) {
            $allswitches[$each['id']] = $each;
        }

        //making id=>parentid array if needed
        if (!empty($traceid)) {
            foreach ($tmpSwitches as $io => $each) {
                $alllinks[$each['id']] = $each['parentid'];
            }
        }
    }

    if (!empty($allswitches)) {
        foreach ($allswitches as $io => $each) {
            if (!empty($each['parentid'])) {
                if (isset($allswitches[$each['parentid']])) {
                    if (($allswitches[$each['parentid']]['geo'] != '') and ($each['geo'] != '')) {
                        $coord1 = $each['geo'];
                        $coord2 = $allswitches[$each['parentid']]['geo'];
                        $hint = $each['location'] . ' ' . $each['ip'] . ' → ' . $allswitches[$each['parentid']]['location'] . ' ' . $allswitches[$each['parentid']]['ip'];

                        if ((!isset($deadarr[$each['ip']])) and (!isset($deadarr[$allswitches[$each['parentid']]['ip']]))) {
                            $color = '#00FF00';
                        } else {
                            $color = '#FF0000';
                        }

                        //trace mode
                        if (!empty($traceid)) {
                            //switch is traced device
                            if ($each['id'] == $traceid) {
                                $width = 5;
                                $result .= sm_MapAddLine($coord1, $coord2, $color, $hint, $width);
                            } else {
                                //detecting uplinks
                                if (sm_MapIsLinked($alllinks, $traceid, $each['id'])) {
                                    $width = 3;
                                    $result .= sm_MapAddLine($coord1, $coord2, $color, $hint, $width);
                                }
                            }
                        } else {
                            $width = 1;
                            $result .= sm_MapAddLine($coord1, $coord2, $color, $hint, $width);
                        }
                    }
                }
            }
        }
    }


    return ($result);
}

/**
 * Returns IDs used in brief mini-map mode:
 * - selected switch
 * - all its uplinks up to top level
 * - all its downlink subtree switches.
 * 
 * @param int $switchId
 * 
 * @return array
 */
function sm_MapGetLinkedSwitchIds($switchId) {
    $switchId = ubRouting::filters($switchId, 'int');
    $switchesDb = new NyanORM('switches');
    $tmpSwitches = $switchesDb->getAll();
    $parentMap = array();
    $childrenMap = array();
    $result = array();
    $queue = array();

    if (!empty($switchId)) {
        if (!empty($tmpSwitches)) {
            foreach ($tmpSwitches as $io => $each) {
                $currentId = (int) $each['id'];
                $parentId = (int) $each['parentid'];
                $parentMap[$currentId] = $parentId;
                if (!isset($childrenMap[$currentId])) {
                    $childrenMap[$currentId] = array();
                }
                if (!empty($parentId)) {
                    if (!isset($childrenMap[$parentId])) {
                        $childrenMap[$parentId] = array();
                    }
                    $childrenMap[$parentId][$currentId] = $currentId;
                }
            }
        }

        // selected switch itself
        $result[$switchId] = $switchId;

        // all uplinks (parents chain)
        $currentParent = isset($parentMap[$switchId]) ? (int) $parentMap[$switchId] : 0;
        while (!empty($currentParent)) {
            if (isset($result[$currentParent])) {
                break;
            }
            $result[$currentParent] = $currentParent;
            if (isset($parentMap[$currentParent])) {
                $currentParent = (int) $parentMap[$currentParent];
            } else {
                $currentParent = 0;
            }
        }

        // all downlinks (children subtree)
        $queue[] = $switchId;
        while (!empty($queue)) {
            $current = array_shift($queue);
            if (isset($childrenMap[$current])) {
                foreach ($childrenMap[$current] as $childId) {
                    if (!isset($result[$childId])) {
                        $result[$childId] = $childId;
                        $queue[] = $childId;
                    }
                }
            }
        }
    }

    return ($result);
}

/**
 * Returns map marks for linked switches only
 * (parent/child devices for selected switch).
 * 
 * @param int $switchId
 * 
 * @return string
 */
function sm_MapDrawLinkedSwitches($switchId) {
    global $ubillingConfig;
    $switchId = ubRouting::filters($switchId, 'int');
    $linkedSwitches = sm_MapGetLinkedSwitchIds($switchId);
    
    $switchesDb=new NyanORM('switches');
    $switchesDb->where('geo', '!=', '');
    $allswitches=$switchesDb->getAll();

    $uplinkTraceIcon = wf_img('skins/ymaps/uplinks.png', __('Show links'));
    $switchEditIcon = wf_img('skins/icon_edit.gif', __('Edit'));
    $switchPollerIcon = wf_img('skins/snmp.png', __('SNMP query'));
    $switchLocatorIcon = wf_img('skins/icon_search_small.gif', __('Zoom in'));

    $footerDelimiter = wf_tag('br');
    $result = '';
    //dead switches detection
    $dead_raw = zb_StorageGet('SWDEAD');
    $deadarr = array();
    if ($dead_raw) {
        $deadarr = unserialize($dead_raw);
    }

    if (!empty($allswitches)) {
        foreach ($allswitches as $io => $each) {
            if (isset($linkedSwitches[$each['id']])) {
                $geo = ubRouting::filters($each['geo'], 'mres');
                $title = ubRouting::filters($each['ip'], 'mres');

                //switch hint content
                $content = ubRouting::filters($each['location'], 'mres');
                if (empty($content)) {
                    $content = __('No location set');
                }

                $iconlabel = '';

                if (!isset($deadarr[$each['ip']])) {
                    if (ispos($each['desc'], 'NP')) {
                        $footer = __('Switch') . ': '.__('Status').' '.__('Unknown');
                        $icon = sm_MapNPIcon(false);
                    } else {
                        $footer = __('Switch alive');
                        $icon = sm_MapGoodIcon(false);
                    }
                } else {
                    $footer = __('Switch dead');
                    $icon = sm_MapBadIcon(false);
                }

                if (!empty($each['location'])) {
                    $iconlabel = $each['location'];
                } else {
                    $iconlabel = $each['ip'];
                }


                //switch footer controls
                $footer .= $footerDelimiter;
                $footer .= wf_tag('a', false, '', 'href="?module=switches&edit=' . $each['id'] . '"') . $switchEditIcon . wf_tag('a', true) . ' ';


                if (!empty($each['snmp'])) {
                    $footer .= wf_tag('a', false, '', 'href="?module=switchpoller&switchid=' . $each['id'] . '"') . $switchPollerIcon . wf_tag('a', true) . ' ';
                }

                $footer .= wf_tag('a', false, '', 'href="?module=switchmap&finddevice=' . $each['geo'] . '"') . $switchLocatorIcon . wf_tag('a', true) . ' ';


                if (!empty($each['parentid'])) {
                    $uplinkTraceUrl = '?module=switchmap&finddevice=' . $each['geo'] . '&showuplinks=true&traceid=' . $each['id'];
                    $uplinkTraceLink = wf_tag('a', false, '', 'href="' . $uplinkTraceUrl . '"') . $uplinkTraceIcon . wf_tag('a', true) . ' ';
                    $footer .= $uplinkTraceLink;
                }
                
                $result .= sm_MapAddMark($geo, $title, $content, $footer, $icon, $iconlabel, true);
            }
        }
    }
    return ($result);
}

/**
 * Returns map links for all linked switches
 * (both uplink and downlink links for selected switch).
 * 
 * @param int $switchId
 * 
 * @return string
 */
function sm_MapDrawSwitchAllLinks($switchId) {
    $switchId = ubRouting::filters($switchId, 'int');
    $switchesDb=new NyanORM('switches');
    $tmpSwitches=$switchesDb->getAll();
    $allswitches = array();
    $linkedSwitches = sm_MapGetLinkedSwitchIds($switchId);
    $result = '';

    //dead switches detection
    $dead_raw = zb_StorageGet('SWDEAD');
    $deadarr = array();
    if ($dead_raw) {
        $deadarr = unserialize($dead_raw);
    }

    if (!empty($tmpSwitches)) {
        foreach ($tmpSwitches as $io => $each) {
            $allswitches[$each['id']] = $each;
        }
    }

    if (!empty($allswitches)) {
        foreach ($allswitches as $io => $each) {
            if (!empty($each['parentid'])) {
                if (isset($allswitches[$each['parentid']])) {
                    if (($allswitches[$each['parentid']]['geo'] != '') and ($each['geo'] != '')) {
                        if (isset($linkedSwitches[$each['id']]) and isset($linkedSwitches[$each['parentid']])) {
                            $coord1 = $each['geo'];
                            $coord2 = $allswitches[$each['parentid']]['geo'];
                            $hint = $each['location'] . ' ' . $each['ip'] . ' → ' . $allswitches[$each['parentid']]['location'] . ' ' . $allswitches[$each['parentid']]['ip'];

                            if ((!isset($deadarr[$each['ip']])) and (!isset($deadarr[$allswitches[$each['parentid']]['ip']]))) {
                                $color = '#00FF00';
                            } else {
                                $color = '#FF0000';
                            }

                            if (($each['id'] == $switchId) or ($each['parentid'] == $switchId)) {
                                $width = 5;
                            } else {
                                $width = 3;
                            }
                            $result .= sm_MapAddLine($coord1, $coord2, $color, $hint, $width);
                        }
                    }
                }
            }
        }
    }

    return ($result);
}

/**
 * Returns indications point to nuclear strikes :)
 * 
 * @return string 
 */
function sm_MapDrawSwitchesCoverage() {
    $query = "SELECT * from `switches` WHERE `geo` != '' ";
    $allswitches = simple_queryall($query);
    $result = '';
    if (!empty($allswitches)) {
        foreach ($allswitches as $io => $each) {
            $geo = mysql_real_escape_string($each['geo']);
            $result .= sm_MapAddCircle($geo, '100');
        }
    }
    return ($result);
}

/**
 * Returns full map marks for switches with filled GEO field
 * 
 * @return string
 *  
 */
function sm_MapDrawSwitches() {
    global $ubillingConfig;
    
    $switchesDb=new NyanORM('switches');
    $switchesDb->where('geo', '!=', '');
    $allswitches=$switchesDb->getAll();

    $uplinkTraceIcon = wf_img('skins/ymaps/uplinks.png', __('Show links'));
    $switchEditIcon = wf_img('skins/icon_edit.gif', __('Edit'));
    $switchPollerIcon = wf_img('skins/snmp.png', __('SNMP query'));
    $switchLocatorIcon = wf_img('skins/icon_search_small.gif', __('Zoom in'));

    $footerDelimiter = wf_tag('br');
    $result = '';
    //dead switches detection
    $dead_raw = zb_StorageGet('SWDEAD');
    $deadarr = array();
    if ($dead_raw) {
        $deadarr = unserialize($dead_raw);
    }
    

    if (!empty($allswitches)) {
        foreach ($allswitches as $io => $each) {
            $geo = mysql_real_escape_string($each['geo']);
            $title = mysql_real_escape_string($each['ip']);

            //switch hint content
            $content = mysql_real_escape_string($each['location']);
            if (empty($content)) {
                $content = __('No location set');
            }


            $iconlabel = '';

            if (!isset($deadarr[$each['ip']])) {
                if (ispos($each['desc'], 'NP')) {
                    $footer = __('Switch') . ': '.__('Status').' '.__('Unknown');
                    $icon = sm_MapNPIcon(false);
                } else {
                    $footer = __('Switch alive');
                    $icon = sm_MapGoodIcon(false);
                }
            } else {
                $footer = __('Switch dead');
                $icon = sm_MapBadIcon(false);
            }

            if (!empty($each['location'])) {
                $iconlabel = $each['location'];
            } else {
                $iconlabel = $each['ip'];
            }

            //switch footer controls
            $footer .= $footerDelimiter;
            $footer .= wf_tag('a', false, '', 'href="?module=switches&edit=' . $each['id'] . '"') . $switchEditIcon . wf_tag('a', true) . ' ';


            if (!empty($each['snmp'])) {
                $footer .= wf_tag('a', false, '', 'href="?module=switchpoller&switchid=' . $each['id'] . '"') . $switchPollerIcon . wf_tag('a', true) . ' ';
            }

            $footer .= wf_tag('a', false, '', 'href="?module=switchmap&finddevice=' . $each['geo'] . '"') . $switchLocatorIcon . wf_tag('a', true) . ' ';


            if (!empty($each['parentid'])) {
                $uplinkTraceUrl = '?module=switchmap&finddevice=' . $each['geo'] . '&showuplinks=true&traceid=' . $each['id'];
                $uplinkTraceLink = wf_tag('a', false, '', 'href="' . $uplinkTraceUrl . '"') . $uplinkTraceIcon . wf_tag('a', true) . ' ';
                $footer .= $uplinkTraceLink;
            }

         
            $result .= sm_MapAddMark($geo, $title, $content, $footer, $icon, $iconlabel, true);
        }
    }
    return ($result);
}

/**
 * Returns full map marks for builds with filled GEO field
 * 
 * @param int $buildIdFilter return only one build placemark
 * 
 * @return string
 */
function um_MapDrawBuilds($buildIdFilter = '') {
    global $ubillingConfig;
    $result = '';
    $allUserData=zb_UserGetAllDataCache();
    $buildIdFilter = ubRouting::filters($buildIdFilter, 'int');
    $defferedLoading = ($ubillingConfig->getAlterParam('BUILDMAP_DEFERRED')) ? true : false;
    if ($defferedLoading) {
        if (!function_exists('generic_MapAddMarkDynamic')) {
            $defferedLoading = false;
        }
    }
    $query = "SELECT * from `build` WHERE `geo` != '' ";
    //optional filter here
    if ($buildIdFilter) {
        $query .= " AND `id`='" . $buildIdFilter . "'";
    }
    $allbuilds = simple_queryall($query);
    $allstreets = zb_AddressGetStreetAllData();
    $alluserips = zb_UserGetAllIPs();
    $streetData = array();

    $cache = new UbillingCache();
    $cacheTime = 3600;
    //reading cached data
    $cachedData = $cache->get('INBUILDUSERS', $cacheTime);
    if (empty($cachedData)) {
        $cachedData = array();
        $updateCache = true;
    } else {
        $updateCache = false;
    }

    //street id => streetname
    if (!empty($allstreets)) {
        foreach ($allstreets as $ia => $eachstreet) {
            $streetData[$eachstreet['id']] = $eachstreet['streetname'];
        }
    }

    //get apts in all builds aggregated with users logins
    $aptData = array();
    $allapts_q = "SELECT `buildid`,`apt`,`login` from `apt` JOIN `address` ON `apt`.`id`=`address`.`aptid`";
    $allapts = simple_queryall($allapts_q);
    if (!empty($allapts)) {
        $aptData = $allapts;
    }

    //get all Online users if available
    $dnUsers = rcms_scandir('content/dn');
    if (!empty($dnUsers)) {
        $dnUsers = array_flip($dnUsers);
    }

    if (!empty($allbuilds)) {
        foreach ($allbuilds as $io => $each) {
            $geo = mysql_real_escape_string($each['geo']);
            @$streetname = $streetData[$each['streetid']];
            $title = wf_Link("?module=builds&action=editbuild&frommaps=true&streetid=" . $each['streetid'] . "&buildid=" . $each['id'], $streetname . ' ' . $each['buildnum'], false);

            $content = '';
            $cells = wf_TableCell(__('apt.'));
            $cells .= wf_TableCell(__('User'));
            $cells .= wf_TableCell(__('Active'));
            $cells .= wf_TableCell(__('Online'));
            $rows = wf_tag('tr', false, 'row1', 'bgcolor=#DCDCDC') . $cells . wf_tag('tr', true);
            $iconlabel = '';
            $footer = '';

            $onlineUsers = 0;
            $activeUsers = 0;
            $usersCount = 0;
            if (!empty($aptData)) {
                //is current build in cache
                if (isset($cachedData[$each['id']])) {
                    $updateCache = false;
                } else {
                    $updateCache = true;
                }
                //cache in actual state
                if (!$updateCache) {
                    //build extracted from cache
                    $cachePrev = $cachedData[$each['id']];

                    $rows = $cachePrev['rows'];
                    $usersCount = @$cachePrev['userscount'];
                    $onlineUsers = @$cachePrev['onlineusers'];
                    $activeUsers = @$cachePrev['activeusers'];
                } else {
                    //all cache need to be updated
                    foreach ($aptData as $ib => $eachapt) {
                        if ($eachapt['buildid'] == $each['id']) {
                            if (isset($alluserips[$eachapt['login']])) {
                                $usersCount++;
                                $userLogin = $eachapt['login'];
                                $userIp = $alluserips[$eachapt['login']];

                                //online flag
                                if (isset($dnUsers[$userLogin])) {
                                    $onlineFlag = web_bool_star(true);
                                    $onlineUsers++;
                                    $onlineKey = 'l';
                                } else {
                                    $onlineFlag = web_bool_star(false);
                                    $onlineKey = 'd';
                                }

                                //activity flag
                                $activeFlag = web_bool_led(false);
                                $activeKey = '0';

                                if (isset($allUserData[$userLogin])) {
                                   $activityState=zb_UserIsAlive($allUserData[$userLogin]);
                                   switch ($activityState) {
                                    case -1:
                                        $activeFlag = web_yellow_led();
                                        $activeKey = '-1';
                                        break;
                                    case 1:
                                        $activeFlag = web_bool_led(true);
                                        $activeKey = '1';
                                        $activeUsers++;
                                        break;
                                    case 0:
                                        $activeFlag = web_bool_led(false);
                                        $activeKey = '0';
                                        break;
                                }

                                } 


                                $cells = wf_TableCell($eachapt['apt']);
                                $cells .= wf_TableCell(wf_Link('?module=userprofile&username=' . $userLogin, $userIp, false));
                                $cells .= wf_TableCell($activeFlag, '', '', 'sorttable_customkey="' . $activeKey . '"');
                                $cells .= wf_TableCell($onlineFlag, '', '', 'sorttable_customkey="' . $onlineKey . '"');
                                $rows .= wf_TableRow($cells, 'row5');
                            }
                        }
                    }

                    $cachedData[$each['id']]['rows'] = $rows;
                    $cachedData[$each['id']]['userscount'] = $usersCount;
                    $cachedData[$each['id']]['onlineusers'] = $onlineUsers;
                    $cachedData[$each['id']]['activeusers'] = $activeUsers;
                }
            }

            $footer = __('Active').'/'.__('Online').'/'.__('Total').': ' . $activeUsers . '/' . $onlineUsers . '/' . $usersCount;
            
            $icon = um_MapBuildIcon($usersCount);

            $content = json_encode(wf_TableBody($rows, '', 0));
            $title = json_encode($title);

            $content = str_replace('"', '', $content);
            $content = str_replace("'", '', $content);
            $content = str_replace("\n", '', $content);

            $title = str_replace('"', '', $title);
            $title = str_replace("'", '', $title);
            $title = str_replace("\n", '', $title);

            if ($defferedLoading) {
                $result .= generic_MapAddMarkDynamic($geo, $title, '?module=usersmap&getbuildusers=' . $each['id'], $icon);
            } else {
                $result .= sm_MapAddMark($geo, $title, $content, $footer, $icon, $iconlabel, true);
            }
        }

        //update cache data if required
        if ($updateCache) {
            $cache->set('INBUILDUSERS', $cachedData, $cacheTime);
        }
    }
    return ($result);
}

/**
 * Retrieves and formats building data including address and user statistics
 * 
 * This function gets building information from cache and formats it with address,
 * user table data and statistics about active/total users.
 *
 * @param mixed $buildId Building ID to retrieve data for
 * 
 * @return string 
 */
function um_GetBuildData($buildId) {
    $buildId = ubRouting::filters($buildId, 'int');
    $result = 'Oo';
    $cache = new UbillingCache();
    $cacheTime = 3600;
    $cachedData = $cache->get('INBUILDUSERS', $cacheTime);
    if (is_array($cachedData) and !empty($cachedData)) {
        if (isset($cachedData[$buildId])) {
            $result = '';
            $allBuildsAddress = zb_AddressGetBuildAllAddress(false);
            if (isset($allBuildsAddress[$buildId])) {
                $result .= wf_tag('b') . $allBuildsAddress[$buildId] . wf_tag('b', true);
            }
            $buildData = $cachedData[$buildId];
            $result .= wf_TableBody($buildData['rows'], '', 0);
            $result .= wf_delimiter(0);
            $result .= __('Active') . '/' . __('Online') . '/' . __('Total') . ': ' . @$buildData['activeusers'] . '/' . @$buildData['onlineusers'] . '/' . @$buildData['userscount'];
        }
    }

    return ($result);
}

/**
 * Returns build icon class 
 * 
 * @param int $usersCount - count of users in building
 * 
 * @return string
 */
function um_MapBuildIcon($usersCount) {
    if ($usersCount < 3) {
        $iconClass = 'twirl#houseIcon';
    } else {
        $iconClass = 'twirl#buildingsIcon';
    }

    if ($usersCount == 0) {
        $iconClass = 'twirl#campingIcon';
    }
    return ($iconClass);
}

/**
 * Returns bad icon class
 * 
 * @param bool $stretchy - icon resizable by content?
 * 
 * @return string
 */
function sm_MapBadIcon($stretchy = true) {
    if ($stretchy) {
        return ('twirl#redStretchyIcon');
    } else {
        return ('twirl#redIcon');
    }
}

/**
 * Returns good icon class
 * 
 * @param bool $stretchy - icon resizable by content?
 * 
 * @return string
 */
function sm_MapGoodIcon($stretchy = true) {
    if ($stretchy) {
        return ('twirl#lightblueStretchyIcon');
    } else {
        return ('twirl#lightblueIcon');
    }
}

/**
 * Returns NP (unknown) icon class
 * 
 * @param bool $stretchy - icon resizable by content?
 * 
 * @return string
 */
function sm_MapNPIcon($stretchy = true) {
    if ($stretchy) {
        return ('twirl#nightDotIcon');
    } else {
        return ('twirl#nightDotIcon');
    }
}

/**
 * Returns form for placing switch to selected coordinates
 * 
 * @return string
 */
function um_MapLocationBuildForm() {
    $query = "SELECT * from `build` WHERE `geo` IS NULL OR `geo`='' ORDER by `streetid`";
    $allNoGeoBuilds = simple_queryall($query);
    $buildData = array();
    $streetData = array();
    $cityData = array();
    $result = '';

    $selectedBuild = (wf_CheckGet(array('placebld'))) ? vf($_GET['placebld'], 3) : '';

    if (!empty($allNoGeoBuilds)) {
        $allCities = zb_AddressGetFullCityNames();
        $allStreets = zb_AddressGetStreetAllData();
        if (!empty($allStreets)) {
            foreach ($allStreets as $ia => $eachstreet) {
                $streetData[$eachstreet['id']] = $eachstreet['streetname'];
                if (isset($allCities[$eachstreet['cityid']])) {
                    $cityData[$eachstreet['id']] = $allCities[$eachstreet['cityid']];
                }
            }
        }

        foreach ($allNoGeoBuilds as $io => $each) {
            @$streetname = $streetData[$each['streetid']];
            $streetcity = (isset($cityData[$each['streetid']])) ? $cityData[$each['streetid']] . ' ' : '';
            $buildData[$each['id']] = $streetcity . $streetname . ' - ' . $each['buildnum'];
        }
        //form construct
        if (cfr('BUILDS')) {
            $inputs = wf_Selector('buildplacing', $buildData, '', $selectedBuild, true);
            $inputs .= wf_Submit('Save');
            $result .= $inputs;
        }
    }
    return ($result);
}

/**
 * Returns form for placing switch to selected coordinates
 * 
 * @return string
 */
function sm_MapLocationSwitchForm() {
    $query = "SELECT * from `switches` WHERE `geo`='' AND `desc` NOT LIKE '%NP%'";
    $allNoGeoSwitches = simple_queryall($query);
    $switchData = array();
    $result = '';

    if (!empty($allNoGeoSwitches)) {
        foreach ($allNoGeoSwitches as $io => $each) {
            $cleanLocation = str_replace("'", '`', $each['location']);
            $switchData[$each['id']] = $each['ip'] . ' - ' . $cleanLocation;
        }
        //form construct
        if (cfr('SWITCHESEDIT')) {
            //preselect some switch if required
            if (wf_CheckGet(array('placesw'))) {
                $selected = $_GET['placesw'];
            } else {
                $selected = '';
            }
            $inputs = wf_Selector('switchplacing', $switchData, '', $selected, true);
            $inputs .= wf_Submit('Save');
            $result .= $inputs;
        }
    }
    return ($result);
}

/**
 * Returns map mark
 * 
 * @param $coords - map coordinates
 * @param $title - ballon title
 * @param $content - ballon content
 * @param $footer - ballon footer content
 * @param $icon - YM icon class
 * @param $iconlabel - icon label string
 * @param $canvas - is canvas rendering enabled?
 * 
 * @return string
 */
function sm_MapAddMark($coords, $title = '', $content = '', $footer = '', $icon = 'twirl#lightblueIcon', $iconlabel = '', $canvas = false) {
    return (generic_MapAddMark($coords, $title, $content, $footer, $icon, $iconlabel, $canvas));
}

/**
 * Returns map circle
 * 
 * @param string $coords
 * @param int $radius
 * @param string $content
 * @param string $hint
 * 
 * @return string
 */
function sm_MapAddCircle($coords, $radius, $content = '', $hint = '') {
    return (generic_MapAddCircle($coords, $radius, $content, $hint));
}

/**
 * Returns JS code to draw line within two points
 * 
 * @param string $coord1
 * @param string $coord2
 * @param string $color
 * @param string $hint
 * 
 * @return string
 */
function sm_MapAddLine($coord1, $coord2, $color = '', $hint = '', $width = '') {
    return (generic_MapAddLine($coord1, $coord2, $color, $hint, $width));
}


/**
 * Return geo coordinates locator for builds
 * 
 * @return string
 */
function um_MapLocationFinder() {
    $title = wf_tag('b') . __('Place coordinates') . wf_tag('b', true);
    $data = um_MapLocationBuildForm();
    $result = generic_MapEditor('placecoords', $title, $data);
    return ($result);
}

/**
 * Returns geo coordinates locator
 * 
 * @return string
 */
function sm_MapLocationFinder() {
    $title = wf_tag('b') . __('Place coordinates') . wf_tag('b', true);
    $data = sm_MapLocationSwitchForm();
    $result = generic_MapEditor('placecoords', $title, $data);
    return ($result);
}

/**
 * Shows map container
 *
 * @return void
 *  
 */
function sm_ShowMapContainer() {
    $container = wf_tag('div', false, '', 'id="ubmap" style="width: 1000; height:800px;"');
    $container .= wf_tag('div', true);
    $controls = '';
    if (cfr('SWITCHMAP')) {
        $controls .= wf_Link("?module=switchmap", wf_img('skins/ymaps/network.png') . ' ' . __('Switches map'), false, 'ubButton');
    }
    if (cfr('USERSMAP')) {
        $controls .= wf_Link("?module=usersmap", wf_img('skins/ymaps/build.png') . ' ' . __('Builds map'), false, 'ubButton');
    }
    if (cfr('SWITCHESEDIT')) {
        $controls .= wf_Link("?module=switchmap&locfinder=true", wf_img('skins/ymaps/edit.png') . ' ' . __('Edit map'), false, 'ubButton');
    }
    $controls .= wf_Link("?module=switchmap&showuplinks=true", wf_img('skins/ymaps/uplinks.png') . ' ' . __('Show links'), false, 'ubButton');
    //$controls .= wf_Link("?module=switchmap&coverage=true", wf_img('skins/ymaps/coverage.png') . ' ' . __('Coverage area'), false, 'ubButton');
    if (cfr('SWITCHES')) {
        $controls .= wf_Link("?module=switches", wf_img('skins/ymaps/switchdir.png') . ' ' . __('Available switches'), false, 'ubButton');
    }
    $controls .= wf_delimiter(1);

    show_window(__('Active equipment map'), $controls . $container);
}

/**
 * Shows map container for builds
 *
 * @return void
 */
function um_ShowMapContainer() {
    $container = wf_tag('div', false, '', 'id="ubmap" style="width: 1000; height:800px;"');
    $container .= wf_tag('div', true);
    $controls = '';
    if (cfr('SWITCHMAP')) {
        $controls .= wf_Link("?module=switchmap", wf_img('skins/ymaps/network.png') . ' ' . __('Switches map'), false, 'ubButton');
    }
    if (cfr('USERSMAP')) {
        $controls .= wf_Link("?module=usersmap", wf_img('skins/ymaps/build.png') . ' ' . __('Builds map'), false, 'ubButton');
    }
    if (cfr('BUILDS')) {
        $controls .= wf_Link("?module=usersmap&locfinder=true", wf_img('skins/ymaps/edit.png') . ' ' . __('Edit map'), false, 'ubButton');
    }
    $controls .= wf_delimiter(1);

    show_window(__('Builds and users map'), $controls . $container);
}
