module OrbitFormHelper
  def self.included(base)
    #ActionView::Helpers::FormBuilder.send(:include, Orbit::FormBuilder)
    ActionView::Helpers::FormBuilder.send(:include,ActionView::Helpers::UrlHelper)
    ActionView::Helpers::FormBuilder.send(:include,ActionView::Helpers::TagHelper)
    ActionView::Helpers::FormBuilder.send(:include,ActionView::Context)
    ActionView::Helpers::FormBuilder.send(:include,ActionView::Helpers::FormTagHelper)
  end

  def datetime_picker(object_name, options = {})
    def objectify_options(options)
      @default_options = {} if @default_options.class != Hash
      @default_options.merge(options.merge(object: @object))
    end
    options[:icon_time] ||= 'icons-clock'
    options[:icon_date] ||= 'icons-calendar'
    options[:icon_clear] ||= 'icons-cross-3'
    options[:input_class] ||= 'input-large'
    options[:new_record] = true if options[:new_record].nil?
    options = objectify_options(options)
    options[:value] ||= options[:object].send(object_name) if options[:object] && options[:object][object_name]
    options[:placeholder] ||= (options[:format].to_s.empty? ? nil : options[:format])
    case options[:picker_type]
    when 'date'
      content_tag :div, :id => options[:id], :class => options[:class] do
        date_picker(object_name, options)
      end
    when 'time'
      content_tag :div, :id => options[:id], :class => options[:class] do
        time_picker(object_name, options)
      end
    when 'separated'
      options[:label] ||= I18n.t('datetime_picker.separated.label')
      content_tag :div, :id => options[:id], :class => "separated_picker #{options[:class]}" do
        concat label_tag options[:label] unless options[:no_label]
        concat hidden_field(object_name, :value => options[:value])
        concat separated_picker(object_name, options)
      end
    when 'simple'
       content_tag :div, :id => options[:id], :class => options[:class] do
        simple_picker(object_name, options)
      end
    else
      content_tag :div, :id => options[:id], :class => options[:class] do
        default_picker(object_name, options)
      end
    end
  end

  def default_picker(object_name, options)
    custom = {}
    options[:format] = options[:format] || 'yyyy/MM/dd hh:mm'
    options[:value] = format_value(options[:value], options[:format]) if options[:value] && !options[:new_record]
    options[:value] = "" if options[:new_record]
    custom[:picker_class] = 'default_picker'
    custom[:label] = options[:label] || I18n.t('datetime_picker.default.label')
    custom[:placeholder] = options[:placeholder] || I18n.t('datetime_picker.default.placeholder')
    picker(object_name, options.merge(custom))
  end

  def picker(object_name, options)
    content_tag :div, :class => "#{options[:picker_class]} input-append" do
      concat label_tag options[:label] unless options[:no_label]
      if object_name.nil?
        if !options['id'].nil?
          concat text_field_tag nil ,options[:value], :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :data => options[:data], :id => options['id']
        else
          concat text_field_tag nil,options[:value], :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :data => options[:data]
        end
      else
        if !@object.nil?
          if !options['id'].nil?
            concat text_field object_name , :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :value => options[:value], :data => options[:data], :id => options['id']
          else
            concat text_field object_name, :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :value => options[:value], :data => options[:data]
          end
        else
          if !options['id'].nil?
            concat text_field_tag object_name ,options[:value], :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :value => options[:value], :data => options[:data], :id => options['id']
          else
            concat text_field_tag object_name ,options[:value], :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :value => options[:value], :data => options[:data]
          end
        end
      end
      concat (content_tag :span, :class => 'add-on clearDate' do
                content_tag :i, nil, :class => options[:icon_clear]
              end)
      concat (content_tag :span, :class => 'add-on iconbtn' do
                content_tag :i, nil, 'data-time-icon' => options[:icon_time], 'data-date-icon' => options[:icon_date]
              end)
    end
  end

  def format_value(value, format = 'yyyy-MM-dd hh:mm')
    value.strftime(format.gsub('yyyy', '%Y').gsub('MM', '%m').gsub('dd', '%d').gsub('hh', 'h').gsub('HH','H').gsub('H', '%H').gsub('h', '%H').gsub('mm', '%M')) rescue value.to_s
  end


  def simple_picker(object_name, options)
    onkeypress_for_input = 'return (event.charCode >= 48 && event.charCode <= 57) || event.keyCode == 8 || event.keyCode == 46 || (event.keyCode >= 37 && event.keyCode <= 40) || event.keyCode == 9'
    onkeyup_for_input = 'this.value=(this.value.length <= 2 ? (parseInt(this.value) > 0 && parseInt(this.value) < 32 ? this.value : this.value.substring(0,this.value.length-1)) : this.value.substring(0,this.value.length-1))'
    onkeyup_for_input2 = 'this.value=(this.value.length == 4 ? (parseInt(this.value) > 1900 && parseInt(this.value) < 3000 ? this.value : this.value.substring(0,this.value.length-1)) : (this.value.length > 4 ? this.value.substring(0,this.value.length-1) : this.value))'
    html = "<div class='simple-date-picker'>
              <input type='text' class='span1' #{(options[:value] ? "value='#{options[:value].day}'" : "")} placeholder='Date' onkeypress='#{onkeypress_for_input}' onkeyup='#{onkeyup_for_input}'>
              <select class='span2'>"
    ["January","February","March","April","May","June","July","August","September","October","November","December"].each_with_index do |mon,index|
      html = html + "<option value='#{(index < 9 ? "0" : "")}#{(index + 1).to_s}' #{(options[:value] && options[:value].month == (index + 1) ? "selected='selected'" : "")}>#{mon}</option>"
    end
    html = html + "</select><input type='text' class='span3' #{(options[:value] ? "value='#{options[:value].year}'" : "")} placeholder='Year' onkeypress='#{onkeypress_for_input}'  onkeyup='#{onkeyup_for_input2}'>"
    html = html + hidden_field(object_name, :value => options[:value] || "1901-01-01")
    html = html + "</div>"
    html.html_safe
  end

  def date_picker(object_name, options)
    custom = {}
    custom[:format] = options[:format] || 'yyyy/MM'
    custom[:value] = format_value(options[:value], custom[:format]) if options[:value]
    custom[:picker_class] = 'date_picker'
    custom[:label] = options[:label] || I18n.t('datetime_picker.date.label')
    options[:placeholder] ||= I18n.t('datetime_picker.date.placeholder')
    picker(object_name, options.merge(custom))
  end

  def time_picker(object_name, options)
    custom = {}
    custom[:format] = options[:format] || 'HH:mm'
    custom[:value] = format_value(options[:value], custom[:format]) if options[:value]
    custom[:picker_class] = 'time_picker'
    custom[:label] = options[:label] || I18n.t('datetime_picker.time.label')
    custom[:placeholder] = options[:placeholder] || I18n.t('datetime_picker.time.placeholder')
    picker(object_name, options.merge(custom))
  end

  def separated_picker(object_name, options)
    custom = {}
    custom[:no_label] = true
    custom[:separated] = true
    date_picker(nil, options.merge(custom).merge({:format=>'yy/mm/dd','id'=>"_1_#{object_name}"})) + time_picker(nil, options.merge(custom).merge({:format=>'hh:mm','id'=>"_2_#{object_name}"}))
  end


  def single_picker(object_name, options)
    content_tag :div, :id => options[:id], :class => options[:class] do
      picker(object_name, options)
    end
  end

  def double_picker(object_name, options)
    
  end


end

module Orbit::FormBuilder
  # ActionPack's metaprogramming would have done this for us, if FormHelper#labeled_input 
  # had been defined  at load.   Instead we define it ourselves here.
  #def datetime_picker(method, options = {})
    # @template.datetime_picker(@object_name, method, objectify_options(options))
  #end
end