#encoding: utf-8
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper

  ##
  ## Fehlerkonstanten für Formularüberprüfung (seit Dez. 2012, nbw)
  ##
  ## ANFANG
  ERROR_PL_N_ANH1_ID=1 # ok
  ERROR_PL_NCOM_ID=2 # ok
  ERROR_PL_P_ANH1_ID=3 # ok
  ERROR_PL_PCOM_ID=4 # ok
  ERROR_PL_N = 5 # ok
  ERROR_PL_N100 = 6 # ok
  ERROR_PL_P = 7 # ok
  ERROR_PL_P100 = 8 # ok
  ERROR_PL_COD = 9 # ok
  ERROR_PL_COD100 = 10 # ok
  ERROR_PL_BOD = 11 # ok
  ERROR_PL_BOD100 = 12 # ok
  ERROR_PL_CITY_ID = 13 # ok
  ERROR_PL_OTHER_COMMENT = 14 # ok

  ERROR_AG_REMARK_CHANGE = 15 # ok
  ERROR_AGG_C2_PT = 16 # ok
  ERROR_AGG_C2_FT = 17 # ok
  ERROR_AGG_C2_ST = 18 # ok
  ERROR_AGG_DATE_COLL = 19 # ok

  ERROR_DP_GWBODY_ID = 20 #ok
  ERROR_DP_WATERBODY_ID = 21 # ok
  ERROR_DP_SURFACE_LAND_ID = 22 # ok

  ERROR_AG_TO_BE_REPORTED = 23
  ERROR_AG_STATE_ACTIVE = 24

  ERROR_PL_TO_BE_REPORTED = 25
  ERROR_PL_STATE_ACTIVE = 26

  ERROR_DP_TO_BE_REPORTED = 27
  ERROR_DP_STATE_ACTIVE = 28

  ERROR_PL_CD = 29 # ok
  ERROR_PLANT_ID = 30
  ERROR_AG_NLOAD = 31

  ERROR_WRONG_TYPE = 254 # ok
  ERROR_REQUIRED = 255 # ok
  ERROR_KEY_REQUIRED = 256 # ok
  NO_ERROR = 0 # ok

  $x=0

  def zeile
    if $x==0
      $x=1
    else
      $x=0
    end
  end

  def reset_x
    $x=0
  end

  def error_class(errno)
    if errno.to_i.between?(1, 200) # Abhängige Pflichtfelder
      return "cond_required"
    elsif errno == ERROR_WRONG_TYPE # Falscher Datentyp
      return "wrong_type"
    elsif errno == ERROR_REQUIRED # Pflichtfeld
      return "required"
    elsif errno == ERROR_KEY_REQUIRED # Schlüsselfeld
      return "key_required"
    else # Alles in Ordnung
      return ""
    end
  end

  def error_text(errno)
    if errno.to_i.between?(1, 200) # Abhängige Pflichtfelder
      return "Abhängiges Pflichtfeld nicht ausgefüllt"
    elsif errno == ERROR_WRONG_TYPE # Falscher Datentyp
      return "Falscher Datentyp"
    elsif errno == ERROR_REQUIRED # Pflichtfeld
      return "Pflichtfeld nicht ausgefüllt"
    elsif errno == ERROR_KEY_REQUIRED # Schlüsselfeld
      return "Schlüsselfeld nicht angegeben (beim Anlegen)"
    else # Alles in Ordnung
      return ""
    end
  end

  def doku_link(errno)
    site=controller.class::LINK
    #if errno.to_i.between?(ERROR_AG_REMARK_CHANGE, ERROR_AGG_DATE_COLL) or errno.to_i == ERROR_PL_CITY_ID
    #  site='Agglomerationen_%28gemeindliche_Gebiete%29'
    #elsif errno.to_i.between?(ERROR_DP_GWBODY_ID, ERROR_DP_SURFACE_LAND_ID)
    #  site='Einleitstellen'
    #else
    #  site=''S
    #end

    if errno == 0
      return ""
    else
      msg=''
      msg<< %Q^<a href="#{site}##{errno.to_s}" target="#{controller.class::NAME}_Doku"><i class="fa fa-question-circle-o doku-link" aria-hidden="true" alt="Zur Onlinedokumentation" title="Zur Online-Dokumentation"></i></a>^
      return msg
    end
  end

  def input_for(field, data, disabled) #, disabled   disabled muss implementiert werden, :disabled => disabled , :readonly => disabled
    if (field.is_locked? || (data.id && field.is_key_or_locked?))
      if field.has_select?
           option = field.reference.options.select do |opt|
             opt[2].to_i==data[field].to_i
           end

        return text_field_tag(field['col_name'], option.first[1], :disabled => true, :readonly => true).html_safe
      end
      return text_field_tag(field['col_name'], data[field], :disabled => true, :readonly => true).html_safe
    end

    # Listeneinschraenkung auf Datenbankebene nicht mehr vorhanden
    # -> wir schraenken auf Anwendungseben ein
    if (field['reference_type'].to_i == 6)
      bulas = field.reference.options.select do |opt|
         theUser(session).get_states_for_write.include?(opt[2]);
      end
      return select_tag(field['col_name'], options_for_select_with_title(bulas, data[field]), :disabled => disabled).html_safe if field.has_select?
    # Verwaltendes Bundesland standardmaessig mit eigener ID fuellen
    elsif (field['col_name'].eql?("handled_by_federal_state_id"))
      user = theUser(session)

      # Wenn nur Verwaltungsrecht & kein Besitzer -> read only
      # data[field] => Verwaltendes Bundesland
      # woher nehmen wir die ID der Entitaet?
      if ( false && !user.is_admin? && data[field]!= nil && !user.get_states_for_read.include?(data[field]) )
           option = field.reference.options.select do |opt|
             opt[2].to_i==data[field].to_i
           end
        return text_field_tag(field['col_name'], option.first[1], :disabled => true, :readonly => true).html_safe
      # Wenn Eigentümer dann darf das Recht zum Bearbeiten vergeben werden
      else
         bulas_with_empty =  field.reference.options.unshift([' ', nil])
         return select_tag(field['col_name'], options_for_select_with_title(bulas_with_empty, data[field]), :disabled => disabled).html_safe if field.has_select?
      end
    end

    if data['rep_code']
     rep_code = data['rep_code']
    else
     rep_code = @gen.reporting_period.key_report
    end

    return case field['reference_type'].to_i
             when 5 then
               self.method(field['col_name']+'_select').call(data).html_safe
             when 1, 2, 6 then
                  select_tag(field['col_name'], options_for_select_with_title(field.reference.options, data[field]), :disabled => disabled).html_safe if field.has_select?
             when 10 then
               controller.limited_list(field['col_name'], "Nuts-Regionen", field['foreign_table'],  data['federal_state_id'], false, data[field], disabled, rep_code).html_safe
             when 12 then
               controller.limited_list(field['col_name'], field['human_name'], field['foreign_table'], data['federal_state_id'], false, data[field], disabled, rep_code).html_safe
             when 13 then
               controller.method('get_' + field['col_name']).call(data).html_safe
             when 3 then
               select_tag(field['col_name'], options_for_select([[' ', nil], ['Nein', '0'], ['Ja', '1']], data[field] == 1? "1" : data[field] == nil ? "" : "0") , :disabled => disabled).html_safe
             when 7 then
               text_area_tag(field['col_name'], data[field], :readonly => disabled).html_safe
             when 9, 91 then
               text_field_tag(field['col_name'], (data[field].to_s.sub(/\./, ',') rescue nil), :readonly => disabled).html_safe
             else
               text_field_tag(field['col_name'], data[field], :readonly => disabled).html_safe
           end
  end

  def format_value_for(value, type = 0)
    return nil if value.nil?
    return case type
             when 9, 91 then
               value.to_s.sub(/\./, ',').html_safe
             when 3 then
               value.to_i == 1 ? 'Ja' : 'Nein'
             else
               value.to_s.html_safe
           end
  end

  def value_for(field, data)
    return format_value_for(data[field], field['reference_type'].to_i)
  end

  def get_error_class(field, data)
    cls = error_class(get_errno(field, data))

    if cls.length > 0
      return "key #{error_class(get_errno(field, data))}"
    else
      return ""
    end


  end

  def name_for(field, data)
    errno = get_errno(field, data)

    classes = "key"

    if error_class(errno) != ""
      classes += " " + error_class(errno)
    end

    if field['field_mode'].to_i == 3
      classes += " " + "predefined"
    end

    if data.errors.any? && data.errors[0][0] == field['human_name']
      classes += " " + "error"
    end

    str =  "<td class='#{classes}'>" + doku_link(errno) + "</td>"
    str += "<td class='#{classes}'>" +('*'*field['field_mode'].to_i)+ "</td>"
    str += "<td class='#{classes}' title='" + field['description'] +  "'>" +field['human_name']+"</td>"

    return str.html_safe
  end

  def data_for(field, data)
    logger.info "Data for: #{field['col_name']} = #{data}"
    errno = get_errno(field, data)
    str = '<td '
    #str << 'title="'+error_message(errno)+'"'
    str << ' id="plant-view"' if field['col_name']=='plants' || field['col_name'] == 'plant_id'
    str << ' id="dp-view"' if field['col_name']=='discharge_points'
    str << ' id="agg-view"' if field['col_name']=='agglomerations'
    str << ' id="successor-view"' if field['col_name']=='successors'
    str << ' class="key input-field '
    str << error_class(errno)
    #str << chk_required(field, data) #string that contains additional class for this field according to require_status
    str << ' error' if data.errors.any? { |e| e[0] == field['human_name'] }
    str << '">'
    str << input_for(field, data, data.read_only_or_locked?)
    str << '</td>'
    return str.html_safe
  end

  def get_errno(field, data)
    state = data['agg_state_active'] || data['pl_state_active'] || data['dp_state_active']
    reported = data['ag_to_be_reported'] || data['pl_to_be_reported'] || data['dp_to_be_reported']
    returnStatus =NO_ERROR # integer als verweis auf die fehlertabelle

    unless (state == '0' || reported == '0')
      returnStatus = case field['col_name']
                       when 'pl_n_anh1_id' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_n_anh1_id'].blank?) ? ERROR_PL_N_ANH1_ID : NO_ERROR
                       when 'pl_ncom_id' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_ncom_id'].blank?) ? ERROR_PL_NCOM_ID : NO_ERROR
                       when 'pl_p_anh1_id' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_p_anh1_id'].blank?) ? ERROR_PL_P_ANH1_ID : NO_ERROR
                       when 'pl_pcom_id' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_pcom_id'].blank?) ? ERROR_PL_PCOM_ID : NO_ERROR

                       when 'pl_n' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_n'].to_i <= 0 && data['pl_n100'].to_i <= 0) ? ERROR_PL_N : NO_ERROR
                       when 'pl_n100' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_n'].to_i <= 0 && data['pl_n100'].to_i <= 0) ? ERROR_PL_N100 : NO_ERROR
                       when 'pl_p' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_p'].to_i <= 0 && data['pl_p100'].to_i <= 0) ? ERROR_PL_P : NO_ERROR
                       when 'pl_p100' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_p'].to_i <= 0 && data['pl_p100'].to_i <= 0) ? ERROR_PL_P100 : NO_ERROR

                       when 'pl_cod' then
                         (data['pl_cod'].to_i <= 0 && data['pl_cod100'].to_i <= 0) ? ERROR_PL_COD : NO_ERROR
                       when 'pl_cod100' then
                         (data['pl_cod'].to_i <= 0 && data['pl_cod100'].to_i <= 0) ? ERROR_PL_COD100 : NO_ERROR
                       when 'pl_bod' then
                         (data['pl_bod'].to_i <= 0 && data['pl_bod100'].to_i <= 0) ? ERROR_PL_BOD : NO_ERROR
                       when 'pl_bod100' then
                         (data['pl_bod'].to_i <= 0 && data['pl_bod100'].to_i <= 0) ? ERROR_PL_BOD100 : NO_ERROR

                       when 'pl_city_id' then
                         ((data['ag_city'].nil? or data['ag_city'].to_i == 1) && data['pl_city_id'].blank?) ? ERROR_PL_CITY_ID : NO_ERROR
                       when 'pl_other_comment' then
                         (data['pl_other'].to_i == 1 && data['pl_other_comment'].blank?) ? ERROR_PL_OTHER_COMMENT : NO_ERROR
                       when 'ag_remark_change' then
                         ((data['ag_change_nload'].nil? or data['ag_change_nload'].to_i == 1) && data['ag_remark_change'].blank?) ? ERROR_AG_REMARK_CHANGE : NO_ERROR
                       when 'agg_c2_pt' then
                         ((data['ag_nload'].blank? or data['agg_c2'].blank? or (data['ag_nload'].to_f > 100000 and data['ag_nload'].to_f * data['agg_c2'].to_f > 200000)) && data['agg_c2_pt'].blank? && data['agg_c2_st'].blank? && data['agg_c2_ft'].blank?) ? ERROR_AGG_C2_PT : NO_ERROR
                       when 'agg_c2_st' then
                         ((data['ag_nload'].blank? or data['agg_c2'].blank? or (data['ag_nload'].to_f > 100000 and data['ag_nload'].to_f * data['agg_c2'].to_f > 200000)) && data['agg_c2_pt'].blank? && data['agg_c2_st'].blank? && data['agg_c2_ft'].blank?) ? ERROR_AGG_C2_FT : NO_ERROR
                       when 'agg_c2_ft' then
                         ((data['ag_nload'].blank? or data['agg_c2'].blank? or (data['ag_nload'].to_f > 100000 and data['ag_nload'].to_f * data['agg_c2'].to_f > 200000)) && data['agg_c2_pt'].blank? && data['agg_c2_st'].blank? && data['agg_c2_ft'].blank?) ? ERROR_AGG_C2_ST : NO_ERROR
                       when 'agg_date_coll' then
                         ((data['agg_not_collected'].nil? or data['agg_not_collected'].to_i > 0) && data['agg_date_coll'].blank?) ? ERROR_AGG_DATE_COLL : NO_ERROR
                       when 'dp_gwbody_id' then
                         (data['dp_waterbody_id'].blank? && data['dp_gwbody_id'].blank?) ? ERROR_DP_GWBODY_ID : NO_ERROR
                       when 'dp_waterbody_id' then
                         (data['dp_waterbody_id'].blank? && data['dp_gwbody_id'].blank?) ? ERROR_DP_WATERBODY_ID : NO_ERROR
                       when 'dp_gwbody_id' then
                         (data['rb_type_id'].to_i == 1 && data['dp_gwbody_id'].blank?) ? ERROR_DP_GWBODY_ID : NO_ERROR # TODO: MARKER
                       when 'dp_surface_land_id' then
                         (data['dp_surface_id'].to_i == 1 && data['dp_surface_land_id'].blank?) ? ERROR_DP_SURFACE_LAND_ID : NO_ERROR
                       else
                         (data[field].blank? && (1..2).include?(field['field_mode'].to_i)) ? (field['field_mode'].to_i == 2 ? ERROR_KEY_REQUIRED : ERROR_REQUIRED) : NO_ERROR
                     end
    else
      returnStatus = case field['col_name']
                       when 'ag_to_be_reported' then
                         (data['ag_to_be_reported'] == '0' && data['agg_state_active'].to_i == 0) ? ERROR_AG_TO_BE_REPORTED : NO_ERROR
                       when 'agg_state_active' then
                         (data['ag_to_be_reported'] == '0' && data['agg_state_active'].to_i == 0) ? ERROR_AG_STATE_ACTIVE : NO_ERROR
                       when 'pl_to_be_reported' then
                         (data['pl_to_be_reported'] == '0' && data['pl_state_active'].to_i == 0) ? ERROR_PL_TO_BE_REPORTED : NO_ERROR
                       when 'pl_state_active' then
                         (data['pl_to_be_reported'] == '0' && data['pl_state_active'].to_i == 0) ? ERROR_PL_STATE_ACTIVE : NO_ERROR
                       when 'dp_to_be_reported' then
                         (data['dp_to_be_reported'] == '0' && data['dp_state_active'].to_i == 0) ? ERROR_DP_TO_BE_REPORTED : NO_ERROR
                       when 'dp_state_active' then
                         (data['dp_to_be_reported'] == '0' && data['dp_state_active'].to_i == 0) ? ERROR_DP_STATE_ACTIVE : NO_ERROR
                       when 'pl_cd' then
                         (data['pl_state_active'] == '0' && data['pl_cd'].nil?) ? ERROR_PL_CD : NO_ERROR
                       when 'plant_id' then
                         (data['dp_to_be_reported'] == '0' && data['plant_id'].nil?) ? ERROR_PLANT_ID : NO_ERROR
                       when 'ag_nload' then
                         (data['ag_to_be_reported'] == '0' && data['ag_nload'].nil?) ? ERROR_AG_NLOAD : NO_ERROR
                       else
                         NO_ERROR
                     end
    end
    if returnStatus == NO_ERROR && !data[field].nil?
      returnStatus = case field['reference_type']
                       when '8' then
                         data[field].to_i <= 0 ? ERROR_WRONG_TYPE : NO_ERROR
                       when '81' then
                         data[field].to_i <= 0 && data[field].strip != '0' ? ERROR_WRONG_TYPE : NO_ERROR
                       when '9' then
                         data[field].to_f <= 0.0 ? ERROR_WRONG_TYPE : NO_ERROR
                       when '91' then
                         data[field].to_f <= 0.0 && data[field].strip[0, 1] != '0' ? ERROR_WRONG_TYPE : NO_ERROR
                       else
                         returnStatus
                     end
    end
    return returnStatus
  end

  def chk_required(field, data)
    state = data['agg_state_active'] || data['pl_state_active'] || data['dp_state_active']
    reported = data['ag_to_be_reported'] || data['pl_to_be_reported'] || data['dp_to_be_reported']
    status_class = ''
    unless (state == '0' || reported == '0')
      status_class = case field['col_name']
                       when 'pl_n_anh1_id' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_n_anh1_id'].blank?) ? ' cond_required' : ''
                       when 'pl_ncom_id' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_ncom_id'].blank?) ? ' cond_required' : ''
                       when 'pl_p_anh1_id' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_p_anh1_id'].blank?) ? ' cond_required' : ''
                       when 'pl_pcom_id' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_pcom_id'].blank?) ? ' cond_required' : ''
                       when 'pl_n' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_n'].to_i <= 0 && data['pl_n100'].to_i <= 0) ? ' cond_required' : ''
                       when 'pl_n100' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_n'].to_i <= 0 && data['pl_n100'].to_i <= 0) ? ' cond_required' : ''
                       when 'pl_p' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_p'].to_i <= 0 && data['pl_p100'].to_i <= 0) ? ' cond_required' : ''
                       when 'pl_p100' then
                         ((data['pl_odc'].nil? or data['pl_odc'].to_i > 10000) && data['pl_p'].to_i <= 0 && data['pl_p100'].to_i <= 0) ? ' cond_required' : ''
                       when 'pl_cod' then
                         (data['pl_cod'].to_i <= 0 && data['pl_cod100'].to_i <= 0) ? ' cond_required' : ''
                       when 'pl_cod100' then
                         (data['pl_cod'].to_i <= 0 && data['pl_cod100'].to_i <= 0) ? ' cond_required' : ''
                       when 'pl_bod' then
                         (data['pl_bod'].to_i <= 0 && data['pl_bod100'].to_i <= 0) ? ' cond_required' : ''
                       when 'pl_bod100' then
                         (data['pl_bod'].to_i <= 0 && data['pl_bod100'].to_i <= 0) ? ' cond_required' : ''
                       when 'pl_city_id' then
                         ((data['ag_city'].nil? or data['ag_city'].to_i == 1) && data['pl_city_id'].blank?) ? ' cond_required' : ''
                       when 'pl_other_comment' then
                         (data['pl_other'].to_i == 1 && data['pl_other_comment'].blank?) ? ' cond_required' : ''
                       when 'ag_remark_change' then
                         ((data['ag_change_nload'].nil? or data['ag_change_nload'].to_i == 1) && data['ag_remark_change'].blank?) ? ' cond_required' : ''
                       when 'agg_c2_pt' then
                         ((data['ag_nload'].blank? or data['agg_c2'].blank? or (data['ag_nload'].to_f > 100000 and data['ag_nload'].to_f * data['agg_c2'].to_f > 200000)) && data['agg_c2_pt'].blank? && data['agg_c2_st'].blank? && data['agg_c2_ft'].blank?) ? ' cond_required' : ''
                       when 'agg_c2_st' then
                         ((data['ag_nload'].blank? or data['agg_c2'].blank? or (data['ag_nload'].to_f > 100000 and data['ag_nload'].to_f * data['agg_c2'].to_f > 200000)) && data['agg_c2_pt'].blank? && data['agg_c2_st'].blank? && data['agg_c2_ft'].blank?) ? ' cond_required' : ''
                       when 'agg_c2_ft' then
                         ((data['ag_nload'].blank? or data['agg_c2'].blank? or (data['ag_nload'].to_f > 100000 and data['ag_nload'].to_f * data['agg_c2'].to_f > 200000)) && data['agg_c2_pt'].blank? && data['agg_c2_st'].blank? && data['agg_c2_ft'].blank?) ? ' cond_required' : ''
                       when 'agg_date_coll' then
                         ((data['agg_not_collected'].nil? or data['agg_not_collected'].to_i > 0) && data['agg_date_coll'].blank?) ? ' cond_required' : ''
                       when 'rb_type_id' then
                         ((data['dp_surface_sp_id'].to_i == 2 or data['dp_surface_sp_id'].to_i == 3 or data['dp_surface_sp_id'].to_i == 4) && data['rb_type'].blank?) ? ' cond_required' : ''
                       when 'dp_gwbody_id' then
                         ((data['dp_surface_sp_id'].to_i == 1 or data['dp_surface_sp_id'].to_i == 5) && data['dp_gwbody_id'].blank?) ? ' cond_required' : ''
                       when 'dp_waterbody_id' then
                         ((data['dp_surface_sp_id'].to_i == 2 or data['dp_surface_sp_id'].to_i == 3 or data['dp_surface_sp_id'].to_i == 4) && data['dp_waterbody_id'].blank?) ? ' cond_required' : ''
                       when 'dp_gwbody_id' then
                         (data['rb_type_id'].to_i == 1 && data['dp_gwbody_id'].blank?) ? ' cond_required' : ''
                       when 'dp_surface_land_id' then
                         (data['dp_surface_id'].to_i == 1 && data['dp_surface_land_id'].blank?) ? ' cond_required' : ''
                       else
                         (data[field].blank? && (1..2).include?(field['field_mode'].to_i)) ? (field['field_mode'].to_i == 2 ? ' key_' : ' ')+'required' : ''
                     end
    else
      status_class = case field['col_name']
                       when 'ag_to_be_reported' then
                         (data['ag_to_be_reported'] == '0' && data['agg_state_active'].to_i == 0) ? ' cond_required' : ''
                       when 'agg_state_active' then
                         (data['ag_to_be_reported'] == '0' && data['agg_state_active'].to_i == 0) ? ' cond_required' : ''
                       when 'pl_to_be_reported' then
                         (data['pl_to_be_reported'] == '0' && data['pl_state_active'].to_i == 0) ? ' cond_required' : ''
                       when 'pl_state_active' then
                         (data['pl_to_be_reported'] == '0' && data['pl_state_active'].to_i == 0) ? ' cond_required' : ''
                       when 'dp_to_be_reported' then
                         (data['dp_to_be_reported'] == '0' && data['dp_state_active'].to_i == 0) ? ' cond_required' : ''
                       when 'dp_state_active' then
                         (data['dp_to_be_reported'] == '0' && data['dp_state_active'].to_i == 0) ? ' cond_required' : ''
                       when 'pl_cd' then
                         (data['pl_state_active'] == '0' && data['pl_cd'].nil?) ? ' cond_required' : ''
                       when 'plant_id' then
                         (data['dp_to_be_reported'] == '0' && data['plant_id'].nil?) ? ' cond_required' : ''
                       when 'ag_nload' then
                         (data['ag_to_be_reported'] == '0' && data['ag_nload'].nil?) ? ' cond_required' : ''
                       else
                         ''
                     end
    end
    if status_class.strip.blank? && !data[field].nil?
      status_class = case field['reference_type']
                       when '8' then
                         data[field].to_i <= 0 ? ' wrong_type' : ''
                       when '81' then
                         data[field].to_i <= 0 && data[field].strip != '0' ? ' wrong_type' : ''
                       when '9' then
                         data[field].to_f <= 0.0 ? ' wrong_type' : ''
                       when '91' then
                         data[field].to_f <= 0.0 && data[field].strip[0, 1] != '0' ? ' wrong_type' : ''
                       else
                         status_class
                     end
    end
    return status_class
  end


  def options_for_select_with_title(container, selected = nil)
    container = container.to_a if Hash === container
    options_for_select = container.inject([]) do |options, element|
      key, text, value = element[0], element[1], element[2]
      selected_attribute = ' selected="selected"' if option_value_selected?(value, selected)
      options << %(<option value="#{html_escape(value.to_s)}" #{selected_attribute} title=\"#{html_escape(text.to_s)}\">#{html_escape(key.to_s)}</option>).html_safe
    end
    options_for_select.join("\n").html_safe
  end

  #called by input_for for reference_type=5
  def agglomerations_select(data)
    return controller.aggs_select_with_add(data.id)
  end

  #called by input_for for reference_type=5
  def discharge_points_select(data)
    return controller.dps_select(data.id) if data.read_only_or_locked?
    controller.dps_select_with_add(data.id)
  end

  #called by input_for for reference_type=5
  def plants_select(data) #wird entweder bei formularerstellung mit data aufgerufen, oder über add-knopf in formular nur mit id
    return "Es können erst Anlagen zugeordnet werden, wenn diese Agglomeration einmal gespeichert wurde" unless data.id
    return controller.plants_select(data.id, true)[0] if data.read_only_or_locked?
    controller.plants_select_with_add(data.id)
  end

  #called by input_for for reference_type=5
  def plant_id_select(data) #wird entweder bei formularerstellung mit data aufgerufen, oder über add-knopf in formular nur mit id
    return "Es können erst Anlagen zugeordnet werden, wenn diese Einleitstelle einmal gespeichert wurde" unless data.id
    # return controller.plants_select(data.id, true)[0] if data.read_only_or_locked?
    return controller.get_plant_id(data.id)[0] if data.read_only_or_locked?
    controller.plants_select_with_add(data.id)
  end

  #called by input_for for reference_type=5
  def successors_select(data) #wird entweder bei formularerstellung mit data aufgerufen, oder über add-knopf in formular nur mit id
    return "Es können erst Vorgänger zugeordnet werden, wenn dieser Datensatz einmal gespeichert wurde" unless data.id
    return controller.successor_select(data.id) if data.read_only_or_locked?
    controller.successor_select_with_add(data.id)
  end

  #auskommentiert weil ich glaube, dass es nicht mehr genutzt wird 21.01.2013
#  def standard_select(table, data, sql_for_options)
#    options = ActiveRecord::Base.connection.query(sql_for_options)
#    if data[table]
#      if data[table].is_a?(Array)
#        selected = data[table]
#      else
#        selected = data[table].split(';')
#      end
#    else
#      selected = []
#    end
#    return call_partial(table, options, selected)
#  end

  def call_partial(table, options, selected)
    return render(:partial => 'layouts/many_select', :locals => {:table => table, :options => options, :selected => selected})
  end

  def filter_link(id, action, select_id, show_all, title)
    link_to('<i class="fa fa-search" aria-hidden="true"></i>'.html_safe,
            '#',
            :title => title + ' filtern',
            :id_ => id,
            :class => 'button_filter_data',
            :onclick => "FilterModal.show('#{url_for({:action => action,
                                                      :id => id,
                                                      :show_all => show_all})}', '#{select_id}', '#{title} filtern')")


  end

  def now
    return Time.now.strftime("%Y-%m-%d %H:%M:%S")
  end

  def now_date_number
    return Time.now.strftime("%Y%m%d").to_i
  end

  def now_time_number
    return Time.now.strftime("%H%M%S").to_i
  end

  def current_date_number
    return Time.now.strftime("%Y%m%d").to_i
  end

  def current_time_number
    return Time.now.strftime("%H%M%S").to_i
  end

  def get_bool(text)
    return nil if text.nil?
    text = text.strip
    # J/j/Ja/JA/ja/Y/y/Yes/YES/yes/1 bzw. N/n/Nein/NEIN/nein/NO/no/No/0
    return 1 if text =~ /^[jy1a].*/ui
    return 0 if text =~ /^[n0i].*/ui
    return nil
  end

  def numerical_date(string_date)
    return 0 if string_date.blank?
    match = /(\d{1,2})\.(\d{1,2})\.(\d{2,4})\.?/.match(string_date)
    if match
      year = match[3]
      if year.length == 2
        if year.to_i < 30
          year = '20' + year
        else
          year = '19' + year
        end
      end
      return sprintf("%04d%02d%02d", year.to_i, match[2].to_i, match[1].to_i)
    end
    begin
      d = Date.parse(string_date, true)
    rescue
      return 0
    end
    return sprintf("%04d%02d%02d", d.year, d.month, d.day)
  end

  def date_to_iso (datum)
    if datum.length == 4
      return datum.to_s + "-01-01"
    else
      if datum.length == 7
        date = datum.split('.')
        isodate = date[1] + "-" + date[0]+ "-01"
      else
        date = datum.split('.')
        isodate = date[2] + "-" + date[1] + "-" + date[0]
        return isodate
      end
    end
  end

  def numerical_date_to_de (num_date)
    year = (num_date.to_i / 10000).to_s
    remainder = num_date.to_i % 10000
    month = (remainder / 100).to_s
    day = (num_date.to_i % 1000000).to_s
    date = year + "." + month + "." + day
    return date
  end

  def is_valid_date(string_date)
    return true if string_date.blank?
    number_date = numerical_date(string_date)
    return false if number_date.to_i == 0
    return true
  end

  def is_valid_float_or_empty(string, only_int = false)
    return true if string.nil? || string.strip.blank?
#    return false if string.index('.')
    # Punkte sind wegen Uneindeutigkeit (Tausendertrennzeichen oder Dezimaltrenner) nicht zugelassen
    return false unless /^[-+]?(?<integral>[.\d]*\d)(?:,(?<decimal>\d*))?$/ =~ string.strip
    # puts "***MITKOMMA"
    return false unless /^\d{1,3}(?:\.?\d{3})*$/ =~ integral #kommt aus voriger regexp
    # puts "***ISTGANZ***#{only_int}"
    return false if only_int && decimal.to_i != 0
    # puts "**GEHTDOCH"
    return true
  end

  def is_valid_int_or_empty(string)
    return is_valid_float_or_empty(string, true)
  end

  def makeOnClick(view, action, controller, parms)

    # if controller is unset automatically std controller will be called
    if controller.nil?
      ufp = { :action => action }
    else
      ufp = { :action => action, :controller => controller }
    end

    parms.keys.each { |k| if k != :confirm; then ufp[k]=parms[k]; end }


    # ret = "new Ajax.Updater('#{view}', '#{url_for(ufp)}', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('#{form_authenticity_token}')});"
    ret = "$.ajax({ url: '#{url_for(ufp)}', data: { authenticity_token: encodeURIComponent('#{form_authenticity_token}') }, success: function(res) {$('#{'#'+view}').html(res);} })";

    if parms[:confirm]
      ret = "if( confirm('#{parms[:confirm].gsub(/'/, "\\'")}') ) {" + ret + "}; return false;"
    else
      ret = ret.sub(/;\s*$/, "") + "; return false;"
    end

    return ret
  end

  def theUser(session)
    return nil unless session && session[:user]
    theId = session[:user]
    return @cachedUser if theId == @cachedId
    @cachedUser = User.find(theId)
    @cachedId = theId
    return @cachedUser
  end


  def getReportTimeFrame(rep_code)
    report = ReportingPeriod.find(rep_code)
    # sql = "select date_from as date_from, date_to as date_to FROM model.reporting_periods
    #        where key_report = '#{rep_code}';"

    # logger.info "Berichtszeitraum : #{[report[:date_from], report[:date_to]]}"
    [report.date_from, report.date_to]
    # result = ActiveRecord::Base.query_sql(sql)

    # return result[0][0], result[0][1]
  end

end
