<commit_before># Copyright (C) 2007, 2008, 2009, 2010 The Collaborative Software Foundation
#
# This file is part of TriSano.
#
# TriSano is free software: you can redistribute it and/or modify it under the
# terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# TriSano is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt.

# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  include PostgresFu

  # Returns a localized date or, if date is nil, the default value.
  #
  # The following returns the date, formatted to the default format,
  # or a non-breaking space if the date is nil:
  #
  #   localize_or_default(some_date)
  #
  # To change the default, pass in a second argument:
  #
  #   localize_or_default(some_date, "No date specified")
  #
  # The last argument is an optional hash that will be passed on to
  # i18n.localize as options. So, to change the format of the date:
  #
  #   localize_of_default(some_date, :format => :short)
  #
  def localize_or_default(date_or_string, *args)
    raise ArgumentError, "wrong number of arguments: (#{args.size + 1} for 3)" if args.size > 2

    options = args.extract_options!
    default = args.first || "&nbsp;"
    begin
      date = date_or_string.is_a?(String) ? Date.parse(date_or_string) : date_or_string
    rescue
      date = nil
    end
    date ? I18n.l(date, options) : default
  end
  alias :ld :localize_or_default

  def localized_calendar_date_select_variables
    <<-JS
      <script type="text/javascript">
        Date.weekdays = $w("#{I18n.translate(:'date.abbr_day_names').join(' ')}");
        Date.months = $w("#{(I18n.translate(:'date.month_names')[1..-1].join(' '))}");

        _translations = {
          "OK" : "#{I18n.t('calendar_date_select.ok')}",
          "Now" : "#{I18n.t('calendar_date_select.now')}",
          "Today" : "#{I18n.t('calendar_date_select.today')}",
          "Clear" : "#{I18n.t('calendar_date_select.clear')}"
        }
      </script>
    JS
  end

  def l(lookup_field)
    lookup_field.nil? ? nil : lookup_field.code_description
  end

  def fml(pre, value_field, post)
    value_field.blank? ? nil : pre+value_field+post
  end

  def phone_number(number)
    if number =~ /\d{7}/
      number = number[0,3] + "-" + number[3,4]
    elsif number =~ /\d{3}-\d{4}/
      number
    elsif number == ""
      ""
    else
      "! "+number
    end
  end

  def calculate_age(date)
    (Date.today - date).to_i / 365
  end

  def editable_content_tag(elemtype, obj, prop, editable, options = {}, editOptions = {}, ajaxOptions = {})
    objname = obj.class.to_s.downcase
    options[:url] = "/#{objname.pluralize}/#{obj.id}" unless options.has_key? :url
    options[:url] += '.json'
    options[:id] = dom_id(obj)+"_#{prop}" unless options.has_key? :id
    ajaxOptions[:method] = 'put'
    edops = jsonify editOptions
    ajops = jsonify ajaxOptions

    tg = content_tag  elemtype,
      obj.send(prop),
      options = options

    if editable then
      tg += "
           <script type='text/javascript'>\n
               new Ajax.InPlaceEditor('#{options[:id]}', '#{options[:url]}', {
                        ajaxOptions: { #{ajops} },
                        callback: function(form, value)
                          { return 'authenticity_token=#{form_authenticity_token}&#{objname}[#{prop}]=' + escape(value) },
                        onComplete: function(transport, element)
                          { element.innerHTML=transport.responseText.evalJSON().#{prop};}"
      tg += ",#{edops}" unless edops.empty?
      tg += "});\n"
      tg += "         </script>\n"

    end
  end

  #Converts a hash into a JSON options list
  # (without the encompasing {}'s or any type of recursion
  #Is there a rails API function that does this?
  def jsonify hsh
    str = ''
    first = true
    hsh.each do |k,v|
      str += ', ' unless first
      str += "#{k}: "
      str += "'" unless (v.class == Fixnum or v.class == Float)
      str += v.to_s
      str += "'" unless (v.class == Fixnum or v.class == Float)
      first = false
    end
    str
  end

  # Determines which element to replace on the form builder interface, and which
  # partial to replace it with, based on the state of the element being updated.
  def replacement_elements(element)
    if (element.form_id.blank?)
      replace_element = 'library-admin'
      replace_partial =  'forms/library_admin'
    elsif (element.is_a?(InvestigatorViewElementContainer) || element.ancestors[1].is_a?(InvestigatorViewElementContainer))
      replace_element = 'root-element-list'
      replace_partial =  'forms/elements'
    elsif (element.is_a?(CoreViewElementContainer) || element.ancestors[1].is_a?(CoreViewElementContainer))
      replace_element = 'core-element-list'
      replace_partial =  'forms/core_elements'
    else
      replace_element = 'core-field-element-list'
      replace_partial =  'forms/core_field_elements'
    end
    return replace_element, replace_partial
  end

  def current_user_name
    if (User.current_user.last_name.blank? || User.current_user.first_name.blank?)
      User.current_user.user_name
    else
      "#{User.current_user.first_name} #{User.current_user.last_name}"
    end
  end

  # http://www.pathf.com/blogs/2008/07/pretty-blocks-in-rails-views/
  def tabbed_content(tabs, focus_tab, &block)
    raise ArgumentError, "Missing block" unless block_given?

    tabs_string = tabs.map{|tab| "'#{tab.first}'"}.join(',')

    concat(
      javascript_tag("var myTabs = new YAHOO.widget.TabView('cmr_tabs'); myTabs.set('activeIndex', #{focus_tab});") +

        content_tag(:span, "[#{t("disable_tabs")}]", :id => 'disable_tabs', :onClick => "myTabs.removeClass('yui-navset'); myTabs.removeClass('yui-content'); [#{tabs_string}].each(Element.show); Element.hide('disable_tabs'); Element.hide('tabs'); Element.show('enable_tabs');return false;") +
        content_tag(:span, "[#{t("enable_tabs")}]", :id => 'enable_tabs', :onClick => "myTabs.addClass('yui-navset'); myTabs.addClass('yui-content'); [#{tabs_string},'enable_tabs'].each(Element.hide); Element.show('disable_tabs'); Element.show('tabs'); myTabs.set('activeIndex',0); return false;", :style => 'display: none;') +

        content_tag(:div, :id => "cmr_tabs", :class => "yui-navset") do
        content_tag(:ul, :id => "tabs", :class => "yui-nav") do
          line_items = ""
          tabs.each do |tab|
            line_items += content_tag(:li) do
              link_to(content_tag(:em, tab.last), "##{tab.first}")
            end
          end
          line_items
        end +
          content_tag(:div, :class => "yui-content") do
          capture(&block)
        end<commit_msg>[Finished #6319575] Fixing tab index when you use the sibling nav to move from an event with more tabs to an event with fewer tabs. UAT coverage to follow later when we tackle the Selenium coverage for this.<commit_after># Copyright (C) 2007, 2008, 2009, 2010 The Collaborative Software Foundation
#
# This file is part of TriSano.
#
# TriSano is free software: you can redistribute it and/or modify it under the
# terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# TriSano is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt.

# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  include PostgresFu

  # Returns a localized date or, if date is nil, the default value.
  #
  # The following returns the date, formatted to the default format,
  # or a non-breaking space if the date is nil:
  #
  #   localize_or_default(some_date)
  #
  # To change the default, pass in a second argument:
  #
  #   localize_or_default(some_date, "No date specified")
  #
  # The last argument is an optional hash that will be passed on to
  # i18n.localize as options. So, to change the format of the date:
  #
  #   localize_of_default(some_date, :format => :short)
  #
  def localize_or_default(date_or_string, *args)
    raise ArgumentError, "wrong number of arguments: (#{args.size + 1} for 3)" if args.size > 2

    options = args.extract_options!
    default = args.first || "&nbsp;"
    begin
      date = date_or_string.is_a?(String) ? Date.parse(date_or_string) : date_or_string
    rescue
      date = nil
    end
    date ? I18n.l(date, options) : default
  end
  alias :ld :localize_or_default

  def localized_calendar_date_select_variables
    <<-JS
      <script type="text/javascript">
        Date.weekdays = $w("#{I18n.translate(:'date.abbr_day_names').join(' ')}");
        Date.months = $w("#{(I18n.translate(:'date.month_names')[1..-1].join(' '))}");

        _translations = {
          "OK" : "#{I18n.t('calendar_date_select.ok')}",
          "Now" : "#{I18n.t('calendar_date_select.now')}",
          "Today" : "#{I18n.t('calendar_date_select.today')}",
          "Clear" : "#{I18n.t('calendar_date_select.clear')}"
        }
      </script>
    JS
  end

  def l(lookup_field)
    lookup_field.nil? ? nil : lookup_field.code_description
  end

  def fml(pre, value_field, post)
    value_field.blank? ? nil : pre+value_field+post
  end

  def phone_number(number)
    if number =~ /\d{7}/
      number = number[0,3] + "-" + number[3,4]
    elsif number =~ /\d{3}-\d{4}/
      number
    elsif number == ""
      ""
    else
      "! "+number
    end
  end

  def calculate_age(date)
    (Date.today - date).to_i / 365
  end

  def editable_content_tag(elemtype, obj, prop, editable, options = {}, editOptions = {}, ajaxOptions = {})
    objname = obj.class.to_s.downcase
    options[:url] = "/#{objname.pluralize}/#{obj.id}" unless options.has_key? :url
    options[:url] += '.json'
    options[:id] = dom_id(obj)+"_#{prop}" unless options.has_key? :id
    ajaxOptions[:method] = 'put'
    edops = jsonify editOptions
    ajops = jsonify ajaxOptions

    tg = content_tag  elemtype,
      obj.send(prop),
      options = options

    if editable then
      tg += "
           <script type='text/javascript'>\n
               new Ajax.InPlaceEditor('#{options[:id]}', '#{options[:url]}', {
                        ajaxOptions: { #{ajops} },
                        callback: function(form, value)
                          { return 'authenticity_token=#{form_authenticity_token}&#{objname}[#{prop}]=' + escape(value) },
                        onComplete: function(transport, element)
                          { element.innerHTML=transport.responseText.evalJSON().#{prop};}"
      tg += ",#{edops}" unless edops.empty?
      tg += "});\n"
      tg += "         </script>\n"

    end
  end

  #Converts a hash into a JSON options list
  # (without the encompasing {}'s or any type of recursion
  #Is there a rails API function that does this?
  def jsonify hsh
    str = ''
    first = true
    hsh.each do |k,v|
      str += ', ' unless first
      str += "#{k}: "
      str += "'" unless (v.class == Fixnum or v.class == Float)
      str += v.to_s
      str += "'" unless (v.class == Fixnum or v.class == Float)
      first = false
    end
    str
  end

  # Determines which element to replace on the form builder interface, and which
  # partial to replace it with, based on the state of the element being updated.
  def replacement_elements(element)
    if (element.form_id.blank?)
      replace_element = 'library-admin'
      replace_partial =  'forms/library_admin'
    elsif (element.is_a?(InvestigatorViewElementContainer) || element.ancestors[1].is_a?(InvestigatorViewElementContainer))
      replace_element = 'root-element-list'
      replace_partial =  'forms/elements'
    elsif (element.is_a?(CoreViewElementContainer) || element.ancestors[1].is_a?(CoreViewElementContainer))
      replace_element = 'core-element-list'
      replace_partial =  'forms/core_elements'
    else
      replace_element = 'core-field-element-list'
      replace_partial =  'forms/core_field_elements'
    end
    return replace_element, replace_partial
  end

  def current_user_name
    if (User.current_user.last_name.blank? || User.current_user.first_name.blank?)
      User.current_user.user_name
    else
      "#{User.current_user.first_name} #{User.current_user.last_name}"
    end
  end

  # http://www.pathf.com/blogs/2008/07/pretty-blocks-in-rails-views/
  def tabbed_content(tabs, focus_tab, &block)
    raise ArgumentError, "Missing block" unless block_given?

    focus_tab = 0 if tabs.size <= focus_tab.to_i

    tabs_string = tabs.map{|tab| "'#{tab.first}'"}.join(',')

    concat(
      javascript_tag("var myTabs = new YAHOO.widget.TabView('cmr_tabs'); myTabs.set('activeIndex', #{focus_tab});") +

        content_tag(:span, "[#{t("disable_tabs")}]", :id => 'disable_tabs', :onClick => "myTabs.removeClass('yui-navset'); myTabs.removeClass('yui-content'); [#{tabs_string}].each(Element.show); Element.hide('disable_tabs'); Element.hide('tabs'); Element.show('enable_tabs');return false;") +
        content_tag(:span, "[#{t("enable_tabs")}]", :id => 'enable_tabs', :onClick => "myTabs.addClass('yui-navset'); myTabs.addClass('yui-content'); [#{tabs_string},'enable_tabs'].each(Element.hide); Element.show('disable_tabs'); Element.show('tabs'); myTabs.set('activeIndex',0); return false;", :style => 'display: none;') +

        content_tag(:div, :id => "cmr_tabs", :class => "yui-navset") do
        content_tag(:ul, :id => "tabs", :class => "yui-nav") do
          line_items = ""
          tabs.each do |tab|
            line_items += content_tag(:li) do
              link_to(content_tag(:em, tab.last), "##{tab.first}")
            end
          end
          line_items
        end +
          content_tag(:div, :class => "yui-content") do
          capture(&block)
        end
{'fraction_non_alphanumeric': 0.13486842105263158, 'fraction_numerical': 0.008634868421052632, 'mean_word_length': 3.078535494689771, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4319890', 'n_tokens_mistral': 4772, 'n_tokens_neox': 4605, 'n_words': 1203}