{title}Time & Expenses Reports{/title}
{add_bread_crumb}Filter Time & Expenses{/add_bread_crumb}

<div id="tracking_reports" class="filter_criteria">
  <form action="{assemble route=tracking_reports_run}" method="get" class="expanded">
  
    <!-- Filter Picker -->
    <div class="filter_criteria_head">
      <div class="filter_criteria_head_inner">
        <div class="filter_criteria_picker">
          {lang}Filter{/lang}: 
          <select>
            <option value="">{lang}Custom{/lang}</option>
          </select>
        </div>
        
        <div class="filter_criteria_run">{button type="submit" class="default"}Run{/button}</div>
        <div class="filter_criteria_options" style="display: none"></div>
      </div>
    </div>
    
    <div class="filter_criteria_body"></div>
  </form>
  
  <div class="filter_results"></div>
</div>

<script type="text/javascript">

  App.Wireframe.Events.bind('create_invoice_from_tracking_report.single', function (event, invoice) {
    if (invoice['class'] == 'Invoice') {
      App.Wireframe.Flash.success(App.lang('New invoice created.'));
      App.Wireframe.Content.setFromUrl(invoice['urls']['view']);
    } // if
  });


  $('#tracking_reports').each(function() {
    var wrapper = $(this);
    
    /**
     * Prepare select job type picker
     *
     * @param String submit_as
     * @param String criterion
     * @param Object filter
     * @param Object data
     */
    var prepare_select_job_type = function(submit_as, criterion, filter, data) {
      if(data['job_types']) {
        var selected_job_type_ids = typeof(filter) == 'object' && filter && filter['job_type_ids'] ? filter['job_type_ids'] : null;
        var select = $('<div class="time_report_' + criterion + '"></div>');

        for(var job_type_id in data['job_types']) {
          var id = 'time_report_' + criterion + '_' + job_type_id;
          var job_type = $('<div class="job_type"><input type="checkbox" name="' + submit_as + '[job_type_ids][]" value="' + job_type_id + '" id="' + id + '" /> <label for="' + id + '">' + data['job_types'][job_type_id].clean() + '</label></div>').appendTo(select);

          if(jQuery.isArray(selected_job_type_ids) && selected_job_type_ids.indexOf(parseInt(job_type_id)) >= 0) {
            job_type.find('input[type=checkbox]')[0].checked = true;
          } // if
        } // for

        $(this).append(select);
      } else {
        $(this).text(App.lang('There are no job types to select from'));
      } // if
    }; // prepare_select_job_type
    
    /**
     * Prepare select expense categories picker
     *
     * @param String submit_as
     * @param String criterion
     * @param Object filter
     * @param Object data
     */
    var prepare_select_expense_categories = function(submit_as, criterion, filter, data) {
      if(data['expense_categories']) {
        var selected_category_ids = typeof(filter) == 'object' && filter && filter['expense_category_ids'] ? filter['expense_category_ids'] : null;
        var select = $('<div class="time_report_' + criterion + '"></div>');

        for(var category_id in data['expense_categories']) {
          var id = 'time_report_' + criterion + '_' + category_id;
          var category = $('<div class="expense_category"><input type="checkbox" name="' + submit_as + '[expense_category_ids][]" value="' + category_id + '" id="' + id + '" /> <label for="' + id + '">' + data['expense_categories'][category_id].clean() + '</label></div>').appendTo(select);

          if(jQuery.isArray(selected_category_ids) && selected_category_ids.indexOf(parseInt(category_id)) >= 0) {
            category.find('input[type=checkbox]')[0].checked = true;
          } // if
        } // for

        $(this).append(select);
      } else {
        $(this).text(App.lang('There are no expense categories to select from'));
      } // if
    }; // prepare_select_expense_categories
    
    /**
     * Prepare select user box
     *
     * @param String submit_as
     * @param String criterion
     * @param Object filter
     * @param Object data
     */
    var prepare_select_company = function(submit_as, criterion, filter, data) {
      if(data['companies']) {
        if(criterion == 'project_filter') {
          var selected_company_id = typeof(filter) == 'object' && filter && filter['project_client_id'] ? filter['project_client_id'] : null; 
          var name = 'project_client_id';
        } else {
          var selected_company_id = typeof(filter) == 'object' && filter && filter['company_id'] ? filter['company_id'] : null; 
          var name = 'company_id';
        } // if

        var select = $('<select name="' + submit_as + '[' + name + ']"></select>');

        for(var company_id in data['companies']) {
          if(company_id == selected_company_id) {
            select.append('<option value="' + company_id + '" selected="selected">' + data['companies'][company_id].clean() + '</option>');
          } else {
            select.append('<option value="' + company_id + '">' + data['companies'][company_id].clean() + '</option>');
          } // if
        } // for

        $(this).append(select);
      } else {
        $(this).text(App.lang('There are no companies to select from'));
      } // if
    }; // prepare_select_company

    /**
     * Prepare user picker
      * 
     * @param String submit_as
     * @param String criterion
     * @param Object filter
     * @param Object data
     */
    var prepare_select_users = function(submit_as, criterion, filter, data) {
      if(data['users']) {
        var selected_user_ids = typeof(filter) == 'object' && filter && filter['user_ids'] ? filter['user_ids'] : null;
        var name = 'user_ids';

        var select = $('<div class="time_report_' + criterion + '"></div>');

        for(var company_name in data['users']) {
          var company_wrapper = $('<div class="tracking_report_select_users_company">' +
            '<div class="company_name">' + company_name.clean() + '</div>' +
            '<div class="company_users"></div>' + 
          '</div>').appendTo(select);

          var company_users_wrapper = company_wrapper.find('div.company_users');

          for(var user_id in data['users'][company_name]) {
            var id = 'time_report_' + criterion + '_' + user_id;
            var company_user = $('<div class="company_user"><input type="checkbox" name="' + submit_as + '[' + name + '][]" value="' + user_id + '" id="' + id + '" /> <label for="' + id + '">' + data['users'][company_name][user_id].clean() + '</label></div>').appendTo(company_users_wrapper);

            if(jQuery.isArray(selected_user_ids) && selected_user_ids.indexOf(parseInt(user_id)) >= 0) {
              company_user.find('input[type=checkbox]')[0].checked = true;
            } // if
          } // for
        } // for

        $(this).append(select);
      } else {
        $(this).text(App.lang('There are no users to select from'));
      } // if
    }; // prepare_select_users
    
    /**
     * Prepare select projects box
     *
     * @param String submit_as
     * @param String criterion
     * @param Object filter
     * @param Object data
     */
    var prepare_select_projects = function(submit_as, criterion, filter, data) {
      if(data['projects']) {
        var selected_project_ids = typeof(filter) == 'object' && filter && filter['project_ids'] ? filter['project_ids'] : null;
        var select = $('<div class="time_report_' + criterion + '"></div>');

        for(var project_id in data['projects']) {
          var id = 'time_report_' + criterion + '_' + project_id;
          var project = $('<div class="project"><input type="checkbox" name="' + submit_as + '[project_ids][]" value="' + project_id + '" id="' + id + '" /> <label for="' + id + '">' + data['projects'][project_id].clean() + '</label></div>').appendTo(select);

          if(jQuery.isArray(selected_project_ids) && selected_project_ids.indexOf(parseInt(project_id)) >= 0) {
            project.find('input[type=checkbox]')[0].checked = true;
          } // if
        } // for

        $(this).append(select);
      } else {
        $(this).text(App.lang('There are no projects to select from'));
      } // if
    }; // prepare_select_projects

    /**
     * Prepare select project category picker
     *
     * @param String submit_as
     * @param String criterion
     * @param Object filter
     * @param Object data
     */
    var preapre_select_project_category = function(submit_as, criterion, filter, data) {
      if(data['project_categories']) {
        var selected_category_id = typeof(filter) == 'object' && filter && filter['project_category_id'] ? filter['project_category_id'] : null;
        var select = $('<select name="' + submit_as + '[project_category_id]"></select>');

        for(var project_category_id in data['project_categories']) {
          if(project_category_id == selected_category_id) {
            select.append('<option value="' + project_category_id + '" selected="selected">' + data['project_categories'][project_category_id].clean() + '</option>');
          } else {
            select.append('<option value="' + project_category_id + '">' + data['project_categories'][project_category_id].clean() + '</option>');
          } // if
        } // for

        $(this).append(select);
      } else {
        $(this).append(App.lang('There are no project categories to select from'));
      } // if
    }; // preapre_select_project_category

    /**
     * Prepare date picker
     *
     * @param String submit_as
     * @param String criterion
     * @param Object filter
     * @param Object data
     */
    var prepare_date = function(submit_as, criterion, filter, data) {
      var name = 'date_on';
      
      if(typeof(filter) == 'object' && filter) {
        var value = filter['date_on'];
      } else {
        var value = '';
      } // if

      var select = $('<div class="select_date"><input name="' + submit_as + '[' + name + ']" value="' + (typeof(value) == 'object' && value ? value['mysql'] : '') + '" /></div>');

      select.find('input').datepicker({
        'dateFormat' : "yy/mm/dd",
        'minDate' : new Date("2000/01/01"),
        'maxDate' : new Date("2050/01/01"),
        'showAnim' : "blind",
        'duration' : 0,
        'changeYear' : true,
        'showOn' : "both",
        'buttonImage' : App.Wireframe.Utils.imageUrl('icons/16x16/calendar.png', 'tracking'),
        'buttonImageOnly' : true,
        'buttonText' : App.lang('Select Date'),
        'firstDay' : App.Config.get('first_week_day'),
        'hideIfNoPrevNext' : true,
        'defaultDate' : typeof(value) == 'object' && value ? new Date(value['mysql']) : new Date(),
      });

      $(this).append(select);
    }; // prepare_date

    /**
     * Prepare date range picker
     *
     * @param String submit_as
     * @param String criterion
     * @param Object filter
     * @param Object data
     */
    var prepare_date_range = function(submit_as, criterion, filter, data) {
      if(typeof(filter) == 'object' && filter) {
        var value_from = filter['date_from'];
        var value_to = filter['date_to'];
      } else {
        var value_from = new Date();
        var value_to = new Date();
      } // if

      if(value_from instanceof Date) {
        var value_from_str = value_from.toString('yyyy/MM/dd');
      } else if(typeof(value_from) == 'object' && value_from) {
        var value_from_str = value_from['mysql'];
      } else {
        var value_from_str = date.today().toString('yyyy/MM/dd');
      } // if

      if(value_to instanceof Date) {
        var value_to_str = value_to.toString('yyyy/MM/dd');
      } else if(typeof(value_to) == 'object' && value_to) {
        var value_to_str = value_to['mysql'];
      } else {
        var value_to_str = date.today().toString('yyyy/MM/dd');
      } // if

      var select = $('<div class="select_range">' + 
        '<div class="select_date range_from"><span>' + App.lang('From') + ':</span><span><input name="' + submit_as + '[date_from]" value="' + value_from_str + '"></span></div>' +
        '<div class="select_date range_to"><span>' + App.lang('To') + ':</span><span><input name="' + submit_as + '[date_to]" value="' + value_to_str + '"></span></div>' +
      '</div>');

      var datepicker_settings = {
        'dateFormat' : "yy/mm/dd",
        'minDate' : new Date("2000/01/01"),
        'maxDate' : new Date("2050/01/01"),
        'showAnim' : "blind",
        'duration' : 0,
        'changeYear' : true,
        'showOn' : "both",
        'buttonImage' : App.Wireframe.Utils.imageUrl('icons/16x16/calendar.png', 'tracking'),
        'buttonImageOnly' : true,
        'buttonText' : App.lang('Select Date'),
        'firstDay' : App.Config.get('first_week_day'),
        'hideIfNoPrevNext' : true
      };

      select.find('div.select_date.range_from input').datepicker(jQuery.extend(datepicker_settings, {
        'defaultDate' : typeof(value_from) == 'object' && value_from ? new Date(value_from['mysql']) : new Date()
      }));

      select.find('div.select_date.range_to input').datepicker(jQuery.extend(datepicker_settings, {
        'defaultDate' : typeof(value_to) == 'object' && value_to ? new Date(value_to['mysql']) : new Date()
      }));

      $(this).append(select);
    }; // prepare_date_range
    
    wrapper.filterCriteria({
      'options' : {
        'sum_by_user' : {
          'label' : App.lang('Sum by User'), 
          'selected' : true
        }
      },
      'on_result_links' : function(response, data, links) {
        links.push({
          'text' : App.lang('Export CSV'), 
          'url' : '{assemble route=tracking_reports_export}', 
          'download' : true
        });

        {if $invoice_based_on_url}
        links.push({
          'text' : App.lang('Create Invoice'), 
          'url' : {$invoice_based_on_url|json nofilter},
          'init' : function() {
            $(this).flyoutForm({
              'title' : App.lang('Create Invoice based on Time Report'),
              'success_event' : 'create_invoice_from_tracking_report'
            });
          }
        });
        {/if}
      }, 
      'criterions' : {
        'type_filter' : {
          'label' : App.lang('Show'), 
          'choices' : {
            'any' : App.lang('Time & Expenses'), 
            'time' : App.lang('Time Only'), 
            'expenses' : App.lang('Expenses Only')
          }
        }, 
        'job_type_filter' : {
          'label' : App.lang('Job Type'), 
          'choices' : {
            'any' : App.lang('Any'), 
            'selected' : {
              'label' : App.lang('Selected Types ...'), 
              'prepare' : prepare_select_job_type
            }
          }
        },
        'expense_category_filter' : {
          'label' : App.lang('Expense Category'), 
          'choices' : {
            'any' : App.lang('Any'), 
            'selected' : {
              'label' : App.lang('Selected Categories ...'), 
              'prepare' : prepare_select_expense_categories
            }
          }
        }, 
        'user_filter' : {
          'label' : App.lang('Assigned To'), 
          'choices' : {
            'anybody' : App.lang('Anybody'), 
            'logged_user' : App.lang('Person Accessing This Report'), 
            'company' : {
              'label' : App.lang('Member of a Company ...'), 
              'prepare' : prepare_select_company
            },
            'selected' : {
              'label' : App.lang('Selected Users ...'), 
              'prepare' : prepare_select_users
            }
          }
        }, 
        'date_filter' : {
          'label' : App.lang('For Day'), 
          'choices' : {
            'any' : App.lang('Any Day'), 
            'last_month' : App.lang('Last Month'), 
            'last_week' : App.lang('Last Week'), 
            'yesterday' : App.lang('Yesterday'), 
            'today' : App.lang('Today'), 
            'this_week' : App.lang('Week'), 
            'this_month' : App.lang('This Month'), 
            'selected_date' : {
              'label' : App.lang('Selected Date ...'), 
              'prepare' : prepare_date
            }, 
            'selected_range' : {
              'label' : App.lang('Selected Date Range ...'), 
              'prepare' : prepare_date_range
            }
          }
        }, 
        'project_filter' : {
          'label' : App.lang('Projects'), 
          'choices' : {
            'any' : App.lang('Any Project'), 
            'active' : App.lang('Active Projects'), 
            'completed' : App.lang('Completed Projects'), 
            'category' : {
              'label' : App.lang('From Category ...'), 
              'prepare' : preapre_select_project_category
            }, 
            'client' : {
              'label' : App.lang('For Client ...'), 
              'prepare' : prepare_select_company
            },  
            'selected' : {
              'label' : App.lang('Selected Projects ...'),
              'prepare' : prepare_select_projects 
            } 
          }
        }, 
        'billable_status_filter' : {
          'label' : App.lang('Status'), 
          'choices' : {
            'all' : App.lang('Any'), 
            'not_billable' : App.lang('Non-Billable'), 
            'billable' : App.lang('Billable'), 
            'pending_payment' : App.lang('Pending Payment'), 
            'billable_not_paid' : App.lang('Not Yet Paid (Billable or Pending Payment)'), 
            'billable_paid' : App.lang('Already Paid')
          }
        }, 
        'group_by' : {
          'label' : App.lang('Group By'), 
          'choices' : {
            'all' : App.lang("Don't Group"), 
            'date' : App.lang('by Date'), 
            'project' : App.lang('by Project'), 
            'project_client' : App.lang('by Project Client')
          }
        }
      }, 
      'filters' : {$tracking_reports|json nofilter},
      'new_filter_url' : '{assemble route=tracking_reports_add}',
      'can_add_filter' : true,
      'on_show_results' : function(response, data, form_data) {
        var results_wrapper = $(this);
        
        // Settings that affect the way results are displayed
        var sum_by_user = false;
        var group_by = 'dont';
        var show_time = true;
        var show_expenses = true;
        
        if(jQuery.isArray(form_data)) {
          for(var i in form_data) {
            if(form_data[i]['name'] == 'filter[sum_by_user]') {
              sum_by_user = form_data[i]['value'] == '1';
            } else if(form_data[i]['name'] == 'filter[group_by]') {
              group_by = form_data[i]['value'];
            } else if(form_data[i]['name'] == 'filter[type_filter]') {
              show_time = form_data[i]['value'] == 'any' || form_data[i]['value'] == 'time';
              show_expenses = form_data[i]['value'] == 'any' || form_data[i]['value'] == 'expenses';
            } // if
          } // for
        } // if
        
        // Display results summarized by user
        if(sum_by_user) {

          App.each(response, function (group_id, group) {
          	if(typeof(group['records']) == 'object' && !jQuery.isEmptyObject(group['records'])) {
              var group_label = typeof(group['label']) == 'string' ? group['label'] : '--';
              var group_wrapper = $('<div class="tracking_report_result_group_wrapper">' +
                '<h2>' + group_label.clean() + '</h2>' + 
                '<div class="tracking_report_result_group_inner_wrapper"></div>' + 
              '</div>').appendTo(results_wrapper);

              var group_table = $('<table class="common auto summarized" cellspacing="0">' + 
                '<thead><tr><th class="user">' + App.lang('User') + '</th></tr></thead>' +
                '<tbody></tbody>' + 
                '<tfoot><tr><td class="total">' + App.lang('Total') + ':</td></tr></tfoot>' +
              '</table>').appendTo(group_wrapper.find('div.tracking_report_result_group_inner_wrapper'));
              
              if(show_time || show_expenses) {
                var header = group_table.find('thead tr');
                var footer = group_table.find('tfoot tr');
                
                if(show_time) {
                  header.append('<th class="time center">' + App.lang('Time') + '</th>');
                  footer.append('<td class="time center"></td>');
                } // if
                
                if(show_expenses) {
                  for(var currency_id in data['currencies']) {
                    header.append('<th class="expenses center" currency_id="' + currency_id + '">' + App.lang('Expenses (:currency_code)', {
                      'currency_code' : data['currencies'][currency_id]['code']
                    }) + '</th>');
                    footer.append('<td class="expenses center" currency_id="' + currency_id + '"></td>');
                  } // for
                } // if
              } // if
              
              var group_table_body = group_table.find('tbody');

              var total_time = 0;
              var total_expenses = {};

              for(var currency_id in data['currencies']) {
                total_expenses[currency_id] = 0;
              } // for

              App.each(group['records'], function(user_email, record) {
                if(show_time) {
                  total_time += record['time'];
                } // if
                
                if(show_expenses) {
                  for(var currency_id in data['currencies']) {
                    total_expenses[currency_id] += record['expenses_for_' + currency_id];
                  } // for
                } // if
                
                var row = '<tr class="record summarized" user_id="' + record['user_id'] + '" user_email="' + user_email.clean() + '">';
                
                row += '<td class="user">' + record['user_name'].clean() + '</td>';
                
                if(show_time) {
                  row += '<td class="time center">' + App.hoursFormat(record['time']) + '</td>';
                } // if
                
                if(show_expenses) {
                  for(var currency_id in data['currencies']) {
                    row += '<td class="expenses center" currency_id="' + currency_id + '">' + App.moneyFormat(record['expenses_for_' + currency_id]) + '</td>';
                  } // for
                  //row += '<td class="expenses center">' + App.moneyFormat(response[group_id]['records'][user_email]['expenses']) + '</td>';
                } // if
                
                group_table_body.append(row + '</tr>');
              }); // each
              
              if(group_table_body.find('tr.record').length > 1) {
                if(show_time && group_table_body.find('tr.record').length > 1) {
                  footer.find('td.time').text(App.hoursFormat(total_time));
                } // if
              
                if(show_expenses) {
                  for(var currency_id in data['currencies']) {
                    footer.find('td.expenses[currency_id=' + currency_id + ']').text(App.moneyFormat(total_expenses[currency_id]));
                  } // for
                } // if
              } else {
                group_table.find('tfoot').remove();
              } // if 
            } // if
          }); // each
          
        // Display a list of records that match given filter criteria
        } else {
          switch(group_by) {
            case 'date':
              var columns = [ App.lang('Value'), App.lang('User'), App.lang('Summary'), App.lang('Status'), App.lang('Project') ]; break;
            case 'project':
              var columns = [ App.lang('Date'), App.lang('Value'), App.lang('User'), App.lang('Summary'), App.lang('Status') ]; break;
            default:
              var columns = [ App.lang('Date'), App.lang('Value'), App.lang('User'), App.lang('Summary'), App.lang('Status'), App.lang('Project') ];
          } // switch

          /**
           * Render record date
           *
           * @param Object record
           * @return string
           */
          var render_date = function(record) {
            return typeof(record['record_date']) == 'object' && record['record_date'] ? record['record_date']['formatted_date_gmt'].clean() : '--';
          }; // render_date

          /**
           * Render record user
           *
           * @param Object record
           * @return string
           */
          var render_user = function(record) {
            return typeof(record['user_name']) == 'string' && record['user_name'] ? record['user_name'] : record['user_email'];
          }; // render_user

          /**
           * Render tracked value
           *
           * @param Object record
           * @return string
           */
          var render_value = function(record) {
            if(record['type'] == 'TimeRecord') {
              if(typeof(record['group_name']) != 'undefined' && record['group_name']) {
                return App.lang(':hours of :job_type', {
                  'hours' : App.hoursFormat(record['value']), 
                  'job_type' : record['group_name']
                });
              } else {
                return App.hoursFormat(record['value']);
              } // if
            } else {
              var currency_id = typeof(record['currency_id']) != 'undefined' ? record['currency_id'] : 0;

              if(currency_id && typeof(data['currencies'][currency_id]) == 'object') {
                var currency_code = data['currencies'][currency_id]['code'];
              } else {
                var currency_code = '';
              } // if
              
              if(typeof(record['group_name']) != 'undefined' && record['group_name']) {
                return App.lang(':amount in :category', {
                  'amount' : currency_code.clean() + ' ' + App.moneyFormat(record['value']), 
                  'category' : record['group_name']
                });
              } else {
                return currency_code.clean() + App.moneyFormat(record['value']);
              } // if
            } // if
          }; // render_value

          /**
           * Render time record summary
           *
           * @param Object record
           * @return string
           */
          var render_summary = function(record) {
            if(record['parent_type'] == 'Task' && record['parent_name'] && record['parent_url']) {
              var parent_text = '<a href="' + record['parent_url'].clean() + '">' + record['parent_name'].clean() + '</a>';
            } else {
              var parent_text = '';
            } // if

            if(typeof(record['summary']) == 'string' && record['summary']) {
              var summary_text = record['summary'].clean();
            } else {
              var summary_text = '';
            } // if

            if(parent_text && summary_text) {
              return parent_text + ' (' + summary_text + ')';
            } else if(parent_text) {
              return parent_text;
            } else if(summary_text) {
              return summary_text;
            } else {
              return '';
            } // if
          }; // render_summary

          /**
           * Render record status
           *
           * @param Object record
           * @return string
           */
          var render_status = function(record) {
            switch(record['billable_status']) {
              case 0:
                return App.lang('Not Billable');
              case 1:
                return App.lang('Billable');
              case 2:
                return App.lang('Pending Payment');
              case 3:
                return App.lang('Paid');
              default:
                return App.lang('Unknown Status');
            } // switch
          }; // render_status

          /**
           * Render project name
           *
           * @param Object record
           * @return string
           */
          var render_project = function(record) {
            return typeof(record['project_name']) == 'string' && record['project_name'] && typeof(record['project_url']) == 'string' && record['project_url'] ? '<a href="' + record['project_url'].clean() + '">' + record['project_name'].clean() + '</a>' : App.lang('Unknown Project');
          }; // render_project

          App.each(response, function(group_id, group) {
          
            if(jQuery.isArray(group['records']) && group['records'].length) {
              var group_label = typeof(group['label']) == 'string' ? group['label'] : '--';
              var group_wrapper = $('<div class="tracking_report_result_group_wrapper">' +
                '<h2>' + group_label.clean() + '</h2>' + 
                '<div class="tracking_report_result_group_inner_wrapper"></div>' + 
              '</div>').appendTo(results_wrapper);

              var group_table = $('<table class="common records_list" cellspacing="0">' + 
                '<thead></thead>' +
                '<tbody></tbody>' + 
              '</table>').appendTo(group_wrapper.find('div.tracking_report_result_group_inner_wrapper'));

              var group_table_head = group_table.find('thead');
              var group_table_body = group_table.find('tbody');

              switch(group_by) {
  
                // Render row content for reported grouped by date
                case 'date':
                  group_table_head.append('<tr>' + 
                    '<th class="value">' + App.lang('Value') + '</th>' + 
                    '<th class="user">' + App.lang('User') + '</th>' + 
                    '<th class="summary">' + App.lang('Summary') + '</th>' + 
                    '<th class="status center">' + App.lang('Status') + '</th>' + 
                    '<th class="project right">' + App.lang('Project') + '</th>' + 
                  '</tr>');
  
                  break;
  
                // Render row content for report grouped by project
                case 'project':
                  group_table_head.append('<tr>' + 
                    '<th class="date left">' + App.lang('Date') + '</th>' + 
                    '<th class="value">' + App.lang('Value') + '</th>' + 
                    '<th class="user">' + App.lang('User') + '</th>' + 
                    '<th class="summary">' + App.lang('Summary') + '</th>' + 
                    '<th class="status center">' + App.lang('Status') + '</th>' + 
                  '</tr>');
  
                  break;
  
                // Render row content for report that's not grouped or for report that's grouped by project client
                default:
                  group_table_head.append('<tr>' + 
                    '<th class="date left">' + App.lang('Date') + '</th>' + 
                    '<th class="value">' + App.lang('Value') + '</th>' + 
                    '<th class="user">' + App.lang('User') + '</th>' + 
                    '<th class="summary">' + App.lang('Summary') + '</th>' + 
                    '<th class="status center">' + App.lang('Status') + '</th>' + 
                    '<th class="project right">' + App.lang('Project') + '</th>' + 
                  '</tr>');
  
                  break;
              } // switch

              var total_time = 0;
              var total_expenses = {};

							App.each(group['records'], function(record_id, record) {
              
                if(record['type'] == 'TimeRecord') {
                  var record_type = 'time_record';
                  total_time += record['value'];
                } else {
                  var record_type = 'expense';
                  
                  var currency_id = record['currency_id'];

                  if(typeof(total_expenses[currency_id]) == 'undefined') {
                    total_expenses[currency_id] = 0;
                  } // if  

                  total_expenses[currency_id] += record['value'];
                } // if

                // Open row and set properties
                var row = '<tr class="record ' + record_type + '" record_id="' + record_id + '" user_id="' + record['user_id'] + '" currency_id="' + record['currency_id'] + '">';

                switch(group_by) {

                  // Render row content for reported grouped by date
                  case 'date':
                    row += '<td class="value">' + render_value(record) + '</td>';
                    row += '<td class="user">' + render_user(record) + '</td>';
                    row += '<td class="summary">' + render_summary(record) +'</td>';
                    row += '<td class="status center">' + render_status(record) + '</td>';
                    row += '<td class="project right">' + render_project(record) + '</td>';

                    break;

                  // Render row content for report grouped by project
                  case 'project':
                    row += '<td class="date left">' + render_date(record) + '</td>';
                    row += '<td class="value">' + render_value(record) + '</td>';
                    row += '<td class="user">' + render_user(record) + '</td>';
                    row += '<td class="summary">' + render_summary(record) +'</td>';
                    row += '<td class="status center">' + render_status(record) + '</td>';

                    break;

                  // Render row content for report that's not grouped or for report that's grouped by project client
                  default:
                    row += '<td class="date left">' + render_date(record) + '</td>';
                    row += '<td class="value">' + render_value(record) + '</td>';
                    row += '<td class="user">' + render_user(record) + '</td>';
                    row += '<td class="summary">' + render_summary(record) +'</td>';
                    row += '<td class="status center">' + render_status(record) + '</td>';
                    row += '<td class="project right">' + render_project(record) + '</td>';

                    break;
                } // switch

                group_table_body.append(row + '</tr>');
              }); // each

              var total_time_string = App.lang('Total Time: :time', {
                'time' : App.hoursFormat(total_time)
              });

              var total_expenses_by_currency = [];

              for(var currency_id in total_expenses) {
                if(currency_id && typeof(data['currencies'][currency_id]) == 'object') {
                  var currency_code = data['currencies'][currency_id]['code'];
                } else {
                  var currency_code = '';
                } // if

                total_expenses_by_currency.push(App.moneyFormat(total_expenses[currency_id], currency_code));
              } // for

              if(total_expenses_by_currency.length < 1) {
                var total_expenses_string = App.lang('Total Expenses: :expenses', {
                  'expenses' : 0
                });
              } else {
                var total_expenses_string = App.lang('Total Expenses: :expenses', {
                  'expenses' : total_expenses_by_currency.join(', ')
                });
              } // if

              group_table_body.after('<tfoot><tr><td colspan="' + columns.length + '">' + total_time_string.clean() + '. ' + total_expenses_string.clean() + '</td></tr></tfoot>');
            } // if
          }); // each
        } // if
      },
      'data' : {
        'companies' : {$companies|json nofilter},
        'users' : {$users|json nofilter},
        'projects' : {$projects|json nofilter},
        'project_categories' : {$project_categories|json nofilter},
        'job_types' : {$job_types|json nofilter},
        'expense_categories' : {$expense_categories|json nofilter},
        'currencies' : {$currencies|json nofilter}
      }
    });
  });
</script>