# Methods added to this helper will be available to all templates in the application.
#--######################################################################
# Copyright (c) 2006 Logica
# 
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# 
# Onno van der Straaten:: initial implementation
#++######################################################################
# {Copyright (c) 2006 Logica}[link:files/COPYRIGHT.html]

module ApplicationHelper
  
  # Helper to simplify In-Place Editing 
  def editable_content(options)
    options[:content] = { :element => 'span' }.merge(options[:content])
    options[:url] = {}.merge(options[:url])
    options[:ajax] = { :okText => 'Save', :cancelText => 'Cancel'}.merge(options[:ajax] || {})
    script = Array.new
    script << 'new Ajax.InPlaceEditor('
    script << "  '#{options[:content][:options][:id]}',"
    script << "  '#{url_for(options[:url])}',"
    script << "  {"
    script << options[:ajax].map{ |key, value| "#{key.to_s}: #{value}" }.join(", ")
    script << "  }"
    script << ")"
    content_tag(
                options[:content][:element],
                options[:content][:text],
                options[:content][:options]
    ) + javascript_tag( script.join)
  end
  
  # TODO a better name for this method
  def menulink_to(*args)
    logger.debug("Creating menulink #{args.inspect}, #{params[:action]}")
    current = @current || params[:action].capitalize 
    s=' class="current"' if args[0].downcase == current.downcase
    if current == 'Edit' 
      txt = "Are you sure? By navigating away from the editor any unsaved changes will be lost."
      if args.size == 3
        args.last[:confirm] = txt
      else
        args << {:confirm => txt}        
      end
    end
    args[0] = "<span>#{args[0]}</span>"
    "<li#{s}>" + link_to(*args) + '</li>'
  end
  
  class TabularFormBuilder < ActionView::Helpers::FormBuilder
   (field_helpers - %w(radio_button hidden_field)).each do |selector|
      src = <<-END_SRC
        def #{selector}(field, options = {})
          @template.content_tag("tr", 
            @template.content_tag("th", field.to_s.humanize, :width => 200) + 
              @template.content_tag("td", super))
        end
      END_SRC
      class_eval src, __FILE__, __LINE__
    end
  end  
  
  def tabular_form_for(name, object = nil, options = nil, &proc)
    if @table_heading
      concat("<div>#{@table_heading}</div>", proc.binding)
    else
      concat("<div>#{name.to_s.humanize}</div>", proc.binding)
    end
    concat("<div class=\"sectionContent\"><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"sectionTable\"><tr valign=\"top\"><td class=\"sectionTableCell\"><table>",
    proc.binding)
    form_for(name, 
             object, 
     (options||{}).merge(:builder => TabularFormBuilder), 
    &proc)
    concat("</table></td></tr></table></div>", proc.binding)               
  end   
  
  # Helper #tinymce in your view to render textarea's as TinyMCE textarea's
  def tinymce(theme = 'simple')
    @tinymce = theme
  end

   # Link To for a Page 
  def link_to_page(page)
      link_to(page.presentation_name + ' ' + image_tag("link.gif",:border => 0,:title => "Activate page \"#{page.presentation_name}\" in site \"#{page.site.title}\""), page.url)
  end
    
  # Helper #link_to_notification_toggle
  def link_to_notification_toggle(page, notification_type, user = session['user'])
    returning html = [] do
      notification = Notification.find(:first, :conditions => ["user_id=? and page_id=? and notification_type=?", user.id, page.id, notification_type])
      if session['user'] && (mine?(user) || cadmin?)
        div_id = "notification_" + page.id.to_s + "_" + notification_type
        html << "<span id=\"" + div_id + "\">"
        txt = "<input type=checkbox>notify me of new comments and changes"
        txt = "<input type=checkbox checked>notify me of new comments and changes" if notification
        html << link_to_remote(txt, :update => div_id, :url => {:controller => "users", :action => "notification", :page_id => page.id, :site_id => page.site.id,:user_id => user.id, :notification_type=> notification_type}, :method => 'post')
        html << "</span>"
      else
        html << "<input type=checkbox #{'checked' if notification} DISABLED>notify me of new comments and changes"
      end
    end.join("\n")
  end
          
  def link_to_change_report_notification_toggle(type = 'D', user = session['user'])
    returning html = [] do
      if !user.nil? && (mine?(user) || cadmin?)
          checked = ""
          checked = "checked" if (type == 'D' && user.notify_daily == 1) || (type == 'M' && user.notify_monthly == 1) || (type == 'W' && user.notify_weekly == 1) || (type == 'I' && user.notify_immediate == 1)
          txt = "<input type=checkbox #{checked} DISABLED> Daily" if type == 'D'
          txt = "<input type=checkbox #{checked} DISABLED> Monthly" if type == 'M'
          txt = "<input type=checkbox #{checked} DISABLED> Weekly" if type == 'W'
          txt = "<input type=checkbox #{checked} DISABLED> Immediate" if type == 'I'
          div_id = "change_report_" + user.id.to_s + "_"  + type
          #checked = "checked" if type == 'M' && user.notify_monthly == "1"
          #checked = "checked" if type == 'D' && user.notify_weekly == "1"
        if mine?(user) || cadmin?
          html << "<span id=\"" + div_id + "\">"
          html << link_to_remote(txt.gsub('DISABLED', ''), :update => div_id, :url => {:controller => "users", :action => "toggle_change_report_notification", :type => type, :user_id => user.id}, :method => 'post')
          html << "</span>"
        else
          html << txt
        end
      else
        html << "ERROR: No user specified"
      end
    end.join("\n")
  end 
              
  def link_to_done_toggle(record)
    class_name = 'DaText'
    class_name = record.class.name if ['Version','Upload', 'UserVersion', 'BaselineProcessVersion'].include?(record.class.name)
    returning html = [] do
      html << "<span id=\"" + div_id(record, "done_toggle") + "\">"
      if record.done == 'Y'
        title = 'Click to mark this record \'todo\''
        html4checkbox = "<input type=checkbox checked>"
      else
        title = 'Check to mark this record \'done\''
        html4checkbox = "<input type=checkbox>"
      end        
      if  !session["user"] || !admin?
        html << html4checkbox.gsub('type=checkbox', 'type=checkbox disabled=disabled')
      else
        html << link_to_remote(html4checkbox, :update => div_id(record, 'done_toggle'), :url => { :controller => 'review', :action => "toggle_done", :id => record.id, :class_name => class_name}, :title => title)
      end
      html << "</span>"
    end.join("\n")
  end
                
    # Helper #link_to_reviewer to set the reviewer. See ReviewController.
    def link_to_reviewer(record)
      returning url = [] do
        url << "<span id=\"" + div_id(record, "reviewer") + "\">"
        if  !session["user"]
          if  record.reviewer_id != nil
            url << link_to_user(record.reviewer)
          end
        else 
          if  record.reviewer_id == nil
            if  admin?
              url << link_to_remote("_______", :update => div_id(record, "reviewer"), :url => { :controller => 'review', :action => 'assign', :id => record.id, :class_name => record.class} )
            else
              url << "" 
            end
          else
              url << link_to_remote(record.reviewer.name, :update => div_id(record, "reviewer"), :url => { :controller => 'review', :action => 'assign', :id => record.id, :class_name => record.class} )
          end
          url << "</span> "
        end
      end.join("\n")
    end
                    
  # link_to helper method for a Version. Renders a link with a given prefix (often "version") with possibly a lot of clickable images displaying status
  def link_to_version(version,urlprefix)
    returning link = [] do
      # TODO below incorrect
      urlprefix = 'CHECKOUT' if version.version.nil?
      link << link_to(urlprefix + " " + version.version.to_s,:controller => 'versions',:action => 'show',:id => version.id)
      if  !version.version_id
      else
        source_version = version.source_version
        if  version.wiki_id != source_version.wiki_id 
          from_site = source_version.wiki
          to_site = version.wiki
          link << link_to(image_tag('site.gif', :border => 0,  :title => 'Based on version ' + source_version.version.to_s + " from site " + from_site.title) ,:controller => 'versions',:action => 'show',:id => source_version.id)
        else
          if version.page_id != source_version.page_id
            base_page = source_version.page
            link << link_to(image_tag('new.png', :border => 0, :title => 'New page based on  ' + source_version.page.presentation_name + " version " + source_version.version.to_s) ,:controller => 'versions',:action => 'show',:id => source_version.id)  
          else
            if  version.version != source_version.version + 1
              link <<  " (based on "
              link << link_to(" version " + source_version.version.to_s,:controller => 'versions',:action => 'show',:id => source_version.id)
              link <<  ")"
            end
          end
        end
      end
      if version.current
        link << image_tag('harvest.gif', :title => 'This version is the current version')
      end
      checkout = version.checkout
      if  checkout
        user = checkout.user
        link << link_to(image_tag('checkout.gif', :border => 0, :title =>'Version is checked-out by ' + user.name ),:controller => 'versions',:action => 'show',:id => version.id)
        link << " " 
        if user == session['user'] || cadmin?
          link << link_to(image_tag('edit.gif', :border => 0, :title =>'Version is checked-out by you. Click to continue editing.' ),:controller => 'pages',:action => 'edit',:checkout_id => checkout.id)
        end
      end
      link << link_to(image_tag('compare.gif', :border => 0, :title =>'Compare with previous version' ),:controller => 'versions', :action => 'diff',:id => version) 
      link << link_to(image_tag('txt.gif', :border => 0,  :title =>'View as plain text' ), {:controller => 'versions',:action => 'text',:id => version})
    end.join("\n")
  end
                      
  # Helper for a Version 
  def link_to_version2(version)
    link_to_page(version.page) + ' ' + link_to_version(version,'version')
  end
                        
  # Helper for a Site
  def link_to_site(site)
    img = "link.gif"
    img = "link_gs.gif" if !site.wiki?
    ttl = site.title
    ttl = site.title + ' (OBSOLETE)' unless site.obsolete_on.nil?
    link = link_to(ttl,:controller => 'sites',:action => 'description',:id => site.id) #if !admin?
    link += ' ' + link_to(image_tag(img,:border => 0,:title => "Activate site \"#{site.title}\""), site.url, :title => "Activate site \"#{site.title}\"", :popup => true)
    if  site.type == 'BaselineProcess'
      link += ' ' + link_to(image_tag("csv.gif", :border => 0, :title => "Download content information as CSV"), {:controller => "sites", :action => "csv", :id => site.id}, :method => :post )
    end 
    return link
  end
                          
  # link_to helper method for a User
  def link_to_user(user)
    link_to(user.name,:controller => 'users',:action => 'show',:id => user.id) + image_tag("user" + user.admin + '.png', :border => 0, :title => "") 
  end
                            
  # link_to helper method for a Comment
  def link_to_comment(comment)
    link_to(truncate(strip_tags(comment.text)), :controller => 'pages', :action => 'discussion', :site_folder => comment.site.folder, :id => comment.page.id)
  end
                              
  # returns unique div id from a record in a page
  def div_id(record, call_id)
    return  record.class.to_s + record.id.to_s + "_" + call_id
  end
                              
  # helper method for a displaying navigation links to first, next, previous, last pages to use when displaying records in pages.
  # See preserving parameters [http://64.233.183.104/search?q=cache:VZkWDCGLNBIJ:wiki.rubyonrails.com/rails/show/HowtoPagination+pagination+how+to+ruby+on+rails&hl=nl&gl=nl&ct=clnk&cd=4]
  def links_to_pages(pages)
    if pages.length > 1
      returning link = [] do
        link << '<p>'
      link << link_to(image_tag('first_page.png', :border => 0, :align=>"middle", :title => "First Page"), {:params => params.merge(:page => 1)} ) if pages.current.previous
      link << image_tag('first_page_disabled.png', :border => 0, :align=>"middle", :title => "First Page")  if !pages.current.previous
      link << link_to(image_tag('previous_page.png', :border => 0, :align=>"middle", :title => "Previous Page"), {:params => params.merge(:page => pages.current.previous)}) if pages.current.previous
      link << image_tag('previous_page_disabled.png', :border => 0, :align=>"middle", :title => "Previous Page")  if !pages.current.previous  
      link << "<small>[" + pages.current.number.to_s + "/" + pages.length.to_s + "]</small>"
      link << link_to(image_tag('next_page.png', :border => 0, :align=>"middle", :title => "Next Page"),  {:params => params.merge(:page => pages.current.next)}) if pages.current.next
      link << image_tag('next_page_disabled.png', :border => 0, :align=>"middle", :title => "Next Page")  if !pages.current.next
      link << link_to(image_tag('last_page.png', :border => 0, :align=>"middle", :title => "Last Page"), {:params => params.merge( :page => pages.last)}) if pages.current.next
      link << image_tag('last_page_disabled.png', :border => 0, :align=>"middle", :title => "Last Page")  if !pages.current.next
      link << '</p>'
      end.join("\n")
    end
  end
                                  
end
                                
