<?php

/**
 * @file
 */

function stormtask_tasks($project) {
  $breadcrumb = array();
  $breadcrumb[] = l(t('SuiteDesk'), 'dashboard');
  $breadcrumb[] = l(t('Projects'), 'projects');
  $breadcrumb[] = l(t('Project : !project', array('!project' => $project->title)), 'node/'. $project->nid);
  drupal_set_breadcrumb($breadcrumb);

  $i = new stdClass();
  $i->type = 'stormtask';

  $o = drupal_get_form('stormtask_tasks_filter');

  $params = $_GET;
  $params['organization_nid'] = $project->organization_nid;
  $params['project_nid'] = $project->nid;

  $header = array(
    array(
      'data' => t('Title'),
    ),
    array(
      'data' => ' ',
    ),
    array(
      'data' => t('St.'),
    ),
    array(
      'data' => t('Pr.'),
    ),
    array(
      'data' => t('Begin'),
    ),
    array(
      'data' => t('End'),
    ),
    array(
      'data' => t('Duration'),
      'style' => 'text-align: right;',
    ),
    array(
      'data' => t('Parent'),
    ),
    array(
      'data' => t('Weight'),
    ),
    array(
      'data' => storm_icon_add_node($i, $params),
      'class' => 'storm_list_operations',
    ),
  );

  if (!stormproject_access('update', $project->nid)) {
    unset($header[7]);
    unset($header[8]);
  }

  $where = array();
  $args = array();

  $taskcategory = $_SESSION['stormtask_tasks_filter']['taskcategory'];
  if (!$taskcategory) {
    $category_list = storm_attributes_bydomain('Task category search');
    $taskcategory = $category_list['default'];
    $_SESSION['stormtask_tasks_filter']['taskcategory'] = $taskcategory;
  }
  if ($taskcategory && $taskcategory != '-') {
    $category = split(',', $taskcategory);
    $v = array();
    foreach ($category as $item) $v[] = '%s';
    $where[] = "sta.taskcategory IN ('". implode("','", $v) ."')";
    foreach ($category as $key => $value) {
      $args[] = $value;
    }
  }

  $taskstatus = $_SESSION['stormtask_tasks_filter']['taskstatus'];
  if (!$taskstatus) {
    $status_list = storm_attributes_bydomain('Task status search');
    $taskstatus = $status_list['default'];
    $_SESSION['stormtask_tasks_filter']['taskstatus'] = $taskstatus;
  }
  if ($taskstatus && $taskstatus != '-') {
    $status = split(',', $taskstatus);
    $v = array();
    foreach ($status as $item) $v[] = '%s';
    $where[] = "sta.taskstatus IN ('". implode("','", $v) ."')";
    foreach ($status as $key => $value) {
      $args[] = $value;
    }
  }

  $taskpriority = $_SESSION['stormtask_tasks_filter']['taskpriority'];
  if (!$taskpriority) {
    $priority_list = storm_attributes_bydomain('Task priority search');
    $taskpriority = $priority_list['default'];
    $_SESSION['stormtask_tasks_filter']['taskpriority'] = $taskpriority;
  }
  if ($taskpriority && $taskpriority != '-') {
    $priority = split(',', $taskpriority);
    $v = array();
    foreach ($priority as $item) $v[] = '%s';
    $where[] = "sta.taskpriority IN ('". implode("','", $v) ."')";
    foreach ($priority as $key => $value) {
      $args[] = $value;
    }
  }

  $taskstree = _stormtask_get_tree($project->nid, 0, -1, NULL, $where, $args);

  $o_gantt = "";
  $jsgantt_dir = drupal_get_path('module', 'stormtask') . '/dhtmlxgantt';

  $dispOpt = variable_get('stormtask_jsgantt_options', array());
  if ($dispOpt['ShowStartDate']) {
    $dispOpt['ShowStartDate'] = 1;
  }
  if ($dispOpt['ShowEndDate']) {
    $dispOpt['ShowEndDate'] = 1;
  }
  if ($dispOpt['ShowDur']) {
    $dispOpt['ShowDur'] = 1;
  }

  if (variable_get('stormtask_enable_ganttchart', 0)) {
    drupal_add_js($jsgantt_dir . '/dhtmlxgantt.js');
    drupal_add_js($jsgantt_dir . '/ext/dhtmlxgantt_marker.js');
    drupal_add_js($jsgantt_dir . '/locale/locale_es.js');
    drupal_add_css($jsgantt_dir . '/dhtmlxgantt.css');
    drupal_add_css(drupal_get_path('module', 'stormtask') . '/stormtask-gantt.css');

    $tasks = '';
    $links = '';
    $tasksIDs = array();

    $now = time();
    $one_day = 24 * 60 * 60;
    $earliest_date = $now;
    foreach ($taskstree as $task) {
      if ($task->datebegin && $task->datebegin < $earliest_date) {
        $earliest_date = $task->datebegin;
      }
    }
    $last_date = $earliest_date;

    $nTasks = 0;
    $nLinks = 0;
    foreach ($taskstree as $task) {
      $tID = 'id:' . ++$nTasks;
      $tasksIDs[$nTasks] = $task->nid;

      $tName = ',text:"' . check_plain($task->title) . '"';
      $tColor = '';
      $tCompl = '';

      if (!$task->datebegin) {
        if (!$task->parent_nid) {
          $last_date = $earliest_date;
        }
        $tStart = ',start_date:"' . date("j/n/Y", $last_date) . '",duration:1';
        $tStart .= $task->taskcategory == 'tasks group' ? ',type:gantt.config.types.project' : ',type:gantt.config.types.milestone';
      } else {
        $tStart = ',start_date:"' . date("j/n/Y", $task->datebegin) . '"';
        $tStart .= ',duration:' . (($task->dateend - $task->datebegin) / $one_day + 1);

        $last_date = $task->datebegin;

        if ($task->taskcategory == 'tasks group') {
          $tStart .= ',type:gantt.config.types.project';
        } else {
          // Task color by task status:
          $color_default = variable_get('stormtask_jsgantt_color', '3db9d3');
          $color = variable_get('stormtask_jsgantt_color_' . str_replace(' ', '_', $task->taskstatus), $color_default);
          // Highlight overdue tasks:
          if ($now > $task->dateend) {
            $color = variable_get('stormtask_jsgantt_color_overdue', 'ff0d0d');
          }
          $tColor = ',color:"#' . $color . '"';

          $tCompl = ',progress:';
          switch ($task->taskstatus) {
            case 'completed':
              $tCompl .= '1';
              break;
            case 'on hold':
              $tCompl .= '0.5';
              break;
            case 'in progress':
              if ($now > $task->datebegin && $task->dateend > $task->datebegin) {
                $tCompl .= round(($now - $task->datebegin) / ($task->dateend - $task->datebegin + $one_day), 2);
              } else {
                $tCompl .= '0';
              }
              break;
            default:
              $tCompl .= '0';
          }          
        }
      }

      $tParent = '';
      if ($task->parent_nid) {
        $parent_nid = array_search($task->parent_nid, $tasksIDs);
        if (!empty($parent_nid)) {
          $tParent = ',parent:' . $parent_nid;

          $lID = 'id:' . ++$nLinks;
          $lSource = ',source:' . $parent_nid;
          $lTarget = ',target:' . $nTasks;
          $links .= '{' . $lID . $lSource . $lTarget . ',type:"1"},';
        }
      }

      $tasks .= '{' . $tID . $tName . $tStart . $tColor . $tCompl . $tParent . ',open:true},';
    }

    $o_gantt .= '<div id="stormgantt"><div id="ggantt" style="height: ' . ($nTasks * 24 + 35) . 'px;"></div></div>';

    drupal_add_js('var tasks = {data:[' . rtrim($tasks, ',') . '],links:[' . rtrim($links, ',') . ']};
    gantt.config.readonly = true;
    gantt.config.autosize = "x";

    // Header
    gantt.config.columns = [
      {name:"text",tree:true,width:"*",resize:true},
      {name:"start_date",align:"center",width:90},
      {name:"duration",align:"right",width:30}
    ];
    gantt.config.row_height = 24;

    // Highlight weekends
    gantt.templates.scale_cell_class = function(date){
      if(date.getDay()==0||date.getDay()==6){
        return "weekend";
      }
    };
    gantt.templates.task_cell_class = function(item,date){
      if(date.getDay()==0||date.getDay()==6){
        return "weekend"
      }
    };
          
    // Scale
    gantt.config.scale_unit = "month";
    gantt.config.step = 1;
    gantt.config.date_scale = "%F, %Y";
    gantt.config.min_column_width = 30;

    gantt.config.scale_height = 30;
    var dayScaleTemplate = function(date){
      var dateToStr = gantt.date.date_to_str("%D");
      var dayToStr = gantt.date.date_to_str("%d");
      return dateToStr(date).substr(0,1) + "<strong>" + dayToStr(date) + "</strong>";
    };
    gantt.config.subscales = [
      {unit:"day",step:1,template:dayScaleTemplate}
    ];

    // Milestones
    gantt.templates.rightside_text = function(start,end,task){
      if(task.type == gantt.config.types.project){
        return "";
      }
      return task.text;
    };
    gantt.templates.task_text=function(start,end,task){
      if(task.type == gantt.config.types.project){
        return task.text;
      }
      return "";
    };
    gantt.templates.task_class=function(start,end,task){
      switch(task.type){
        case gantt.config.types.milestone:
          return "gantt_milestone";
        case gantt.config.types.project:
          return "";
      }
      return "gantt_task_normal";
    };

    // Today
    var date_to_str = gantt.date.date_to_str(gantt.config.task_date);
    var id = gantt.addMarker({start_date: new Date(),css:"today",title:date_to_str(new Date())});
    setInterval(function(){
      var today = gantt.getMarker(id);
      today.start_date = new Date();
      today.title = date_to_str(today.start_date);
      gantt.updateMarker(id);
    },1000*60);

    gantt.init("ggantt");
    gantt.parse(tasks);', 'inline', 'footer');
  }

  $o .= drupal_get_form('stormtask_tasks_form', $header, $taskstree, $project);
  $o .= $o_gantt;
  return $o;
}

function stormtask_tasks_form($form_id, $header, $tasks, $project) {
  $form = array();

  $form['tasks'] = array(
    '#theme' => 'stormtask_tasks',
  );

  $form['tasks']['header'] = array(
    '#value' => $header,
  );

  $tree = _stormtask_get_tree($project->nid);
  $parent_tasks = _stormtask_plain_tree($tree);

  $params = $_GET;
  $params['project_nid'] = $project->nid;

  foreach ($tasks as $task) {
    $task->type = 'stormtask';

    $form['tasks']['tasks'][$task->nid]['task_depth_'. $task->nid] = array(
      '#value' => $task->depth,
    );

    $form['tasks']['tasks'][$task->nid]['task_description_'. $task->nid] = array(
      '#value' => l($task->stepno .' '. $task->title, 'node/'. $task->nid, array('html' => TRUE)),
    );

    $form['tasks']['tasks'][$task->nid]['task_category_'. $task->nid] = array(
      '#value' => storm_icon('category_'. $task->taskcategory, storm_attribute_value('Task category', $task->taskcategory)),
    );

    $form['tasks']['tasks'][$task->nid]['task_status_'. $task->nid] = array(
      '#value' => storm_icon('status_'. $task->taskstatus, storm_attribute_value('Task status', $task->taskstatus)),
    );

    $form['tasks']['tasks'][$task->nid]['task_priority_'. $task->nid] = array(
      '#value' => storm_icon('priority_'. $task->taskpriority, storm_attribute_value('Task priority', $task->taskpriority)),
    );

    $datebegin = format_date($task->datebegin, 'small');
    $form['tasks']['tasks'][$task->nid]['task_datebegin_'. $task->nid] = array(
      '#value' => empty($task->datebegin) ? '' : substr($datebegin, 0, strpos($datebegin, ' ')),
    );

    $dateend = format_date($task->dateend, 'small');
    $form['tasks']['tasks'][$task->nid]['task_dateend_'. $task->nid] = array(
      '#value' => empty($task->dateend) ? '' : substr($dateend, 0, strpos($dateend, ' ')),
    );

    $form['tasks']['tasks'][$task->nid]['task_duration_'. $task->nid] = array(
      '#value' => $task->duration,
    );

    $form['tasks']['tasks'][$task->nid]['task_durationunit_'. $task->nid] = array(
      '#type' => 'hidden',
      '#value' => $task->durationunit,
    );

    $form['tasks']['tasks'][$task->nid]['task_parent-nid_'. $task->nid] = array(
      '#type' => 'select',
      '#options' => array(0 => '-') + $parent_tasks,
      '#default_value' => $task->parent_nid,
    );

    $form['tasks']['tasks'][$task->nid]['task_nid_'. $task->nid] = array(
      '#type' => 'hidden',
      '#default_value' => $task->nid,
    );

    $form['tasks']['tasks'][$task->nid]['task_weight_'. $task->nid] = array(
      '#type' => 'weight',
      '#default_value' => $task->weight,
    );

    $params['task_nid'] = $task->nid;

    $v = storm_icon_comment_node($task, $params);
    $v .= storm_icon_edit_node($task, $params);
    $v .= storm_icon_delete_node($task, $params);
    $v .= storm_icon_add_node($task, $params);

    $form['tasks']['tasks'][$task->nid]['task_operations_'. $task->nid] = array(
      '#value' => $v,
    );
  }

  $form['tasks']['project'] = array(
    '#type' => 'hidden',
    '#value' => $project->nid,
  );

  if (stormproject_access('update', $project->nid)) {
    // This form is displayed for users which may not have edit permissions for the nodes displayed.
    // Furthermore, permissions can mean that the user could have edit permissions for some nodes displayed and not others.
    // Therefore, the submit button must only be displayed if the user has the permission 'edit all', which guarantees the user is allowed to edit all nodes displayed.
    $form['submit'] = array(
      '#type' => 'submit',
      '#submit' => array('stormtask_tasks_submit'),
      '#value' => t('Save'),
    );
  }

  return $form;
}

function stormtask_tasks_submit($form, &$form_state) {
  $tasks = array();
  foreach ($form_state['values'] as $key => $value) {
    $ar = explode('_', $key);
    if ($ar[0]=='task') {
      if ($ar[1]=='weight') $tasks[$ar[2]]['weight'] = $value;
      if ($ar[1]=='parent-nid') $tasks[$ar[2]]['parent-nid'] = $value;
    }
  }

  $s = "UPDATE {stormtask} SET weight=%d, parent_nid=%d WHERE nid=%d";
  foreach ($tasks as $nid => $values) {
    db_query($s, $values['weight'], $values['parent-nid'], $nid);
  }

  drupal_set_message(t('Tasks saved'));
}

function stormtask_tasks_filter() {
  $category_list = storm_attributes_bydomain('Task category search');
  $taskcategory = $_SESSION['stormtask_tasks_filter']['taskcategory'];

  $status_list = storm_attributes_bydomain('Task status search');
  $taskstatus = $_SESSION['stormtask_tasks_filter']['taskstatus'];

  $priority_list = storm_attributes_bydomain('Task priority search');
  $taskpriority = $_SESSION['stormtask_tasks_filter']['taskpriority'];

  $form = array();

  $form['filter'] = array(
        '#type' => 'fieldset',
        '#title' => t('Filter'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
  );

  $form['filter']['group1'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
  );

  $form['filter']['group1']['taskcategory'] = array(
    '#type' => 'select',
    '#title' => t('Category'),
    '#default_value' => $taskcategory,
    '#options' => $category_list['values'],
  );

  $form['filter']['group1']['taskstatus'] = array(
    '#type' => 'select',
    '#title' => t('Status'),
    '#default_value' => $taskstatus,
    '#options' => $status_list['values'],
  );

  $form['filter']['group1']['taskpriority'] = array(
    '#type' => 'select',
    '#title' => t('Priority'),
    '#default_value' => $taskpriority,
    '#options' => $priority_list['values'],
  );

  $form['filter']['group2'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
    '#attributes' => array('class' => 'formgroup-submit'),
  );

  $form['filter']['group2']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Filter'),
    '#submit' => array('stormtask_tasks_filter_filter'),
  );

  $form['filter']['group2']['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('stormtask_tasks_filter_reset'),
  );

  return $form;
}

function stormtask_tasks_filter_filter($form, &$form_state) {
  $_SESSION['stormtask_tasks_filter']['taskcategory'] = $form_state['values']['taskcategory'];
  $_SESSION['stormtask_tasks_filter']['taskstatus'] = $form_state['values']['taskstatus'];
  $_SESSION['stormtask_tasks_filter']['taskpriority'] = $form_state['values']['taskpriority'];
}

function stormtask_tasks_filter_reset($form, &$form_state) {
  unset($_SESSION['stormtask_tasks_filter']);
}

function _stormtask_project_tasks_js($project_nid) {
  $tree = _stormtask_get_tree($project_nid);
  $tasks = _stormtask_plain_tree($tree);
  print drupal_to_js($tasks);
  exit();
}

function _stormtask_project_assignments_js($organization_nid, $project_nid) {
  $assignments = storm_get_assignment_options($organization_nid, $project_nid);
  print drupal_to_js($assignments);
  exit();
}

function stormtask_list() {

  global $user;

  $breadcrumb = array();
  $breadcrumb[] = l(t('SuiteDesk'), 'dashboard');
  drupal_set_breadcrumb($breadcrumb);

  if (array_key_exists('organization_nid', $_GET)) {
    if ($_SESSION['stormtask_list_filter']['organization_nid'] != $_GET['organization_nid']) {
      $_SESSION['stormtask_list_filter']['organization_nid'] = $_GET['organization_nid'];
    }
    unset($_SESSION['stormtask_list_filter']['project_nid']);
  }

  if (array_key_exists('project_nid', $_GET)) {
    if ($_SESSION['stormtask_list_filter']['project_nid'] != $_GET['project_nid']) {
      $_SESSION['stormtask_list_filter']['project_nid'] = $_GET['project_nid'];
    }
    $p = node_load($_GET['project_nid']);
    $_SESSION['stormtask_list_filter']['organization_nid'] = $p->organization_nid;

  }

  $i = new stdClass();
  $i->type = 'stormtask';

  $header = array(
    array(
      'data' => ' ',
    ),
    array(
      'data' => t(' '),
      'field' => 'sta.taskstatus',
    ),
    array(
      'data' => t('Title') . ' / ' . t('Organization') . ' » ' . t('Project'),
      'field' => 'n.title',
    ),
    array(
      'data' => t('Begin') . '&nbsp;/&nbsp;' . t('End'),
      'field' => 'sta.datebegin',
    ),
    array(
      'data' => ' ',
    ),
    array(
      'data' => t('Date'),
      'field' => 'n.changed',
      'sort' => 'desc',
    ),
    array(
      'data' => t('Pr.'),
      'field' => 'sta.taskpriority',
    ),
    array(
      'data' => t('Co.'),
      'field' => 'ncs.comment_count',
    ),
    array(
      'data' => storm_icon_add_node($i, $_GET),
      'class' => 'storm_list_operations',
    ),
  );

  $where = array();
  $args = array();
  $filterfields = array();

  $s  = "SELECT n.*, sta.*, nre.format, fta.field_stormtask_attached_list AS clip, ncs.comment_count FROM {node} AS n
    INNER JOIN {stormtask} AS sta ON n.vid=sta.vid
    INNER JOIN {node_revisions} AS nre ON n.vid = nre.vid
    LEFT JOIN {content_field_stormtask_attached} AS fta ON n.vid = fta.vid AND fta.field_stormtask_attached_list = 1 AND fta.delta = 0
    LEFT JOIN {node_comment_statistics} AS ncs ON n.nid = ncs.nid
    WHERE n.status=1 AND n.type='stormtask' ";

  if (isset($_SESSION['stormtask_list_filter']['organization_nid']) && ($_SESSION['stormtask_list_filter']['organization_nid'] != 0)) {
    $where[] = 'sta.organization_nid=%d';
    $args[] = $_SESSION['stormtask_list_filter']['organization_nid'];
    $filterfields[] = t('Organization');
  }
  if (isset($_SESSION['stormtask_list_filter']['project_nid']) && ($_SESSION['stormtask_list_filter']['project_nid'] != 0)) {
    $where[] = 'sta.project_nid=%d';
    $args[] = $_SESSION['stormtask_list_filter']['project_nid'];
    $filterfields[] = t('Project');
  }
  if (isset($_SESSION['stormtask_list_filter']['taskcategory']) && $_SESSION['stormtask_list_filter']['taskcategory'] != '-') {
    $category = split(',', $_SESSION['stormtask_list_filter']['taskcategory']);
    $v = array();
    foreach ($category as $item) $v[] = '%s';
    $where[] = "sta.taskcategory IN ('". implode("','", $v) ."')";
    foreach ($category as $key => $value) {
      $args[] = $value;
    }
    $filterfields[] = t('Category');
  }
  if (isset($_SESSION['stormtask_list_filter']['taskstatus']) && $_SESSION['stormtask_list_filter']['taskstatus'] != '-') {
    $status = split(',', $_SESSION['stormtask_list_filter']['taskstatus']);
    $v = array();
    foreach ($status as $item) $v[] = '%s';
    $where[] = "sta.taskstatus IN ('". implode("','", $v) ."')";
    foreach ($status as $key => $value) {
      $args[] = $value;
    }
    $filterfields[] = t('Status');
  }
  if (isset($_SESSION['stormtask_list_filter']['taskpriority']) && $_SESSION['stormtask_list_filter']['taskpriority'] != '-') {
    $priority = split(',', $_SESSION['stormtask_list_filter']['taskpriority']);
    $v = array();
    foreach ($priority as $item) $v[] = '%s';
    $where[] = "sta.taskpriority IN ('". implode("','", $v) ."')";
    foreach ($priority as $key => $value) {
      $args[] = $value;
    }
    $filterfields[] = t('Priority');
  }

  if (isset($_SESSION['stormtask_list_filter']['datebeginfrom'])) {
    $datebeginfrom = $_SESSION['stormtask_list_filter']['datebeginfrom'];
    $datebeginfrom['hour'] = 0;
    $datebeginfrom['minute'] = 0;
    $t = _storm_datetime_to_gmtimestamp($datebeginfrom);
    if ($datebeginfrom['year']>0 && $t>=0) {
      $where[] = 'sta.datebegin>=%d';
      $args[] = $t;
      $filterfields[] = t('Date');
    }
  }

  if (isset($_SESSION['stormtask_list_filter']['datebeginto'])) {
    $datebeginto = $_SESSION['stormtask_list_filter']['datebeginto'];
    $datebeginto['hour'] = 23;
    $datebeginto['minute'] = 59;
    $t = _storm_datetime_to_gmtimestamp($datebeginto);
    if ($datebeginto['year']>0 && $t>=0) {
      $where[] = 'sta.datebegin<=%d';
      $args[] = $t;
      $filterfields[] = t('Date');
    }
  }

  if (isset($_SESSION['stormtask_list_filter']['dateendfrom'])) {
    $dateendfrom = $_SESSION['stormtask_list_filter']['dateendfrom'];
    $dateendfrom['hour'] = 0;
    $dateendfrom['minute'] = 0;
    $t = _storm_datetime_to_gmtimestamp($dateendfrom);
    if ($dateendfrom['year']>0 && $t>=0) {
      $where[] = 'sta.dateend>=%d';
      $args[] = $t;
      $filterfields[] = t('Date');
    }
  }

  if (isset($_SESSION['stormtask_list_filter']['dateendto'])) {
    $dateendto = $_SESSION['stormtask_list_filter']['dateendto'];
    $dateendto['hour'] = 23;
    $dateendto['minute'] = 59;
    $t = _storm_datetime_to_gmtimestamp($dateendto);
    if ($dateendto['year']>0 && $t>=0) {
      $where[] = 'sta.dateend<=%d';
      $args[] = $t;
      $filterfields[] = t('Date');
    }
  }

  if (isset($_SESSION['stormtask_list_filter']['assigned_to'])) {
    if (!is_numeric($_SESSION['stormtask_list_filter']['assigned_to'])) {
      switch ($_SESSION['stormtask_list_filter']['assigned_to']) {

        case 'all':
          // NO FILTER
          break;

        case 'mine':
          // CURRENT USER
          if (!empty($user->stormperson_nid) && is_numeric($user->stormperson_nid)) {
            $assigned_to_nid = $user->stormperson_nid;
          }
          break;

        case 'none':
          $where[] = '(sta.assigned_nid IS NULL OR sta.assigned_nid = 0) ';
          break;

      }
    }
    else {
      $assigned_to_nid = $_SESSION['stormtask_list_filter']['assigned_to'];
    }
    if (!empty($assigned_to_nid) && is_numeric($assigned_to_nid)) {
      $where[] = 'sta.assigned_nid=%d';
      $args[] = $assigned_to_nid;
      $filterfields[] = t('Assigned to');
    }
  }

  if (isset($_SESSION['stormtask_list_filter']['billable']) && $_SESSION['stormtask_list_filter']['billable'] != '-') {
    $where[] = 'sta.billable=%d';
    $args[] = $_SESSION['stormtask_list_filter']['billable'];
    $filterfields[] = t('Billable');
  }

  if (isset($_SESSION['stormtask_list_filter']['billed']) && $_SESSION['stormtask_list_filter']['billed'] != '-') {
    $where[] = 'sta.billed=%d';
    $args[] = $_SESSION['stormtask_list_filter']['billed'];
    $filterfields[] = t('Billed');
  }

  $itemsperpage = isset($_SESSION['stormtask_list_filter']['itemsperpage']) ? $_SESSION['stormtask_list_filter']['itemsperpage'] : variable_get('storm_default_items_per_page', 10);

  if (count($filterfields) == 0) {
    $filterdesc = t('Not filtered');
  }
  else {
    $filterdesc = t('Filtered by !fields', array('!fields' => implode(", ", array_unique($filterfields))));
  }
  $filterdesc .= ' | '. t('!items items per page', array('!items' => $itemsperpage));

  $o = drupal_get_form('stormtask_list_filter', $filterdesc);

  $s = stormtask_access_sql($s, $where);
  $s = db_rewrite_sql($s);

  $tablesort = tablesort_sql($header);
  $r = pager_query($s . $tablesort, $itemsperpage, 0, NULL, $args);

  $tasks = array();
  while ($item = db_fetch_object($r)) {
    $tasks[] = $item;
  }

  $o .= theme('stormtask_list', $header, $tasks);
  $o .= theme('pager', NULL, $itemsperpage, 0);
  print theme('page', $o);
}

function stormtask_list_filter(&$form_state, $filterdesc = 'Filter') {
  $category_list = storm_attributes_bydomain('Task category search');
  $taskcategory = isset($_SESSION['stormtask_list_filter']['taskcategory']) ? $_SESSION['stormtask_list_filter']['taskcategory'] : $taskcategory = $category_list['default'];
  $_SESSION['stormtask_list_filter']['taskcategory'] = $taskcategory;

  $status_list = storm_attributes_bydomain('Task status search');
  $taskstatus = isset($_SESSION['stormtask_list_filter']['taskstatus']) ? $_SESSION['stormtask_list_filter']['taskstatus'] : $status_list['default'];
  $_SESSION['stormtask_list_filter']['taskstatus'] = $taskstatus;

  $priority_list = storm_attributes_bydomain('Task priority search');
  $taskpriority = isset($_SESSION['stormtask_list_filter']['taskpriority']) ? $_SESSION['stormtask_list_filter']['taskpriority'] : $priority_list['default'];
  $_SESSION['stormtask_list_filter']['taskpriority'] = $taskpriority;

  $organization_nid = isset($_SESSION['stormtask_list_filter']['organization_nid']) ? $_SESSION['stormtask_list_filter']['organization_nid'] : 0;
  $project_nid = isset($_SESSION['stormtask_list_filter']['project_nid']) ? $_SESSION['stormtask_list_filter']['project_nid'] : 0;

  $datebeginfrom = isset($_SESSION['stormtask_list_filter']['datebeginfrom']) ? $_SESSION['stormtask_list_filter']['datebeginfrom'] : NULL;
  $datebeginto = isset($_SESSION['stormtask_list_filter']['datebeginto']) ? $_SESSION['stormtask_list_filter']['datebeginto'] : NULL;
  $dateendfrom = isset($_SESSION['stormtask_list_filter']['dateendfrom']) ? $_SESSION['stormtask_list_filter']['dateendfrom'] : NULL;
  $dateendto = isset($_SESSION['stormtask_list_filter']['dateendto']) ? $_SESSION['stormtask_list_filter']['dateendfrom'] : NULL;

  $assigned_to = isset($_SESSION['stormtask_list_filter']['assigned_to']) ? $_SESSION['stormtask_list_filter']['assigned_to'] : NULL;

  $itemsperpage = isset($_SESSION['stormtask_list_filter']['itemsperpage']) ? $_SESSION['stormtask_list_filter']['itemsperpage'] : variable_get('storm_default_items_per_page', 10);
  $_SESSION['stormtask_list_filter']['itemsperpage'] = $itemsperpage;

  $form = array();

  $form['filter'] = array(
    '#type' => 'fieldset',
    '#title' => $filterdesc,
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );

  $form['filter']['group1'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
    '#weight' => -20,
  );

  $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;
  }
  $organizations = array(0 => t('All')) + $organizations;
  $form['filter']['group1']['organization_nid'] = array(
    '#type' => 'select',
    '#title' => t('Organization'),
    '#default_value' => $organization_nid,
    '#options' => $organizations,
    '#attributes' => array('onchange' => "stormproject_organization_projects(this, 'edit-project-nid', true, '" . t('All') . "')"),
  );

  $s = "SELECT n.nid, n.title FROM {node} AS n INNER JOIN {stormproject} AS spr ON spr.vid=n.vid
  WHERE n.status=1 AND spr.organization_nid=%d AND n.type='stormproject' ORDER BY n.title";
  $s = stormproject_access_sql($s);
  $s = db_rewrite_sql($s);
  $r = db_query($s, $organization_nid);
  $projects = array();
  while ($project = db_fetch_object($r)) {
    $projects[$project->nid] = $project->title;
  }
  $projects = array(0 => t('All')) + $projects;
  $form['filter']['group1']['project_nid'] = array(
    '#type' => 'select',
    '#title' => t('Project'),
    '#default_value' => $project_nid,
    '#options' => $projects,
    '#process' => array('storm_dependent_select_process'),
  );

  $form['filter']['group2'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
  );

  $form['filter']['group2']['taskcategory'] = array(
    '#type' => 'select',
    '#title' => t('Category'),
    '#default_value' => $taskcategory,
    '#options' => $category_list['values'],
  );

  $form['filter']['group2']['taskstatus'] = array(
    '#type' => 'select',
    '#title' => t('Status'),
    '#default_value' => $taskstatus,
    '#options' => $status_list['values'],
  );

  $form['filter']['group2']['taskpriority'] = array(
    '#type' => 'select',
    '#title' => t('Priority'),
    '#default_value' => $taskpriority,
    '#options' => $priority_list['values'],
  );

  $form['filter']['group3'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
  );

  $form['filter']['group3']['datebeginfrom'] = array(
    '#type' => 'dateext',
    '#withnull' => 'true',
    '#title' => t('Date begin from'),
    '#default_value' => $datebeginfrom,
  );

  $form['filter']['group3']['datebeginto'] = array(
    '#type' => 'dateext',
    '#withnull' => 'true',
    '#title' => t('Date begin to'),
    '#default_value' => $datebeginto,
  );

  $form['filter']['group4'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
  );

  $form['filter']['group4']['dateendfrom'] = array(
    '#type' => 'dateext',
    '#withnull' => 'true',
    '#title' => t('Date end from'),
    '#default_value' => $dateendfrom,
  );

  $form['filter']['group4']['dateendto'] = array(
    '#type' => 'dateext',
    '#withnull' => 'true',
    '#title' => t('Date end to'),
    '#default_value' => $dateendto,
  );

  $form['filter']['group4_1'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
  );

  // ASSIGNED TO
  $options = storm_get_assignment_options(0, 0);
  $form['filter']['group4_1']['assigned_to'] = array(
    '#type' => 'select',
    '#title' => t('Assigned to'),
    '#default_value' => $assigned_to,
    '#options' => $options,
  );

  $form['filter']['group4_1']['billable'] = array(
    '#type' => 'select',
    '#title' => t('Billable'),
    '#options' => array('-' => t('all'), '1' => t('billable'), '0' => t('not billable')),
    '#default_value' => isset($_SESSION['stormtask_list_filter']['billable']) ? $_SESSION['stormtask_list_filter']['billable'] : '-',
  );

  $form['filter']['group4_1']['billed'] = array(
    '#type' => 'select',
    '#title' => t('Billed'),
    '#options' => array('-' => t('all'), '1' => t('billed'), '0' => t('not billed')),
    '#default_value' => isset($_SESSION['stormtask_list_filter']['billed']) ? $_SESSION['stormtask_list_filter']['billed'] : '-',
  );

  $form['filter']['group5'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
    '#attributes' => array('class' => 'formgroup-submit'),
  );

  $form['filter']['group5']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Filter'),
    '#submit' => array('stormtask_list_filter_filter'),
  );

  $form['filter']['group5']['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('stormtask_list_filter_reset'),
  );

  $form['filter']['group5']['itemsperpage'] = array(
    '#type' => 'textfield',
    '#title' => t('Items'),
    '#size' => 10,
    '#default_value' => $itemsperpage,
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );

  return $form;
}

function stormtask_list_filter_filter($form, &$form_state) {
  $_SESSION['stormtask_list_filter']['organization_nid'] = $form_state['values']['organization_nid'];
  $_SESSION['stormtask_list_filter']['project_nid'] = $form_state['values']['project_nid'];
  $_SESSION['stormtask_list_filter']['taskcategory'] = $form_state['values']['taskcategory'];
  $_SESSION['stormtask_list_filter']['taskstatus'] = $form_state['values']['taskstatus'];
  $_SESSION['stormtask_list_filter']['taskpriority'] = $form_state['values']['taskpriority'];
  $_SESSION['stormtask_list_filter']['datebeginfrom'] = $form_state['values']['datebeginfrom'];
  $_SESSION['stormtask_list_filter']['datebeginto'] = $form_state['values']['datebeginto'];
  $_SESSION['stormtask_list_filter']['dateendfrom'] = $form_state['values']['dateendfrom'];
  $_SESSION['stormtask_list_filter']['dateendto'] = $form_state['values']['dateendto'];
  $_SESSION['stormtask_list_filter']['assigned_to'] = $form_state['values']['assigned_to'];
  $_SESSION['stormtask_list_filter']['billable'] = $form_state['values']['billable'];
  $_SESSION['stormtask_list_filter']['billed'] = $form_state['values']['billed'];
  $_SESSION['stormtask_list_filter']['itemsperpage'] = $form_state['values']['itemsperpage'];
}

function stormtask_list_filter_reset($form, &$form_state) {
  unset($_SESSION['stormtask_list_filter']);
}

