<?php

/**
 * @file
 */

function stormperson_help($path, $arg) {
  $o = '';

  switch ($path) {
    case "admin/help#stormperson":
      $o = '<p>'. t("Provides person support for SuiteDesk") .'</p>';
      break;
  }

  return $o;
}

function stormperson_init() {
  if (function_exists('drupal_set_content')) {
    global $user;
    if ($user->uid && !isset($user->stormorganization_nid) || !isset($user->stormperson_nid)) {
      _stormperson_user_load($user);
    }
    if (!$user->uid || !isset($user->stormperson_nid)) {
      $user->stormperson_nid = -1;
    }
    if (!$user->uid || !isset($user->stormorganization_nid)) {
      $user->stormorganization_nid = -1;
    }
  }

  $settings = array(
    'storm' => array(
      'organization_people_url' => url('storm/organization_people_js/')
    ),
  );
  drupal_add_js($settings, 'setting');
  drupal_add_js(drupal_get_path('module', 'storm') .'/storm.js', 'module', 'header', FALSE);
  drupal_add_js(drupal_get_path('module', 'stormperson') .'/stormperson.js', 'module', 'header', FALSE);
}

function stormperson_perm() {
  return array(
    'Storm person: access',
    'Storm person: add',
    'Storm person: delete all',
    'Storm person: delete own',
    'Storm person: delete of user organization',
    'Storm person: delete when linked to own user account',
    'Storm person: edit all',
    'Storm person: edit own',
    'Storm person: edit of user organization',
    'Storm person: edit when linked to own user account',
    'Storm person: view all',
    'Storm person: view own',
    'Storm person: view of user organization',
    'Storm person: view when linked to own user account',
  );
}

function stormperson_access($op, $node, $account = NULL) {
  if (empty($account)) {
    global $user;
    $account = $user;
  }

  if ($op == 'create') {
    return user_access('Storm person: add');
  }

  if (is_numeric($node)) {
    $node = node_load($node);
  }

  if ($op == 'delete') {
    if (user_access('Storm person: delete all')) {
      return TRUE;
    }
    elseif (user_access('Storm person: delete own') && ($account->uid == $node->uid)) {
      return TRUE;
    }
    elseif (user_access('Storm person: delete of user organization') && ($account->stormorganization_nid == $node->organization_nid)) {
      return TRUE;
    }
    elseif (user_access('Storm person: delete when linked to own user account') && ($account->uid == $node->user_uid)) {
      return TRUE;
    }
  }

  if ($op == 'update') {
    if (user_access('Storm person: edit all')) {
      return TRUE;
    }
    elseif (user_access('Storm person: edit own') && ($account->uid == $node->uid)) {
      return TRUE;
    }
    elseif (user_access('Storm person: edit of user organization') && ($account->stormorganization_nid == $node->organization_nid)) {
      return TRUE;
    }
    elseif (user_access('Storm person: edit when linked to own user account') && ($account->uid == $node->user_uid)) {
      return TRUE;
    }
  }

  if ($op == 'view') {
    if (user_access('Storm person: view all')) {
      return TRUE;
    }
    elseif (user_access('Storm person: view own') && ($account->uid == $node->uid)) {
      return TRUE;
    }
    elseif (user_access('Storm person: view of user organization') && ($account->stormorganization_nid == $node->organization_nid)) {
      return TRUE;
    }
    elseif (user_access('Storm person: view when linked to own user account') && ($account->uid == $node->user_uid)) {
      return TRUE;
    }
  }

  return FALSE;
}

function stormperson_access_sql($sql, $where = array()) {
  if (!user_access('Storm person: view all')) {
    global $user;

    $cond = '';
    if (user_access('Storm person: view own')) {
      $cond .= 'n.uid = ' . $user->uid;
    }
    if (user_access('Storm person: view of user organization')) {
      $cond .= !empty($cond) ? ' OR ' : '';
      $cond .= 'spe.organization_nid = ' . $user->stormorganization_nid;
    }
    if (user_access('Storm person: view when linked to own user account')) {
      $cond .= !empty($cond) ? ' OR ' : '';
      $cond .= 'spe.user_uid = ' . $user->uid;
    }
    $where[] = empty($cond) ? '0 = 1' : $cond;
  }

  $where[] = "'storm_access' = 'storm_access'";
  return storm_rewrite_sql($sql, $where);
}

function stormperson_storm_rewrite_where_sql($query, $primary_table, $account) {
  static $conds = array();

  if (isset($conds[$primary_table][$account->uid])) {
    return $conds[$primary_table][$account->uid];
  }

  $cond = '';
  if (!preg_match("/'storm_access' = 'storm_access'/", $query)) {
    if (user_access('Storm person: view all', $account)) {
      return '';
    }
    if (user_access('Storm person: view own', $account)) {
      $cond .= " ${primary_table}.uid = " . $account->uid;
    }
    if (user_access('Storm person: view of user organization', $account)) {
      $cond .= !empty($cond) ? ' OR ' : '';
      # If function is called without viewing an organization, this variable
      # may not be set. These lines check for that and set the organization
      # node id to zero if not otherwise set.
      if (!isset($account->stormorganization_nid)) {
        $account->stormorganization_nid = 0;
      }
      $cond .= ' spe1.organization_nid = ' . $account->stormorganization_nid;
    }
    if (user_access('Storm person: view when linked to own user account', $account)) {
      $cond .= !empty($cond) ? ' OR ' : '';
      $cond .= ' spe1.user_uid = ' . $account->uid;
    }
    if ($cond) {
      $cond = " WHEN 'stormperson' THEN (SELECT IF($cond, 1, 0) FROM {stormperson} spe1 WHERE spe1.vid = ${primary_table}.vid) ";
    }
    else {
      $cond = " WHEN 'stormperson' THEN 0 ";
    }
  }
  $conds[$primary_table][$account->uid] = $cond;
  return $cond;
}

function stormperson_menu() {
  $items['people'] = array(
    'title' => 'People',
    'description' => 'SuiteDesk people',
    'page callback' => 'stormperson_list',
    'access arguments' => array('Storm person: access'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'stormperson.admin.inc',
    'weight' => 1,
  );

  $items['storm/organization_people_js/%'] = array(
    'title' => 'People',
    'page callback' => '_stormperson_organization_people_js',
    'page arguments' => array(2),
    'access callback' => TRUE,
    'file' => 'stormperson.admin.inc',
    'type' => MENU_CALLBACK,
  );

  $items['storm/stormperson_js'] = array(
    'title' => 'Stormperson - User autocomplete',
    'page callback' => 'stormperson_user_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array('access user profiles'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function stormperson_theme() {
  return array(
    'stormperson_list' => array(
      'file'      => 'stormperson.theme.inc',
      'arguments' => array('header', 'people'),
    ),
    'stormperson_people' => array(
      'file'      => 'stormperson.theme.inc',
      'arguments' => array('header', 'people'),
    ),
    'stormperson_view' => array(
      'file'      => 'stormperson.theme.inc',
      'arguments' => array('node', 'teaser', 'page'),
    ),
  );
}

function stormperson_node_info() {
  return array(
    'stormperson' => array(
      'name' => t('Person'),
      'module' => 'stormperson',
      'description' => t("A person for SuiteDesk."),
      'title_label' => t("Name"),
      'body_label' => t("Description"),
    )
  );
}

function stormperson_content_extra_fields($type_name) {
  if ($type_name == 'stormperson') {
    return array(
      'group1' => array('label' => 'Prefix/Name Group', 'weight' => -20),
      'group2' => array('label' => 'Organization/User Group', 'weight' => -19),
      'group3' => array('label' => 'Email/WWW Group', 'weight' => -18),
      'group4' => array('label' => 'Phone/IM Group', 'weight' => -17),
    );
  }
}

function stormperson_stormorganization_change($organization_nid, $organization_title) {
  $s = "UPDATE {stormperson} SET organization_title='%s' WHERE organization_nid=%d AND organization_title <> '%s'";
  db_query($s, $organization_title, $organization_nid, $organization_title);
}

function stormperson_form(&$node) {
  $breadcrumb = array();
  $breadcrumb[] = l(t('SuiteDesk'), 'dashboard');
  $breadcrumb[] = l(t('People'), 'people');
  drupal_set_breadcrumb($breadcrumb);

  if (arg(1)=='add') {
    if (array_key_exists('organization_nid', $_GET) && !$node->organization_nid) {
      $node->organization_nid = $_GET['organization_nid'];
    }

    if (!empty($_SESSION['stormperson_list_filter']['organization_nid']) && !$node->organization_nid) {
      $node->organization_nid = $_SESSION['stormperson_list_filter']['organization_nid'];
    }
  }

  $type = node_get_types('type', $node);

  $form['#attributes']['class'] = 'stormcomponent_node_form';

  $form['group1'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
    '#weight' => module_exists('content') ? content_extra_field_weight($node->type, 'group1') : -20,
  );

  $form['group1']['prefix'] = array(
    '#type' => 'textfield',
    '#title' => t('Prefix'),
    '#size' => 20,
    '#default_value' => isset($node->prefix) ? $node->prefix : '',
  );

  $form['group1']['title'] = array(
    '#type' => 'textfield',
    '#title' => check_plain($type->title_label),
    '#required' => TRUE,
    '#default_value' => $node->title,
    '#size' => 40,
  );

  $form['group2'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
    '#weight' => module_exists('content') ? content_extra_field_weight($node->type, 'group2') : -19,
  );

  $s = "SELECT n.nid, n.title FROM {node} AS n INNER JOIN {stormorganization} AS sor ON sor.vid=n.vid WHERE n.status=1 AND n.type='stormorganization' ORDER BY n.title";
  $s = stormorganization_access_sql($s);
  $s = db_rewrite_sql($s);
  $r = db_query($s);
  $organizations = array();
  while ($organization = db_fetch_object($r)) {
    $organizations[$organization->nid] = $organization->title;
    if (!isset($node->organization_nid)) $node->organization_nid = $organization->nid;
  }
  $form['group2']['organization_nid'] = array(
    '#type' => 'select',
    '#title' => t('Organization'),
    '#default_value' => $node->organization_nid,
    '#options' => $organizations,
    '#required' => TRUE,
    '#attributes' => array('onchange' => "stormperson_organization_project_tasks(this, 'edit-project-nid', 'edit-parent-nid', true, '-')"),
  );

  $form['group2']['user_name'] = array(
    '#type' => 'textfield',
    '#title' => t('User'),
    '#default_value' => isset($node->user_name) ? $node->user_name : '',
    '#autocomplete_path' => 'storm/stormperson_js',
    '#size' => 40,
  );

  $form['group3'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
    '#weight' => module_exists('content') ? content_extra_field_weight($node->type, 'group3') : -18,
  );

  $form['group3']['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
    '#size' => 30,
    '#default_value' => isset($node->email) ? $node->email : '',
  );

  $form['group3']['www'] = array(
    '#type' => 'textfield',
    '#title' => t('WWW'),
    '#size' => 30,
    '#default_value' => isset($node->www) ? $node->www : '',
  );

  $form['group4'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
    '#weight' => module_exists('content') ? content_extra_field_weight($node->type, 'group4') : -17,
  );

  $form['group4']['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone'),
    '#size' => 30,
    '#default_value' => isset($node->phone) ? $node->phone : '',
  );

  $form['group4']['im'] = array(
    '#type' => 'textfield',
    '#title' => t('IM'),
    '#size' => 30,
    '#default_value' => isset($node->im) ? $node->im : '',
  );

  if ($type->has_body) {
    $form['body_field'] = node_body_field($node, $type->body_label, $type->min_word_count);
  }

  $form['title_old'] = array(
    '#type' => 'hidden',
    '#default_value' => isset($node->title_old) ? $node->title_old : NULL,
  );

  return $form;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function stormperson_form_stormperson_node_form_alter(&$form, &$form_state) {
  global $conf;

  if ($conf['storm_suitecrm']) {
    $form['group1']['#access'] = FALSE;
    $form['group3']['#access'] = FALSE;
    $form['group4']['#access'] = FALSE;
#   $form['group2']['user_name']['#required'] = TRUE;
    $form['body_field']['#access'] = FALSE;

    if (!empty($form['#node']->nid)) {
      $form['#after_build'][] = 'stormperson_node_form_after_build';
    }
  }
}

function stormperson_node_form_after_build($form, &$form_state) {
  // https://www.silviogutierrez.com/blog/making-cck-fields-read-only-drupal-6:
  $form['field_stormperson_name'][0]['value']['#attributes']['readonly'] = 'readonly';
  $form_state['values']['field_stormperson_name'][0]['value'] = $form['field_stormperson_name']['#default_value']['value'];
  $form['field_stormperson_lastname'][0]['value']['#attributes']['readonly'] = 'readonly';
  $form_state['values']['field_stormperson_lastname'][0]['value'] = $form['field_stormperson_lastname']['#default_value']['value'];
  return $form;
}

function stormperson_validate($node, &$form) {
  if (!empty($node->user_name)) {
    $ass_user = user_load(array('name' => $node->user_name));
    if (!empty($ass_user)) {
      $result = db_query("SELECT n.nid, n.title FROM {node} n JOIN {stormperson} stp ON (n.nid = stp.nid) WHERE stp.user_uid = %d", $ass_user->uid);
      $row = db_fetch_array($result);
      if ($row && (empty($form['#node']->user_name) || ($form['#node']->user_name != $node->user_name))) {
        form_set_error('user_name', t('This Drupal user is already assigned to a SuiteDesk person (!link). The same Drupal user can not be assigned to two SuiteDesk people.', array('!link' => l($row['title'], 'node/'. $row['nid']))));
      }
    }
  }
}

function stormperson_user_autocomplete($string = '') {
  $matches = array();
  if ($string) {
    $result = db_query_range("SELECT name FROM {users} WHERE name LIKE '%s%%' AND uid NOT IN (SELECT user_uid FROM {stormperson})", $string, 0, 10);
    while ($user = db_fetch_object($result)) {
      $matches[$user->name] = check_plain($user->name);
    }
  }

  drupal_json($matches);
}

function stormperson_insert($node) {
  _stormperson_beforesave($node);

  db_query("INSERT INTO {stormperson}
          (vid, nid, organization_nid, organization_title,
          prefix, email, www, phone, im, user_uid)
          VALUES
          (%d, %d, %d, '%s',
          '%s', '%s', '%s', '%s', '%s', %d)",
          $node->vid, $node->nid, $node->organization_nid, $node->organization_title,
          $node->prefix, $node->email, $node->www, $node->phone, $node->im, $node->user_uid);
  _stormperson_aftersave($node);
}

function stormperson_update($node) {
  // if this is a new node or we're adding a new revision,
  if ($node->revision) {
    stormperson_insert($node);
  }
  else {
    _stormperson_beforesave($node);

    db_query("UPDATE {stormperson} SET
      organization_nid=%d, organization_title='%s',
      prefix='%s', email='%s', www='%s',
      phone='%s', im='%s', user_uid=%d
      WHERE vid = %d",
      $node->organization_nid, $node->organization_title,
      $node->prefix, $node->email, $node->www,
      $node->phone, $node->im, $node->user_uid,
      $node->vid);

    _stormperson_aftersave($node);

    if ($node->title != $node->title_old) {
      module_invoke_all('stormperson_change', $node->nid, $node->title);
    }
  }
}

function _stormperson_beforesave(&$node) {
  $ass_user = user_load(array('name' => $node->user_name));
  $node->user_uid = $ass_user->uid;
  if (!$node->email) {
    $node->email = $ass_user->mail;
  }

  $s = "SELECT n.title FROM {node} AS n INNER JOIN {stormorganization} AS p ON n.nid=p.nid
      WHERE type='stormorganization' AND n.nid=%d";
  $r = db_query($s, $node->organization_nid);
  $o = db_fetch_object($r);
  $node->organization_title = $o->title;
}

function _stormperson_aftersave(&$node) {
  global $user;
  if ($user->uid == $node->user_uid) {
    $user->stormperson_nid = $node->user_nid;
    $user->stormorganization_nid = $node->organization_nid;
  }
}

function stormperson_nodeapi(&$node, $op, $teaser, $page) {
  global $base_url, $conf;

  if ($node->type != 'stormperson') {
    return;
  }
  switch ($op) {
    case 'validate':
      $nid = $node->nid;
      $name = $node->field_stormperson_name[0]['value'];
      $lastname = $node->field_stormperson_lastname[0]['value'];
      $fullname = empty($lastname) ? $name : $lastname . ', ' . $name;
      if (!$conf['storm_suitecrm'] || empty($fullname)) {
        return;
      }
      // Checking if exists the contact in SuiteCRM:
      db_set_active('sugarcrm');
      db_query("SELECT id FROM contacts WHERE first_name = '%s' AND last_name = '%s' AND deleted = 0", $name, $lastname);
      $affected_rows = db_affected_rows();
      db_set_active('default');

      if ($affected_rows == 0) {
        form_set_error('title', t('Contact does not exists in SuiteCRM. Please check!'));
      } elseif ($affected_rows > 1) {
        form_set_error('title', t('More than one contact with this name and lastname in SuiteCRM. Please check!'));
      } else {
        // Checking if there is another contact with the same name:
        $person_nid = db_result(
          db_query(
            "SELECT nid FROM {node} WHERE type = 'stormperson' AND title = '%s'" . (isset($nid) ? " AND nid != $nid" : '') . ' AND status = 1',
            $fullname
          )
        );
        if (!empty($person_nid)) {
          form_set_error('title',
            t('Already exists a !person with this name. Please check!',
              array('!person' => l(t('person'), drupal_get_path_alias('node/' . $person_nid)))
            )
          );
        }
      }
      break;

    case 'presave':
      if ($conf['storm_suitecrm']) {
        $sugarid = $node->field_stormperson_sugarid[0]['value'];

        db_set_active('sugarcrm');
        $query = 'SELECT c.id, c.date_modified, c.salutation, c.first_name, c.last_name, c.primary_address_street, c.primary_address_city, c.primary_address_state, c.primary_address_country, c.primary_address_postalcode, c.alt_address_street, c.alt_address_city, c.alt_address_state, c.alt_address_country, c.alt_address_postalcode, c.phone_work, c.phone_mobile, c.phone_fax, addr.email_address, c.department, c.title, cc.website_c, cc.linkedin_c, cc.facebook_c, cc.twitter_c, cc.otherlink_c FROM contacts c LEFT JOIN contacts_cstm cc ON (cc.id_c = c.id) LEFT JOIN (email_addr_bean_rel bean, email_addresses addr) ON (bean.bean_id = c.id AND addr.id = bean.email_address_id AND bean.primary_address = 1 AND bean.deleted = 0) WHERE ';
        $query .= empty($sugarid) ? "c.first_name = '" . $node->field_stormperson_name[0]['value'] . "' AND c.last_name = '" . $node->field_stormperson_lastname[0]['value'] . "'" : "c.id = '$sugarid'";
        $query .= ' AND c.deleted = 0';
        $suitecrm_data = db_query($query);
        $affected_rows = db_affected_rows();
        db_set_active('default');

        if ($affected_rows == 1) {
          $suitecrm_person = db_fetch_array($suitecrm_data);
          $node->field_stormperson_sugarid[0]['value'] = $suitecrm_person['id'];
          $node->field_stormperson_sugarmod[0]['value'] = $suitecrm_person['date_modified'];
          _stormperson_suitecrm2node($suitecrm_person, $node);
        }
      }
      break;

    case 'insert':
    case 'update':
      if ($conf['storm_suitecrm']) {
        $sugarid = $node->field_stormperson_sugarid[0]['value'];
        if (!empty($sugarid)) {
          db_set_active('sugarcrm');
          db_query("UPDATE contacts_cstm SET stormplus_c = '%s' WHERE id_c = '%s'", $base_url . '/people/' . $node->nid, $sugarid);
          db_set_active('default');
        }
      }
      break;

    case 'delete':
      if ($conf['storm_suitecrm']) {
        $sugarid = $node->field_stormperson_sugarid[0]['value'];
        if (!empty($sugarid)) {
          db_set_active('sugarcrm');
          db_query("UPDATE contacts_cstm SET stormplus_c = NULL WHERE id_c = '%s'", $sugarid);
          db_set_active('default');
        }
      }
      break;

    case 'delete revision':
      // Notice that we're matching a single revision based on the node's vid.
      db_query('DELETE FROM {stormperson} WHERE vid = %d', $node->vid);
      break;

    case 'view':
      if ($conf['storm_suitecrm'] && !storm_cron_is_running()) {
        $sugarid = $node->field_stormperson_sugarid[0]['value'];
        if (!empty($sugarid)) {
          db_set_active('sugarcrm');
          $suitecrm_data = db_query("SELECT id, date_modified FROM contacts WHERE id = '%s' AND deleted = 0", $sugarid);
          $affected_rows = db_affected_rows();
          db_set_active('default');

          if ($affected_rows == 1) {
            $suitecrm_contact = db_fetch_array($suitecrm_data);
            if ($node->field_stormperson_sugarmod[0]['value'] != $suitecrm_contact['date_modified']) {
              $node_update = node_load($node->nid);
              // Prepare node for a submit.
              $node_update = node_submit($node_update);  
              node_save($node_update);
              drupal_set_message(t('SuiteCRM contact has been updated, refresh to view changes.'));
            }
          } elseif ($page) {
            drupal_set_message(t('SuiteCRM contact record associated not found.'), 'error');
            drupal_set_message(t('Contact id !contact does not exists in SuiteCRM.', array('!contact' => "<strong>$sugarid</strong>")), 'error');
            drupal_set_message(t('Please contact your system administrator!'), 'error');
          }
        } elseif ($page) {
          drupal_set_message(t('There no SuiteCRM contact record associated. Please check!'), 'error');
        }
      }
      break;
  }
}

/**
 * Before delete a person.
 */
function _stormperson_validate_predelete($node) {
  $nid = $node->nid;
  $items = array();

  if (_storm_validate_predelete('stormteam', "s.mnid = $nid")) {
    $items[] = '<a href="/teams">' . t('teams') . '</a>';
  }
  if (_storm_validate_predelete('stormproject', "s.manager_nid = $nid OR s.assigned_nid = $nid")) {
    $items[] = '<a href="/projects">' . t('projects') . '</a>';
  }
  if (_storm_validate_predelete('stormtask', "s.assigned_nid = $nid")) {
    $items[] = '<a href="/tasks">' . t('tasks') . '</a>';
  }
  if (_storm_validate_predelete('stormticket', "s.assigned_nid = $nid")) {
    $items[] = '<a href="/tickets">' . t('tickets') . '</a>';
  }

  $nitems = count($items);
  if ($nitems > 0) {
    $elements = $items[0];
    if ($nitems > 2) {
      for ($i = 1; $i < $nitems - 1; $i++) {
        $elements .= ', ' . $items[$i];
      }
    }
    if ($nitems > 1) {
      $elements .= ' ' . t('and') . ' ' . $items[$nitems - 1];
    }
    form_set_error('title', t('Impossible to remove due to existing !elements associated to this person!', array('!elements' => $elements)));
    return FALSE;
  }
  return TRUE;
}

/**
 * Copy SuiteCRM contact data to node.
 */
function _stormperson_suitecrm2node($suitecrm_data, &$node) {

  $node->prefix = $suitecrm_data['salutation'];
  $node->field_stormperson_name[0]['value'] = $suitecrm_data['first_name'];
  $node->field_stormperson_lastname[0]['value'] = $suitecrm_data['last_name'];
  $node->title = empty($suitecrm_data['last_name']) ? $suitecrm_data['first_name'] : $suitecrm_data['last_name'] . ', ' . $suitecrm_data['first_name'];

  $node->field_stormperson_depart[0]['value'] = $suitecrm_data['department'];
  $node->field_stormperson_job[0]['value'] = $suitecrm_data['title'];

  $node->field_stormperson_address[0]['value'] = $suitecrm_data['primary_address_street'];
  $node->field_stormperson_city[0]['value'] = $suitecrm_data['primary_address_city'];
  $node->field_stormperson_provst[0]['value'] = $suitecrm_data['primary_address_state'];
  $node->field_stormperson_country[0]['value'] = $suitecrm_data['primary_address_country'];
  $node->field_stormperson_zip[0]['value'] = $suitecrm_data['primary_address_postalcode'];
  $alt_address =
    $suitecrm_data['primary_address_street'] != $suitecrm_data['alt_address_street'] ||
    $suitecrm_data['primary_address_city'] != $suitecrm_data['alt_address_city'] ||
    $suitecrm_data['primary_address_state'] != $suitecrm_data['alt_address_state'] ||
    $suitecrm_data['primary_address_country'] != $suitecrm_data['alt_address_country'] ||
    $suitecrm_data['primary_address_postalcode'] != $suitecrm_data['alt_address_postalcode'];
  $node->field_stormperson_address2[0]['value'] = $alt_address ? $suitecrm_data['alt_address_street'] : NULL;
  $node->field_stormperson_city2[0]['value'] = $alt_address ? $suitecrm_data['alt_address_city'] : NULL;
  $node->field_stormperson_provst2[0]['value'] = $alt_address ? $suitecrm_data['alt_address_state'] : NULL;
  $node->field_stormperson_country2[0]['value'] = $alt_address ? $suitecrm_data['alt_address_country'] : NULL;
  $node->field_stormperson_zip2[0]['value'] = $alt_address ? $suitecrm_data['alt_address_postalcode'] : NULL;

  if (!valid_url($suitecrm_data['website_c'], TRUE)) {
    $suitecrm_data['website_c'] = valid_url('http://'. $suitecrm_data['website_c'], TRUE) ? 'http://'. $suitecrm_data['website_c'] : NULL;
  }
  if (!valid_url($suitecrm_data['linkedin_c'], TRUE)) {
    $suitecrm_data['linkedin_c'] = valid_url('http://'. $suitecrm_data['linkedin_c'], TRUE) ? 'http://'. $suitecrm_data['linkedin_c'] : NULL;
  }
  if (!valid_url($suitecrm_data['facebook_c'], TRUE)) {
    $suitecrm_data['facebook_c'] = valid_url('http://'. $suitecrm_data['facebook_c'], TRUE) ? 'http://'. $suitecrm_data['facebook_c'] : NULL;
  }
  if (!valid_url($suitecrm_data['twitter_c'], TRUE)) {
    $suitecrm_data['twitter_c'] = valid_url('http://'. $suitecrm_data['twitter_c'], TRUE) ? 'http://'. $suitecrm_data['twitter_c'] : NULL;
  }
  if (!valid_url($suitecrm_data['otherlink_c'], TRUE)) {
    $suitecrm_data['otherlink_c'] = valid_url('http://'. $suitecrm_data['otherlink_c'], TRUE) ? 'http://'. $suitecrm_data['otherlink_c'] : NULL;
  }

  $node->www = $suitecrm_data['website_c'];
  $node->email = $suitecrm_data['email_address'];
  $node->phone = $suitecrm_data['phone_work'];

  $node->field_stormperson_celular[0]['value'] = $suitecrm_data['phone_mobile'];
  $node->field_stormperson_fax[0]['value'] = $suitecrm_data['phone_fax'];

  $node->field_stormperson_linkedin[0]['url'] = $suitecrm_data['linkedin_c'];
  $node->field_stormperson_facebook[0]['url'] = $suitecrm_data['facebook_c'];
  $node->field_stormperson_twitter[0]['url'] = $suitecrm_data['twitter_c'];
  $node->field_stormperson_olink[0]['url'] = $suitecrm_data['otherlink_c'];
}

function stormperson_delete($node) {
  // Notice that we're matching all revision, by using the node's nid.
  db_query('DELETE FROM {stormperson} WHERE nid = %d', $node->nid);
  global $user;
  if ($user->uid == $node->user_uid) {
    $user->stormperson_nid = -1;
    $user->stormorganization_nid = -1;
  }
}

function stormperson_load($node) {
  $additions = db_fetch_object(db_query('SELECT * FROM {stormperson} WHERE vid = %d', $node->vid));
  $ass_user = user_load(array('uid' => $additions->user_uid));
  $additions->user_name = $ass_user->name;
  $additions->title_old = $node->title;
  return $additions;
}

function stormperson_view($node, $teaser = FALSE, $page = FALSE) {
  $breadcrumb = array();
  $breadcrumb[] = l(t('SuiteDesk'), 'dashboard');
  $breadcrumb[] = l(t('People'), 'people');
  drupal_set_breadcrumb($breadcrumb);

  return theme('stormperson_view', $node, $teaser, $page);
}

function _stormperson_people_access($node=NULL) {
  if ($node == NULL) return FALSE;
  if ($node->type == 'stormorganization') return TRUE;
  return FALSE;
}

function stormperson_user($type, &$edit, &$account, $category = NULL) {
  switch ($type) {
    case 'load':
      return _stormperson_user_load($account);
    case 'delete':
      return _stormperson_user_delete($account);
  }
}

function _stormperson_user_load(&$account) {
  static $loaded_persons = array();
  if (isset($loaded_persons[$account->uid])) {
    if (is_object($loaded_persons[$account->uid])) {
      $account->stormperson_nid = $loaded_persons[$account->uid]->nid;
      $account->stormorganization_nid = $loaded_persons[$account->uid]->organization_nid;
    }
  }
  else {
    $a = db_fetch_object(db_query("SELECT nid, organization_nid FROM {stormperson} WHERE user_uid=%d", $account->uid));
    if ($a) {
      $loaded_persons[$account->uid] = new stdClass();
      $loaded_persons[$account->uid]->nid = $a->nid;
      $loaded_persons[$account->uid]->organization_nid = $a->organization_nid;
      $account->stormperson_nid = $loaded_persons[$account->uid]->nid;
      $account->stormorganization_nid = $loaded_persons[$account->uid]->organization_nid;
    }
    else {
      $loaded_persons[$account->uid] = 0;
    }
  }
}

function _stormperson_user_delete(&$account) {
  db_query("UPDATE {stormperson} SET user_uid=NULL WHERE user_uid=%d", $account->uid);
}

function stormperson_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'stormperson'),
  );
}

/**
 * @function
 * A helper function to return the email address of a stormperson
 */
function stormperson_primary_email($node) {
  if ($node->type !== 'stormperson') {
    return NULL;
  }
  // If there is a Drupal user account use that email
  if ($node->user_uid) {
    $stormperson_person = user_load($node->user_uid);
    return $stormperson_person->mail;
  }
  // Else use the stormperson email
  elseif ($node->email) {
    return $node->email;
  }
}

function stormperson_storm_dashboard_links($type) {
  $links = array();
  if ($type == 'page' || $type == 'block') {
    $links[] = array(
      'theme' => 'storm_dashboard_link',
      'title' => t('People'),
      'icon' => 'stormperson-item',
      'path' => 'people',
      'params' => array(),
      'access_arguments' => 'Storm person: access',
      'node_type' => 'stormperson',
      'add_type' => 'stormperson',
      'map' => array(),
      'weight' => 2,
    );
  }
  return $links;
}
