<?php

/**
 * @file
 */

function stormorganization_help($path, $arg) {
  $output = '';

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

  return $output;
}

function stormorganization_perm() {
  return array(
    'Storm organization: access',
    'Storm organization: add',
    'Storm organization: delete all',
    'Storm organization: delete own',
    'Storm organization: edit all',
    'Storm organization: edit own',
    'Storm organization: edit belonged',
    'Storm organization: view all',
    'Storm organization: view own',
    'Storm organization: view belonged',
  );
}

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

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

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

  if (!isset($account->stormorganization_nid) && module_exists('stormperson')) {
    _stormperson_user_load($account);
  }

  if ($op == 'delete') {
    if (user_access('Storm organization: delete all')) {
      return TRUE;
    }
    elseif (user_access('Storm organization: delete own') && ($account->uid == $node->uid)) {
      return TRUE;
    }
  }

  if ($op == 'update') {
    if (user_access('Storm organization: edit all')) {
      return TRUE;
    }
    elseif (user_access('Storm organization: edit own') && ($account->uid == $node->uid)) {
      return TRUE;
    }
    elseif (user_access('Storm organization: edit belonged') && ($account->stormorganization_nid == $node->nid)) {
      return TRUE;
    }
  }

  if ($op == 'view') {
    if (user_access('Storm organization: view all')) {
      return TRUE;
    }
    elseif (user_access('Storm organization: view own') && ($account->uid == $node->uid)) {
      return TRUE;
    }
    elseif (user_access('Storm organization: view belonged') && ($account->stormorganization_nid == $node->nid)) {
      return TRUE;
    }
  }

  return FALSE;
}

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

    $cond = '';
    if (user_access('Storm organization: view own')) {
      $cond .= 'n.uid = ' . $user->uid;
    }
    if (user_access('Storm organization: view belonged')) {
      $cond .= !empty($cond) ? ' OR ' : '';
      $cond .= 'n.nid = ' . $user->stormorganization_nid;
    }
    $where[] = empty($cond) ? '0 = 1' : $cond;
  }

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

function stormorganization_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 organization: view all', $account)) {
      return '';
    }
    if (user_access('Storm organization: view own', $account)) {
      $cond .= "${primary_table}.uid = " . $account->uid;
    }
    if (user_access('Storm organization: view belonged', $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 .= ' sor1.nid = ' . $account->stormorganization_nid;
    }
    if ($cond) {
      $cond = " WHEN 'stormorganization' THEN (SELECT IF($cond, 1, 0) FROM {stormorganization} sor1 WHERE sor1.vid = ${primary_table}.vid) ";
    }
    else {
      $cond = " WHEN 'stormorganization' THEN 0 ";
    }
  }
  $conds[$primary_table][$account->uid] = $cond;
  return $cond;
}

function stormorganization_menu() {
  $items = array();
  $items['organizations'] = array(
    'title' => 'Organizations',
    'description' => 'SuiteDesk organizations',
    'page callback' => 'stormorganization_list',
    'access arguments' => array('Storm organization: access'),
    'file' => 'stormorganization.admin.inc',
    'type' => MENU_NORMAL_ITEM,
    'weight' => 0,
  );

  $items['storm/organizations/autocomplete'] = array(
    'title' => 'Organization autocomplete',
    'page callback' => 'stormorganization_autocomplete',
    'access arguments' => array('Storm organization: access'),
    'type' => MENU_CALLBACK,
    'file' => 'stormorganization.admin.inc',
  );

  $items['admin/settings/suitedesk/organization'] = array(
    'title' => 'SuiteDesk organization',
    'description' => 'SuiteDesk organization administration page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('stormorganization_admin_settings'),
    'access arguments' => array('Storm: access administration pages'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

function stormorganization_theme() {
  return array(
    'stormorganization_list' => array(
      'file'      => 'stormorganization.theme.inc',
      'arguments' => array('header', 'organizations'),
    ),
    'stormorganization_view' => array(
      'file'      => 'stormorganization.theme.inc',
      'arguments' => array('node', 'teaser', 'page'),
    ),
  );
}

function stormorganization_node_info() {
  return array(
    'stormorganization' => array(
      'name' => t('Organization'),
      'module' => 'stormorganization',
      'description' => t("An organization for SuiteDesk."),
      'title_label' => t("Name"),
      'body_label' => t("Note"),
    )
  );
}

function stormorganization_content_extra_fields($type_name) {
  if ($type_name == 'stormorganization') {
    return array(
      'group1' => array('label' => 'Customer/Provider/Active Group', 'weight' => -20),
      'group2' => array('label' => 'Prefix/Fullname Group', 'weight' => -19),
      'group3' => array('label' => 'Address Group', 'weight' => -18),
      'group4' => array('label' => 'Phone/WWW/Email Group', 'weight' => -17),
      'group5' => array('label' => 'Currency/Language/Tax ID Group', 'weight' => -16),
    );
  }
}

function stormorganization_form(&$node) {
  $breadcrumb = array();
  $breadcrumb[] = l(t('SuiteDesk'), 'dashboard');
  $breadcrumb[] = l(t('Organizations'), 'organizations');
  drupal_set_breadcrumb($breadcrumb);

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

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

  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => check_plain($type->title_label),
    '#required' => TRUE,
    '#default_value' => $node->title,
    '#weight' => module_exists('content') ? content_extra_field_weight($node->type, 'title') : -18,
  );

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

  $form['group1']['iscustomer'] = array(
    '#type' => 'checkbox',
    '#title' => t('Customer'),
    '#default_value' => $node->iscustomer,
  );

  $form['group1']['isprovider'] = array(
    '#type' => 'checkbox',
    '#title' => t('Provider'),
    '#default_value' => $node->isprovider,
  );

  $form['group1']['isactive'] = array(
    '#type' => 'checkbox',
    '#title' => t('Active'),
    '#default_value' => $node->isactive,
  );

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

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

  $form['group3']['address'] = array(
    '#type' => 'textfield',
    '#title' => t('Address'),
    '#default_value' => isset($node->address) ? $node->address : NULL,
    '#weight' => 1,
  );

  $form['group3']['city'] = array(
    '#type' => 'textfield',
    '#title' => t('City'),
    '#size' => 20,
    '#default_value' => isset($node->city) ? $node->city : NULL,
    '#weight' => 2,
  );

  $form['group3']['provstate'] = array(
    '#type' => 'textfield',
    '#title' => t('Province / State'),
    '#size' => 20,
    '#default_value' => isset($node->provstate) ? $node->provstate : NULL,
    '#weight' => 3,
  );

  $country_list = storm_attributes_bydomain('Country');
  $form['group3']['country'] = array(
    '#type' => 'select',
    '#title' => t('Country'),
    '#options' => $country_list['values'],
    '#default_value' => $node->country,
    '#weight' => 4,
  );

  $form['group3']['zip'] = array(
    '#type' => 'textfield',
    '#title' => t('Zip'),
    '#size' => 15,
    '#default_value' => isset($node->zip) ? $node->zip : NULL,
    '#weight' => 5,
  );

  $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'),
    '#default_value' => isset($node->phone) ? $node->phone : NULL,
  );

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

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

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

  $currency_list = storm_attributes_bydomain('Currency');
  $form['group5']['currency'] = array(
    '#type' => 'select',
    '#title' => t('Currency'),
    '#options' => $currency_list['values'],
    '#default_value' => $node->currency,
  );

  $pricemode_list = storm_attributes_bydomain('Price mode');
  $form['group5']['pricemode'] = array(
    '#type' => 'select',
    '#title' => t('Price mode'),
    '#default_value' => $node->pricemode,
    '#options' => $pricemode_list['values'],
  );

  $form['group5']['price'] = array(
    '#title' => t('Price'),
    '#type' => 'textfield',
    '#size' => 15,
    '#default_value' => isset($node->price) ? $node->price : NULL,
  );

  $languages = language_list('language', TRUE);
  $languages_options = array();
  foreach ($languages as $language_code => $language) {
    $languages_options[$language_code] = $language->name;
  }
  $form['group5']['orglanguage'] = array(
    '#type' => 'select',
    '#title' => t('Language'),
    '#options' => $languages_options,
    '#default_value' => isset($node->orglanguage) ? $node->orglanguage : NULL,
  );

  $form['group5']['taxid'] = array(
    '#type' => 'textfield',
    '#title' => t('Tax ID'),
    '#size' => 20,
    '#default_value' => isset($node->taxid) ? $node->taxid : NULL,
  );

  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 stormorganization_form_stormorganization_node_form_alter(&$form, &$form_state) {
  if (storm_suitecrm_is_defined()) {
    $form['group3']['#access'] = FALSE;
    $form['group4']['#access'] = FALSE;
    $form['group5']['taxid']['#access'] = FALSE;
    $form['body_field']['#access'] = FALSE;

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

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

function stormorganization_insert($node) {
  db_query("INSERT INTO {stormorganization}
           (vid, nid, country, www, phone, email, currency,
           provstate, zip, city, address, taxid, orglanguage, iscustomer, isprovider, isactive, pricemode, price
           ) VALUES
           (%d, %d, '%s', '%s', '%s', '%s', '%s',
           '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, '%s', %f
           )",
            $node->vid, $node->nid, $node->country, $node->www, $node->phone, $node->email, $node->currency,
            $node->provstate, $node->zip, $node->city, $node->address, $node->taxid,
            $node->orglanguage, $node->iscustomer, $node->isprovider, $node->isactive, $node->pricemode, $node->price
            );
}

function stormorganization_update($node) {
  // if this is a new node or we're adding a new revision,
  if ($node->revision) {
    stormorganization_insert($node);
  }
  else {
    db_query("UPDATE {stormorganization} SET
              country='%s', www='%s', phone='%s', email='%s', currency = '%s',
              provstate = '%s', zip = '%s', city = '%s', address = '%s', taxid = '%s', orglanguage = '%s',
              iscustomer=%d, isprovider=%d, isactive=%d, pricemode='%s', price=%f WHERE vid = %d",
              $node->country, $node->www, $node->phone, $node->email, $node->currency,
              $node->provstate, $node->zip, $node->city, $node->address, $node->taxid, $node->orglanguage,
              $node->iscustomer, $node->isprovider, $node->isactive, $node->pricemode, $node->price, $node->vid);
    if ($node->title != $node->title_old) {
      module_invoke_all('stormorganization_change', $node->nid, $node->title);
    }
  }
}

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

  if ($node->type != 'stormorganization') {
    return;
  }
  switch ($op) {
    case 'prepare':
      if (!isset($node->nid)) {
        $node->iscustomer = 1;
        $node->isprovider = 0;
        $node->isactive = 1;

        $country_list = storm_attributes_bydomain('Country');
        $node->country = $country_list['default'];

        $currency_list = storm_attributes_bydomain('Currency');
        $node->currency = $currency_list['default'];

        $pricemode_list = storm_attributes_bydomain('Price mode');
        $node->pricemode = $pricemode_list['default'];
      }
      break;

    case 'validate':
      $nid = $node->nid;
      $organization_name = $node->title;
      if (!storm_suitecrm_is_defined() || empty($organization_name)) {
        return;
      }
      // Checking if exists the organization in SuiteCRM:
      db_set_active('sugarcrm');
      db_query("SELECT id FROM accounts WHERE name = '%s' AND deleted = 0", $organization_name);
      $affected_rows = db_affected_rows();
      db_set_active('default');

      if ($affected_rows == 0) {
        form_set_error('title', t('Account does not exists in SuiteCRM. Please check!'));
      } elseif ($affected_rows > 1) {
        form_set_error('title', t('More than one account with this name in SuiteCRM. Please check!'));
      } else {
        // Checking if there is another organization with the same name:
        $organization_nid = db_result(
          db_query(
            "SELECT nid FROM {node} WHERE type = 'stormorganization' AND title = '%s'" . (isset($nid) ? " AND nid != $nid" : '') . ' AND status = 1',
            $organization_name
          )
        );
        if (!empty($organization_nid)) {
          form_set_error('title',
            t('Already exists an !organization with this name. Please check!',
              array('!organization' => l(t('organization'), drupal_get_path_alias('node/' . $organization_nid)))
            )
          );
        }
      }
      break;

    case 'presave':
      if (storm_suitecrm_is_defined()) {
        $sugarid = $node->field_stormorganization_sugarid[0]['value'];

        db_set_active('sugarcrm');
        $query = 'SELECT a.id, a.date_modified, a.name, c.fullname_c, a.billing_address_street, a.billing_address_city, a.billing_address_state, a.billing_address_country, a.billing_address_postalcode, a.shipping_address_street, a.shipping_address_city, a.shipping_address_state, a.shipping_address_country, a.shipping_address_postalcode, a.phone_office, a.website, a.phone_alternate, a.phone_fax, addr.email_address, c.cif_c, c.linkedin_c, c.facebook_c, c.twitter_c, c.otherlink_c FROM accounts a LEFT JOIN accounts_cstm c ON (c.id_c = a.id) LEFT JOIN (email_addr_bean_rel bean, email_addresses addr) ON (bean.bean_id = a.id AND addr.id = bean.email_address_id AND bean.primary_address = 1) WHERE ';
        $query .= empty($sugarid) ? "a.name = '$node->title'" : "a.id = '$sugarid'";
        $query .= ' AND a.deleted = 0';
        $suitecrm_data = db_query($query);
        $affected_rows = db_affected_rows();
        db_set_active('default');

        if ($affected_rows == 1) {
          $suitecrm_account = db_fetch_array($suitecrm_data);
          $node->field_stormorganization_sugarid[0]['value'] = $suitecrm_account['id'];
          $node->field_stormorganization_sugarmod[0]['value'] = $suitecrm_account['date_modified'];
          _stormorganization_suitecrm2node($suitecrm_account, $node);
        }
      }
      break;

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

    case 'delete':
      if (storm_suitecrm_is_defined()) {
        $sugarid = $node->field_stormorganization_sugarid[0]['value'];
        if (!empty($sugarid)) {
          db_set_active('sugarcrm');
          db_query("UPDATE accounts_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 {stormorganization} WHERE vid = %d', $node->vid);
      break;

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

          if ($affected_rows == 1) {
            $suitecrm_account = db_fetch_array($suitecrm_data);
            if ($node->field_stormorganization_sugarmod[0]['value'] != $suitecrm_account['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 account has been updated, refresh to view changes.'));
            }
          } elseif ($page) {
            drupal_set_message(t('SuiteCRM account record associated not found.'), 'error');
            drupal_set_message(t('Account id !account does not exists in SuiteCRM.', array('!account' => "<strong>$sugarid</strong>")), 'error');
            drupal_set_message(t('Please contact your system administrator!'), 'error');
          }
        } elseif ($page) {
          drupal_set_message(t('There no SuiteCRM account record associated. Please check!'), 'error');
        }
      }
      break;
  }
}

/**
 * Before delete an organization.
 */
function _stormorganization_validate_predelete($node) {
  $nid = $node->nid;
  $items = array();

  if (_storm_validate_predelete('stormperson', "s.organization_nid = $nid")) {
    $items[] = '<a href="/people">' . t('people') . '</a>';
  }
  if (_storm_validate_predelete('stormteam', "s.mnid = $nid")) {
    $items[] = '<a href="/teams">' . t('teams') . '</a>';
  }
  if (_storm_validate_predelete('stormproject', "s.organization_nid = $nid")) {
    $items[] = '<a href="/projects">' . t('projects') . '</a>';
  }
  if (_storm_validate_predelete('stormtask', "s.organization_nid = $nid")) {
    $items[] = '<a href="/tasks">' . t('tasks') . '</a>';
  }
  if (_storm_validate_predelete('stormticket', "s.organization_nid = $nid")) {
    $items[] = '<a href="/tickets">' . t('tickets') . '</a>';
  }
  if (_storm_validate_predelete('stormtimetracking', "s.organization_nid = $nid")) {
    $items[] = '<a href="/timetrackings">' . t('timetrackings') . '</a>';
  }
  if (_storm_validate_predelete('stormexpense', "s.organization_nid = $nid OR s.provider_nid = $nid")) {
    $items[] = '<a href="/expenses">' . t('expenses') . '</a>';
  }
  if (_storm_validate_predelete('storminvoice', "s.organization_nid = $nid")) {
    $items[] = '<a href="/invoices">' . t('invoices') . '</a>';
  }
  if (_storm_validate_predelete('stormdok', "s.organization_nid = $nid")) {
    $items[] = '<a href="/doks">' . t('documents') . '</a>';
  }
  if (_storm_validate_predelete('stormnote', "s.organization_nid = $nid")) {
    $items[] = '<a href="/notes">' . t('notes') . '</a>';
  }
  if (_storm_validate_predelete('stormevent', "s.organization_nid = $nid")) {
    $items[] = '<a href="/events">' . t('events') . '</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 organization!', array('!elements' => $elements)));
    return FALSE;
  }
  return TRUE;
}

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

  $node->title = $suitecrm_data['name'];
  $node->field_stormorganization_fullname[0]['value'] = $suitecrm_data['fullname_c'];
  $node->taxid = $suitecrm_data['cif_c'];

  $node->address = $suitecrm_data['billing_address_street'];
  $node->city = $suitecrm_data['billing_address_city'];
  $node->provstate = $suitecrm_data['billing_address_state'];
  $node->country = $suitecrm_data['billing_address_country'];
  $node->zip = $suitecrm_data['billing_address_postalcode'];
  $shipping_address =
    $suitecrm_data['billing_address_street'] != $suitecrm_data['shipping_address_street'] ||
    $suitecrm_data['billing_address_city'] != $suitecrm_data['shipping_address_city'] ||
    $suitecrm_data['billing_address_state'] != $suitecrm_data['shipping_address_state'] ||
    $suitecrm_data['billing_address_country'] != $suitecrm_data['shipping_address_country'] ||
    $suitecrm_data['billing_address_postalcode'] != $suitecrm_data['shipping_address_postalcode'];
  $node->field_stormorganization_address2[0]['value'] = $shipping_address ? $suitecrm_data['shipping_address_street'] : NULL;
  $node->field_stormorganization_city2[0]['value'] = $shipping_address ? $suitecrm_data['shipping_address_city'] : NULL;
  $node->field_stormorganization_provst2[0]['value'] = $shipping_address ? $suitecrm_data['shipping_address_state'] : NULL;
  $node->field_stormorganization_country2[0]['value'] = $shipping_address ? $suitecrm_data['shipping_address_country'] : NULL;
  $node->field_stormorganization_zip2[0]['value'] = $shipping_address ? $suitecrm_data['shipping_address_postalcode'] : NULL;

  if (!valid_url($suitecrm_data['website'], TRUE)) {
    $suitecrm_data['website'] = valid_url('http://'. $suitecrm_data['website'], TRUE) ? 'http://'. $suitecrm_data['website'] : 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->phone = $suitecrm_data['phone_office'];
  $node->www = $suitecrm_data['website'];
  $node->email = $suitecrm_data['email_address'];

  $node->field_stormorganization_tel2[0]['value'] = $suitecrm_data['phone_alternate'];
  $node->field_stormorganization_fax[0]['value'] = $suitecrm_data['phone_fax'];

  $node->field_stormorganization_linkedin[0]['url'] = $suitecrm_data['linkedin_c'];
  $node->field_stormorganization_facebook[0]['url'] = $suitecrm_data['facebook_c'];
  $node->field_stormorganization_twitter[0]['url'] = $suitecrm_data['twitter_c'];
  $node->field_stormorganization_olink[0]['url'] = $suitecrm_data['otherlink_c'];
}

function stormorganization_delete($node) {
  // Notice that we're matching all revision, by using the node's nid.
  db_query('DELETE FROM {stormorganization} WHERE nid = %d', $node->nid);
}

function stormorganization_load($node) {
  $additions = db_fetch_object(db_query('SELECT * FROM {stormorganization} WHERE vid = %d', $node->vid));
  $additions->title_old = $node->title;
  return $additions;
}

function stormorganization_view($node, $teaser = FALSE, $page = FALSE) {
  $breadcrumb = array();
  $breadcrumb[] = l(t('SuiteDesk'), 'dashboard');
  $breadcrumb[] = l(t('Organizations'), 'organizations');
  drupal_set_breadcrumb($breadcrumb);

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

function stormorganization_admin_settings() {
  $form = array();

  $s = "SELECT n.nid, n.title FROM  {node} AS n INNER JOIN {stormorganization} AS sor ON sor.nid=n.nid 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 (count($organizations) > 0) {
    $form['storm_organization_nid'] = array(
      '#type' => 'select',
      '#title' => t('Host organization'),
      '#options' => $organizations,
      '#default_value' => variable_get('storm_organization_nid', 0),
      '#description' => t('The organization that owns this system'),
      '#weight' => -30,
    );
  }
  else {
    $form['storm_organization_nid'] = array(
      '#type' => 'item',
      '#title' => t('Host organization'),
      '#value' => t('There are no SuiteDesk Organizations in the system.') .'<br />'. l(t('Create a SuiteDesk Organization'), 'node/add/stormorganization'),
    );
  }
  return system_settings_form($form);
}

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

function stormorganization_storm_dashboard_links($type) {
  $links = array();
  if ($type == 'page' || $type == 'block') {
    $links[] = array(
      'theme' => 'storm_dashboard_link',
      'title' => t('Organizations'),
      'icon' => 'stormorganization-item',
      'path' => 'organizations',
      'params' => array(),
      'access_arguments' => 'Storm organization: access',
      'node_type' => 'stormorganization',
      'add_type' => 'stormorganization',
      'map' => array(),
      'weight' => 1,
    );
  }
  return $links;
}
