function guifi_devices_select($filters, $action = '')
{
    guifi_log(GUIFILOG_TRACE, 'function guifi_devices_select()', $filters);
    $var = array();
    $found = FALSE;
    if ($filters['type'] == 'cable') {
        if ($filters['mode'] != 'cable-router') {
            $query = sprintf("\n        SELECT\n          l.lat, l.lon, r.nick ssid, r.id, r.nid, z.id zone_id\n        FROM {guifi_devices} r,{guifi_location} l, {guifi_zone} z\n        WHERE\n          l.id=%d\n          AND r.nid=l.id\n          AND l.zone_id=z.id", $filters['from_node']);
        } else {
            $query = sprintf("\n        SELECT\n          l.lat, l.lon, r.nick ssid, r.id r.nid, z.id zone_id, r.type,\n          r.fund_required, r.fund_amount, r.fund_currency\n        FROM {guifi_devices} r,{guifi_location} l, {guifi_zone} z\n        WHERE r.type IN ('radio','nat')\n          AND l.id=%d AND r.nid=l.id\n          AND l.zone_id=z.id", $filters['from_node']);
        }
    } else {
        $query = sprintf("\n      SELECT\n        l.lat, l.lon, r.id, r.clients_accepted, r.nid, z.id zone_id,\n        r.radiodev_counter, r.ssid, r.mode, r.antenna_mode,\n        r.fund_required, r.fund_amount, r.fund_currency\n      FROM {guifi_radios} r,{guifi_location} l, {guifi_zone} z\n      WHERE l.id<>%d\n        AND r.nid=l.id\n        AND l.zone_id=z.id", $filters['from_node']);
    }
    $devdist = array();
    $devarr = array();
    $k = 0;
    $devsq = db_query($query);
    while ($device = db_fetch_object($devsq)) {
        $k++;
        $l = FALSE;
        if ($filters['type'] != 'cable') {
            $oGC = new GeoCalc();
            $node = db_fetch_object(db_query('
        SELECT lat, lon
        FROM {guifi_location}
        WHERE id=%d', $filters['from_node']));
            $distance = round($oGC->EllipsoidDistance($device->lat, $device->lon, $node->lat, $node->lon), 3);
            if ($distance > $filters['dmax'] or $distance < $filters['dmin']) {
                continue;
            }
            if ($filters['azimuth']) {
                foreach (explode('-', $filters['azimuth']) as $minmax) {
                    list($min, $max) = explode(',', $minmax);
                    $Az = round($oGC->GCAzimuth($device->lat, $device->lon, $node->lat, $node->lon));
                    if ($Az <= $max and $Az >= $min) {
                        $l = TRUE;
                    }
                }
            } else {
                $l = TRUE;
            }
        }
        if ($l) {
            $devdist[$k] = $distance;
            $devarr[$k] = $device;
            $devarr[$k]->distance = $distance;
        }
    }
    asort($devdist);
    //  ob_start();
    //  print "Query: $query \n<br />";
    //  print_r($devdist);
    //  $txt = ob_get_contents();
    //  ob_end_clean();
    if (!empty($devdist)) {
        foreach ($devdist as $id => $foo) {
            $device = $devarr[$id];
            switch ($filters['type']) {
                case 'ap/client':
                    if ($filters['mode'] == 'ap' and $device->mode == 'client') {
                        $cr = guifi_count_radio_links($device->id);
                        if ($cr['ap'] < 1) {
                            _set_value($device, $node, $var, $filters['from_device'], $filters['from_radio'], $filters['search']);
                        }
                    } else {
                        if ($filters['mode'] == 'client' and $device->mode == 'ap') {
                            _set_value($device, $node, $var, $filters['from_device'], $filters['from_radio'], $filters['search']);
                        }
                    }
                    break;
                case 'wds':
                    if ($device->mode == 'ap') {
                        _set_value($device, $node, $var, $filters['from_device'], $filters['from_radio'], $filters['search']);
                    }
                    break;
                case 'cable':
                    _set_value($device, $node, $var, $filters['from_device'], $filters['from_radio'], $filters['search']);
                    break;
            }
            // eof switch link_type
        }
    }
    // eof while query device,node,zone
    $form = array('#type' => 'fieldset', '#collapsible' => FALSE, '#collapsed' => FALSE, '#prefix' => '<div id="list-devices">', '#suffix' => '</div>');
    if (count($var) == 0) {
        $form['d'] = array('#type' => 'item', '#parents' => array('dummy'), '#title' => t('No devices available'), '#value' => t('There are no devices to link within the given criteria, you can use the filters to get more results.'));
        $form['dbuttons'] = guifi_device_buttons(TRUE, $action, 0);
        return $form;
    }
    $form['d'] = array('#type' => 'radios', '#parents' => array('linked'), '#title' => t('select the device which do you like to link with'), '#options' => $var, '#attributes' => array('class' => 'required'));
    $form['dbuttons'] = guifi_device_buttons(TRUE, $action, 1);
    return $form;
}
function guifi_device_form($form_state, $params = array())
{
    global $user;
    $form = array();
    //$form['#suffix'] = '<script type="text/javascript">'
    //               . 'jQuery(\'input#edit-funders-0-user\').focus();'
    //               . '</script>';
    guifi_log(GUIFILOG_TRACE, 'function guifi_device_form()', $params);
    // Local javascript validations not actve because of bug in Firefox
    // Errors are not displayed when fieldset folder is collapsed
    // guifi_validate_js("#guifi-device-form");
    // $form['#attributes'] = array('onsubmit' => 'kk');
    if (empty($form_state['values'])) {
        $form_state['values'] = $params;
    }
    $form_state['#redirect'] = FALSE;
    // if new device, initializing variables
    if ($form_state['values']['nid'] == NULL && $params['add'] != NULL) {
        $form_state['values']['nid'] = $params['add'];
        $form_state['values']['new'] = TRUE;
        $form_state['values']['type'] = $params['type'];
        $form_state['values']['links'] = array();
        $form_state['values']['netmask'] = '255.255.255.224';
        if ($form_state['values']['type'] == 'radio') {
            $form_state['values']['variable']['firmware_id'] = '23';
            $form_state['values']['variable']['model_id'] = '70';
        }
    }
    drupal_set_breadcrumb(guifi_node_ariadna($form_state['values']['nid']));
    // Check permissions
    if ($params['edit']) {
        if (!guifi_device_access('update', $params['edit'])) {
            drupal_set_message(t('You are not authorized to edit this device', 'error'));
            return;
        }
    }
    // Loading node & zone where the device belongs to (some information will be used)
    $node = node_load(array('nid' => $form_state['values']['nid']));
    $zone = node_load($node->zone_id);
    // Setting the breadcrumb
    drupal_set_breadcrumb(guifi_node_ariadna($form_state['values']['nid']));
    // if contact is NULL, then get it from the node or the user logged in drupal
    if (is_null($form_state['values']['notification'])) {
        if (guifi_notification_validate($node->notification)) {
            $form_state['values']['notification'] = $node->notification;
        } else {
            drupal_set_message(t('The node has not a valid email address as a contact. Using your email as a default. Change the contact mail address if necessary.'));
            $form_state['values']['notification'] = $user->mail;
        }
    }
    // if nick is NULL, get a default name
    if ($form_state['values']['nick'] == "") {
        $form_state['values']['nick'] = guifi_device_get_default_nick($node, $form_state['values']['type'], $form_state['values']['nid']);
    }
    if (isset($form_state['action'])) {
        guifi_log(GUIFILOG_TRACE, 'action', $form_state['action']);
        if (function_exists($form_state['action'])) {
            if (!call_user_func_array($form_state['action'], array(&$form, &$form_state))) {
                return $form;
            }
        }
    }
    $form_weight = 0;
    if ($form_state['values']['id']) {
        $form['id'] = array('#type' => 'hidden', '#name' => 'id', '#value' => $form_state['values']['id'], '#weight' => $form_weight++);
    } else {
        $form['new'] = array('#type' => 'hidden', '#name' => 'new', '#weight' => $form_weight++, '#value' => TRUE);
    }
    $form['type'] = array('#type' => 'hidden', '#name' => 'type', '#weight' => $form_weight++, '#value' => $form_state['values']['type']);
    if ($params['add'] != NULL) {
        drupal_set_title(t('adding a new %device at %node', array('%node' => $node->nick, '%device' => $form_state['values']['type'])));
    } else {
        drupal_set_title(t('edit device %dname', array('%dname' => $form_state['values']['nick'])));
    }
    // All preprocess is complete, now going to create the form
    $form['main'] = array('#type' => 'fieldset', '#title' => t('Device name, status and main settings') . ' (' . $form_state['values']['nick'] . ') - ' . $form_state['values']['flag'], '#weight' => $form_weight++, '#collapsible' => TRUE, '#attributes' => array('class' => 'fieldset-device-main'), '#collapsed' => is_null($params['edit']));
    $form['main']['movenode'] = array('#type' => 'textfield', '#title' => t('Node'), '#maxlength' => 60, '#weight' => $form_weight++, '#default_value' => $form_state['values']['nid'] . '-' . guifi_get_zone_nick(guifi_get_zone_of_node($form_state['values']['nid'])) . ', ' . guifi_get_nodename($form_state['values']['nid']), '#autocomplete_path' => 'guifi/js/select-node', '#element_validate' => array('guifi_nodename_validate'), '#description' => t('Select the node where the device is.<br />' . 'You can find the node by introducing part of the node id number, ' . 'zone name or node name. A list with all matching values ' . 'with a maximum of 50 values will be created.<br />' . 'You can refine the text to find your choice.'), '#prefix' => '<div class"form-newline">', '#suffix' => '</div>');
    $form['main']['nid'] = array('#type' => 'hidden', '#weight' => $form_weight++, '#value' => $form_state['values']['nid']);
    $form['main']['nick'] = array('#type' => 'textfield', '#size' => 20, '#maxlength' => 128, '#title' => t('nick'), '#required' => TRUE, '#attributes' => array('class' => 'required'), '#default_value' => $form_state['values']['nick'], '#weight' => $form_weight++, '#description' => t('The name of the device.<br />Used as a hostname, SSID, etc...'));
    $form['main']['flag'] = array('#type' => 'select', '#title' => t("Status"), '#required' => TRUE, '#default_value' => $form_state['values']['flag'], '#options' => guifi_types('status'), '#weight' => $form_weight++, '#description' => t("Current status of this device."));
    $form['main']['notification'] = array('#type' => 'textfield', '#size' => 60, '#maxlength' => 1024, '#title' => t('contact'), '#required' => TRUE, '#element_validate' => array('guifi_emails_validate'), '#default_value' => $form_state['values']['notification'], '#weight' => $form_weight++, '#description' => t('Mailid where changes on the device will be notified, ' . 'if many, separated by \',\'<br />' . 'used for network administration.'));
    if (!empty($form_state['values']['ipv4'])) {
        $form['main']['mainipv4'] = array('#type' => 'select', '#title' => t('Main IPv4'), '#options' => guifi_get_currentDeviceIpv4s($form_state['values']), '#default_value' => $form_state['values']['mainipv4'], '#weight' => $form_weight++, '#description' => t('Used for monitoring.<br>Save and continue to refresh available addresses'));
    }
    $form['main']['logserver'] = array('#type' => 'textfield', '#size' => 60, '#maxlength' => 60, '#title' => t('Log Server'), '#default_value' => $form_state['values']['logserver'], '#weight' => $form_weight++, '#description' => t('If you have a log server for mikrotik (dude), add your ip.'));
    $form['main']['graph_server'] = array('#type' => 'select', '#title' => t("Server which collects traffic and availability data"), '#required' => FALSE, '#default_value' => $node->graph_server ? $node->graph_server : 0, '#options' => array('0' => t('Default'), '-1' => t('None')) + guifi_services_select('SNPgraphs'), '#weight' => $form_weight++, '#description' => t("If not specified, inherits zone properties."));
    if (!user_access('administer guifi zones') || $device['user_created'] == $user->uid and $form_state['values']['type'] == 'radio') {
        $form['main']['graph_server']['#disabled'] = true;
        $form['main']['graph_server']['#description'] .= '<br>' . t('To change the value, you are required for maintainer privilege.');
    }
    /*
     * maintainers fieldset
     */
    $form['maintainers'] = guifi_maintainers_form(array2object($form_state['values']), $form_weight);
    guifi_log(GUIFILOG_TRACE, 'function guifi_device_form(maintainers)', $form_state['values']['maintainers']);
    /*
     * funders fieldset
     */
    $form['funders'] = guifi_funders_form(array2object($form_state['values']), $form_weight);
    guifi_log(GUIFILOG_TRACE, 'function guifi_device_form(funders)', $form_state['values']['funders']);
    guifi_log(GUIFILOG_TRACE, sprintf('function guifi_device_form(abans type)'), $form_weight);
    // create the device-type depenedent form
    // looking for a "guifi_"<device_type>"_form()" function
    if (function_exists('guifi_' . $form_state['values']['type'] . '_form')) {
        $form = array_merge($form, call_user_func_array('guifi_' . $form_state['values']['type'] . '_form', array($form_state['values'], &$form_weight)));
    }
    // Cable interfaces/networking
    guifi_log(GUIFILOG_TRACE, sprintf('function guifi_device_form(abans if cable links)'), $form_weight);
    $form['if'] = guifi_interfaces_cable_form($form_state['values'], $form_weight);
    $form['if']['#weight'] = $form_weight++;
    // Cable interfaces/ports
    guifi_log(GUIFILOG_TRACE, sprintf('function guifi_device_form(abans if ports)'), $form_weight);
    if (isset($form_state['values']['interfaces'])) {
        foreach ($form_state['values']['interfaces'] as $k => $v) {
            unset($form_state['values']['interfaces'][$k]['ipv4']);
        }
        guifi_log(GUIFILOG_TRACE, sprintf('function guifi_device_form(abans if ports)'), $form_state['values']['interfaces']);
        $form['interfaces'] = guifi_ports_form($form_state['values'], $form_weight);
        $form['interfaces']['#weight'] = $form_weight++;
    }
    // VLANs (VLans, VRRPs, WDS...)
    guifi_log(GUIFILOG_TRACE, sprintf('function guifi_device_form(abans if vLANs)'), $form_weight);
    $form['vlans'] = guifi_vinterfaces_form('vlans', $form_state['values'], $form_weight);
    $form['vlans']['#weight'] = $form_weight++;
    // Aggregations (Bridges & Bondings)
    guifi_log(GUIFILOG_TRACE, sprintf('function guifi_device_form(abans if Aggregations)'), $form_weight);
    $form['aggregations'] = guifi_vinterfaces_form('aggregations', $form_state['values'], $form_weight);
    $form['aggregations']['#weight'] = $form_weight++;
    // ipv4
    guifi_log(GUIFILOG_TRACE, sprintf('function guifi_device_form(abans if ipv4)'), $form_weight);
    $form['ipv4'] = guifi_ipv4s_form($form_state['values'], $form_weight);
    $form['ipv4']['#weight'] = $form_weight++;
    guifi_log(GUIFILOG_TRACE, sprintf('function guifi_device_form(abans comments)'), $form_weight);
    // Comments
    $form['comment'] = array('#type' => 'textarea', '#title' => t('Comments'), '#default_value' => $form_state['values']['comment'], '#description' => t('This text will be displayed as an information of the device.'), '#cols' => 60, '#rows' => 5, '#weight' => $form_weight++);
    guifi_log(GUIFILOG_TRACE, sprintf('function guifi_device_form(abans buttons)'), $form_weight);
    //  save/validate/reset buttons
    $form['dbuttons'] = guifi_device_buttons(FALSE, '', 0, $form_weight);
    $form['dbuttons']['#weight'] = $form_weight++;
    guifi_log(GUIFILOG_TRACE, sprintf('function guifi_device_form(form_final)'), $form);
    return $form;
}