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

  #def self.included(base)
  #    base.class_eval {
  #      session :disabled => false
  #   }
  # end
  def n(number)
    f_number = number.to_f.round
    number_with_delimiter(f_number, :delimiter =>" ") #unless number.class == String
  end
 def n_c(number)
   if number.blank?
     ''
   else
    f_number = number.to_f
    number_with_delimiter(number_with_precision(f_number, :precision => 2), :delimiter =>" ", :separator => ".") #unless number.class == String
   end
  end


 def n_s(number)
   if number.to_f == 0
     ''
   else
     "%.10g" % ("%.2f" % number)
   end
 end


 def d(date)
   Russian::strftime(date.to_date)
 end

 def pay_types_for_category(cat)
   tps = []
   if cat
     if cat.mat_inst
       tps << ["Установка без оплаты",  1]
     end
     if cat.mat_sale
       tps << ["Продажа", 3]
       tps << ["Продажа, списание со счёта", 7]
       tps << ["Продажа на К+", 8]
     end
   if cat.mat_rent
       tps << ["Аренда", 2]
   end
   if cat.mat_rent_rate
       tps << ["Аренда  в счет тарифа", 5]
   end   
   if cat.mat_test
       tps << ["Установка на пробный период", 6]
   end   
   end
   return tps
 end

 def selected_pay_type(cat, material)   
   if cat.department == 'private' && (["Wi-Fi роутеры", "IPTV Приставки", "Powerline", "Wi-Fi адаптеры", "Wi-Fi точки доступа", "Соединительные"].include? material[:group])
     2
   else
     1
   end
 end

 def material_name(material)
     material[:type].to_s + ": " + material[:name] 
 end

 def preowned(material)
   if material[:preowned] == true
     'Б/У'
   else
     ''
   end
 end
 
 def materials_for_index(report)
   ms = []
   mats = report.done_materials
   for m in mats.select{|i| i.inst_type != 6} do
     str = m.pay_type_name + ": "+ m.material_name + " - " + m.count + " шт." 
     str += " ("+ (m.price.to_s || 0) + " руб.)" if m.price.to_f > 0
     str += content_tag(:div, " Продал сотрудник", :class => 'blue') if m.bonus_sale.to_i > 0 
     str += content_tag(:div, "Должно быть " + m.price_from_store.to_s, :class => "red")  if (m.price.to_f != m.price_from_store.to_f && m.pay_type == 3 && m.price_from_store.to_i > 0)
     ms << str
   end
   mats.select{|i| i.inst_type == 6}.group_by{|i| i.store_id}.each do |id, mats_ch|
     ms << "Замена: " + mats_ch.select{|i| i.pay_type != 4}.first.material_name + " на " +   mats_ch.select{|i| i.pay_type == 4}.first.material_name + " - " + mats_ch.select{|i| i.pay_type == 4}.first.count + " шт."
   end
   return ms.join(" <br> ")
 end

 def works_for_index(report)
   ws = []
   dws = report.done_works
   ws << content_tag(:div, "Бесплатные работы: " + report.discount_works.to_s + " р. Коммент: " + report.com_get_money.to_s, :class => "red") if report.discount_works.to_i > 0   

   for done_work in dws do
     count = done_work.count
     rate = done_work.rate
     ws << done_work.work_name + " ("+ count + " X " + rate + " = " + (count.to_i*rate.to_i).to_s + ")"
   end
   return ws.join(" <br> ")
end


 def y_n(b)
   if b == 1 || b == true
     return 'Да'
   end
 end
 
 def true_false_name(b)
   if b == 1 || b == true
     return 'Да'
   else
     return 'Нет'
   end 
 end

  def request_link(request_id)
    if request_id.to_i > 0
      link_to (request_id.to_s), "http://request.rinet.ru/browse.php?page=showstroirequest&index="+request_id.to_s, {'target'=>'_blank'}
    else
      '<p class="red">Не из реквеста</p>'
    end
  end
  
  def attr_for_edit(attr="Добавить")
    if attr.to_s.blank?
      return "<p class='red'>Добавить</p>"
    else
      return attr
    end
  end

  def validate_and_disable
    return "
    var ff = $(this).parents('form');
    if(ff.size() == 0){
    var ff = $('form#report')
    }
    ff.validate({});
    if(ff.valid() == false){ return false; event.returnValue = false} else{$(this).attr('disabled', 'disabled'); ff.submit();return false;}" 
  end

  def validate_and_tags
    return "
    var ff = $(this).parents('form');
    ff.validate({});
    if(ff.valid() == false){ return false; event.returnValue = false} else{$(this).attr('disabled', 'disabled'); $('#sanps').val('1'); $('#new_problems').modal('show');return false;}" 
  end

class Filters < ActionController::Base

    # Переменная для записи сесии
    $session = {}



    # Получаем и устанавливаем параметры и куки
    def setParams(allParams)
      if(allParams) then allParams.each {|key, value| $params[key.to_s] = value.to_s} end
    end

    def setCookies(allCookies)
      if(allCookies) then allCookies.each {|key, value| $cookies[key.to_s] = value.to_s} end
    end



    # Фильтр по сотрудникам
    def employees(employees)

      # работа с параметрами
      employee_selected = ApplicationHelper::ParamsWork::getParams("filter_empl")




      # Сам фильтр
      filter = "<select name='filter_empl'>"
      filter += "<option value='0' SELECTED>Все</option>"

      # Сам HTML код
      old_group_id = '0'
      groupOpened = false

      for val in employees
        empl_id = val['id']
        empl_login = val['login'].sub("'", "")
        group_id = val['division_id'].to_s


        if(group_id!=old_group_id)
          if(groupOpened)
            filter +='</optgroup>'
            groupOpened = false
          end
          filter +='<optgroup label="'+val['division'].to_s+'">'
          old_group_id = group_id
          groupOpened = true
        end

        if(employee_selected.to_s == empl_id.to_s) then selected='SELECTED' else selected='' end
        filter += "<option value="+empl_id.to_s+" "+selected+">"+empl_login.to_s+"</option>"
      end
      filter +='</optgroup></select>'

      return filter.to_s
    end



    # Фильтр по дням
    def days
      time = Time.new

      nowDay = time.day
      nowMonth = time.month
      nowYear = time.year
      maxDays = Time.days_in_month(nowMonth, nowYear)

      # работа с параметрами
      day_selected = ApplicationHelper::ParamsWork::getParams("filter_day")



      filter = "<select name='filter_day'>"
      filter += "<option value='0' SELECTED>Все</option>"
      i=1
      while i <= maxDays
        day_num = i.to_s
        if(day_num == day_selected.to_s) then selected ='SELECTED' else selected='' end
        filter += "<option value="+day_num+" "+selected+">"+day_num+"</option>"
        i+=1
      end
      filter += "</select>"

      return filter.to_s

    end


    # Фильтр по неделям



    # Фильтр по месяца
    def months
      time = Time.new

      nowDay = time.day
      nowMonth = time.month
      nowYear = time.year
      maxMonths = 12

      months = {}
      months[1] = "Январь"
      months[2] = "Февраль"
      months[3] = "Март"
      months[4] = "Апрель"
      months[5] = "Май"
      months[6] = "Июнь"
      months[7] = "Июль"
      months[8] = "Август"
      months[9] = "Сентябрь"
      months[10] = "Октябрь"
      months[11] = "Ноябрь"
      months[12] = "Декабрь"

      # работа с параметрами
      month_selected = ApplicationHelper::ParamsWork::getParams("filter_month")


      if(month_selected=='')
        month_selected = nowMonth
      end



      filter = "<select name='filter_month' ID='filter_month'>"
      i=1
      while i <= maxMonths
        month_num = i.to_s
        if(month_num == month_selected.to_s) then selected ='SELECTED' else selected='' end
        filter += "<option value="+month_num+" "+selected+">"+months[month_num.to_i]+"</option>"
        i+=1
      end
      filter += "</select>"

      return filter.to_s


    end

    # Фильтр по годам
    def years(department)
      time = Time.new

      nowYear = time.year

      # работа с параметрами
      year_selected = ApplicationHelper::ParamsWork::getParams("filter_year")





      query = ReportsDB.find_by_sql("SELECT date FROM reports WHERE department='"+department.to_s+"' ORDER BY id ASC LIMIT 1")
      if(query[0]!=nil)
        minYear = query[0]['date'].sub(/^.*([0-9]{4,4}).*$/, '\1').to_i
      else
        minYear = nowYear
      end

      filter = "<select name='filter_year' ID='filter_year'>"
      i=nowYear

            if(year_selected=='')

        year_selected = nowYear
      end
      while i >= minYear
        year_num = i.to_s
        if(year_num == year_selected.to_s) then selected ='SELECTED' else selected='' end
        filter += "<option value="+year_num+" "+selected+">"+year_num+"</option>"
        i-=1
      end
      filter += "</select>"

      return filter.to_s

    end

    # Фильтр по типу работ
    def workType

      # работа с параметрами
      worktype_selected = ApplicationHelper::ParamsWork::getParams("filter_worktype")





      filter = "<select name='filter_worktype'>"
      filter += "<option value='' SELECTED>Все</option>"
      i=0
      max = $category_info.length
      while i < max
        workType_num = $category_info[i]['id']
        workType_name = $category_info[i]['name']
        if(workType_num.to_s == worktype_selected.to_s) then selected ='SELECTED' else selected='' end
        filter += "<option value="+workType_num.to_s+" "+selected+">"+workType_name.to_s+"</option>"
        i+=1
      end
      filter += "</select>"

      return filter.to_s



    end

    # Фильтр по статусу
    def status

      # работа с параметрами
      status_selected = ApplicationHelper::ParamsWork::getParams("filter_status")





      filter = "<select name='filter_status'>"
      filter += "<option value='' SELECTED>Все</option>"
      i=0
      max = $status.length
      while i < max
        status_num = i.to_s
        status_name = $status[i]['name']
        if(status_num == status_selected) then selected ='SELECTED' else selected='' end
        filter += "<option value="+status_num+" "+selected+">"+status_name+"</option>"
        i+=1
      end
      filter += "</select>"

      return filter.to_s



    end


    # Фильтр по дате
    def date
      # работа с параметрами
      fdate = ApplicationHelper::ParamsWork::getParams("filter_fdate")



      filter = "<input type='text' name='filter_fdate' id='fdate' style='width: 80px;' readonly='1' value='"+fdate+"'>"
      filter += "&nbsp;<img src='/images/calendar.gif' ID='f_trigger_b' title='Календарь' style='cursor: pointer;'>"
      filter += "<script type='text/javascript'>Calendar.setup({ inputField: 'fdate', ifFormat: '%Y-%m-%d', showsTime: false, button: 'f_trigger_b', step: 1})</script>"

      return filter.to_s

    end

    # Фильтр по авариям (для АМС)
    def crash
      # работа с параметрами
      fcrash = ApplicationHelper::ParamsWork::getParams("filter_fcrash")



      filter = "<select name='filter_fcrash'>"
      filter += "<option value='' SELECTED>Все</option>"
      if(fcrash == "0") then selected = 'SELECTED' else selected='' end
      filter += "<option value='0' "+selected+">Устранена</option>"
      if(fcrash == "1") then selected = 'SELECTED' else selected='' end
      filter += "<option value='1' "+selected+">Не устранена</option>"
      filter += "</select>"

      return filter.to_s
    end

end


class ParamsWork

  def self.getParams(param)

    if($session && $session[param])
        selected = $session[param]
    #   cookies[cookie_name] = { :value => params[cookie_name], :expires => 30.days.from_now }
    #elsif(cookies[:filter_empl])
    #   selected = cookies[:filter_worktype]
    else
        selected = ''
    end
    return selected
  end
end



# Класс получает список сотрудников в зависимости от отдела
class UsersDB < ActiveRecord::Base
  self.table_name = "employees"

 def getAllEmployees(getDepartment)

    departments = [] # все отделы
    resultEmployees = {}

    # Проверяем есть ли запятые т.е. не один отдел
    # Если отдел - *, то выводит все отделы
    if(getDepartment!=nil)
      if(getDepartment.scan(/,/).size.to_i>0)
        # Разбиваем на массивы
        departments = getDepartment.split(',')
      else
        departments = [''+getDepartment.to_s+'']
      end
    else
      departments = ['155']
    end


    result = []
    currResult = []

    if(departments.include?('*'))
          resultDB = UsersDB.find_by_sql("SELECT * FROM employees WHERE quitted=0 ORDER BY department_id ASC, login ASC")
          currDep = ''
          for res in resultDB
              dep = res['department']
              if(dep!=currDep)
                result += [{'empl_id'=>'-1', 'login'=>''+dep+''}]
              end
                result += [res]
                currDep = dep
          end

    else
      for dep in departments
          currResult = UsersDB.find_by_sql("SELECT * FROM employees WHERE department_id='"+dep+"' && quitted=0 ORDER BY login ASC")
          if(currResult.size.to_i>0)
            result += [{'empl_id'=>'-1', 'login'=>''+currResult[0]['department']+''}]
            result += currResult
          end
      end
    end

    resultEmployees = result

    #for res in result
    # resultEmployees[res['empl_id']] = res['login'].capitalize
    #end

    return resultEmployees

  end





  def self.getEmployeeInfo(empl_id)
    result = UsersDB.find_by_sql("SELECT * FROM employees WHERE empl_id="+empl_id.to_s+"")
    if(result.size>0) then return result[0] else return false end
  end

  def self.getEmplDep(empl_id)
    result = UsersDB.find_by_sql("SELECT department_id, department FROM employees WHERE empl_id="+empl_id.to_s+"")
    return result
  end

end


# Класс формирует список (HTML) для тех групп которые указали также и всех сотрудников
class HTMLtemplates
    def getHtmlGroupEmployees(employees)
      # Сам HTML код
      old_group_id = '0'
      groupOpened = false

      result = "<select name=empl[] onChange=\"checkEmplNum(this); getStoreMaterials();\">"
      result += "<option value=0 SELECTED></option>"
      for val in employees
        empl_id = val['id']
        empl_login = val['login'].sub("'", "")
        group_id = val['division_id'].to_s


        if(group_id!=old_group_id)
          if(groupOpened)
            result +='</optgroup>'
            groupOpened = false
          end
          result +='<optgroup label="'+val['division'].to_s+'">'
          old_group_id = group_id
          groupOpened = true
        end

        result += "<option value="+empl_id.to_s+">"+empl_login.to_s+"</option>"
      end
      result +='</optgroup></select>'
      return result.to_s
    end
    def getHtmlGroupEmployeesAlp(employees)
      # Сам HTML код
      old_group_id = '0'
      groupOpened = false

      result = "<select name=empl[] onChange=\"checkEmplNum(this); getStoreMaterials(2299);\">"
      result += "<option value=0 SELECTED></option>"
      for val in employees
        empl_id = val['id']
        empl_login = val['login'].sub("'", "")
        group_id = val['division_id'].to_s


        if(group_id!=old_group_id)
          if(groupOpened)
            result +='</optgroup>'
            groupOpened = false
          end
          result +='<optgroup label="'+val['division'].to_s+'">'
          old_group_id = group_id
          groupOpened = true
        end

        result += "<option value="+empl_id.to_s+">"+empl_login.to_s+"</option>"
      end
      result +='</optgroup></select>'
      return result.to_s
    end


    def getHtmlAllEmployees(employees)
    #  tmp = ApplicationHelper::UsersDB.new
      #allEmployees = tmp.getAllEmployees('*')

      # Сам HTML код
      result = "<select name=empl[] onChange=checkEmplNum(this)>"
      result += "<option value=0 SELECTED></option>"
      for val in employees
        value = val['login'].sub("'", "")
        key = val['id']

       # if(employee_selected.to_s == key.to_s) then selected ='SELECTED' else selected='' end
        result += "<option value="+key.to_s+">"+value.to_s+"</option>"

      end

      result += "</select>"
      return result.to_s
    end

#    def getHtmlAllEmployeesWithGroups(employees)
#      # Сам HTML код
#     old_group_id = '' # переключатель открытости и закрытости группы
#      groupOpened = false
#
#      result = "<select name=empl[] onChange=\"checkEmplNum(this); getStoreMaterials();\">"
#     result += "<option value=0 SELECTED></option>"
#      for val in employees
#        empl_id = val['id']
#        empl_login = val['login'].sub("'", "")
#        group_id = val['division_id'].to_s
#
#
#
#        if(group_id!=old_group_id)
#          if(groupOpened)
#            result +='</optgroup>'
#            groupOpened = false
#          end
#          result +='<optgroup label="'+val['division'].to_s+'">'
##         old_group_id = group_id
#          groupOpened = true
#        end
#
#        result += "<option value="+empl_id.to_s+">"+empl_login.to_s+"</option>"
#      end
#      result +='</optgroup></select>'
#
#      return result.to_s
#    end

  def self.getHtmlGroupEmployeesOther(employees, name)

     # Сам HTML код
      old_group_id = '0'
      groupOpened = false

      result = "<select name='"+name+"'>"
      result += "<option value=0 SELECTED></option>"
      for val in employees
        empl_id = val['id']
        empl_login = val['login'].sub("'", "")
        group_id = val['division_id'].to_s


        if(group_id!=old_group_id)
          if(groupOpened)
            result +='</optgroup>'
            groupOpened = false
          end
          result +='<optgroup label="'+val['division'].to_s+'">'
          old_group_id = group_id
          groupOpened = true
        end

        result += "<option value="+empl_id.to_s+">"+empl_login.to_s+"</option>"
      end
      result +='</optgroup></select>'

      return result.to_s
  end


  # Шаблон материалов
  def self.getHtmlStoreMaterials(empl_name)

    empl_name = empl_name.to_s
    # Проверяем на строку т.к. можно спрашивать по ID сотрудника их материалs

    if(empl_name.scan(/^[0-9]*$/).size>0)
      empl_name = EmployeesDB.getUserName(empl_name)
    end


    materials = AssetsDB.getMaterials(empl_name)


    patternToFindJS = '"#[^0-9\.]#gi"'
    patternToRepalceJS = "''"

    result = '<table cellpadding="0" cellspacing="0" class="materials JSstoreMaterials">'
      result += '<tr>'
        result += "<th colspan=4 style='text-align: right; border-bottom-width:1px;'><img src='/images/minus.gif' ID='img_"+empl_name+"' style='vertical-align: text-bottom;'><span class='forRes' onClick='showStoreAssets(this);' style='cursor: pointer;'>"+empl_name+"</span></th>"
      result += '</tr>'

      if(materials!=nil && materials.to_s != 'false' && materials.size.to_i>0)
          materials.each {|key, data|
              if(data['name'] && data['amount'].to_i>0)
                # Получаем стоимость материала если он есть в прайсе
               price = PricelistDB.getPrice(data['asset_id'].to_s).to_s
               result += "<tr ID=\"assets_"+empl_name+"\" style='display: '';'>"
                  result += "<td style='width: 200px; text-align: left;'>"+data['name'].to_s+"</td>"
                  readonly = (price.to_i>0) ? "readonly 1" : ""
                  result += "<td class='pric'><input style='width: 50px;' type=\"text\" value=\""+price+"\" name=\"mprice_"+data['asset_id'].to_s+"|"+empl_name+"\" value=\"\" onkeyup=\"this.value=this.value.replace(/[^0-9.]/ig, ''); setTotalSum(); getStoreSerials(this);\" "+readonly+"><div class='help'>руб.</div></td>"
                  result += "<td><input type='text' name=\"material_"+data['asset_id'].to_s+"|"+empl_name+"\" ID=\"material_"+data['asset_id'].to_s+"|"+empl_name+"\" maxlength='5' onKeyUp=\"check_isInt(this); check_isAmount(this, '"+data['amount'].to_s+"'); setTotalSum(); getStoreSerials(this);\" style='width: 30px;'><div class='help'>На руках: "+data['amount'].to_s+"</div></td>"
                  result += "<td><input type='button' value='+' onClick=\"plusButton('material_"+data['asset_id'].to_s+"|"+empl_name+"'); check_isAmount('material_"+data['asset_id'].to_s+"|"+empl_name+"', "+data['amount'].to_s+"); setTotalSum(); getStoreSerials(this);\" style='width: 20px;'>&nbsp;&nbsp;<input type='button' value='-' onClick=\"minusButton('material_"+data['asset_id'].to_s+"|"+empl_name+"'); setTotalSum(); getStoreSerials(this);\" style='width: 20px;'></td>"
                result += '</tr>'
              end
          }
      else
        result += '<tr><td colspan=3 style="color: gray; font-style: italic; font-size: 12px;">Материалы не брал.</td></tr>'
      end
    result += '</table>'
  end


  def self.getHtmlDoneStoreMaterials(report_id)

    materials = MaterialsDoneDB.getMaterials(report_id)
    result = '<table cellpadding="0" cellspacing="0" class="materials" ID="materials">'

    if(materials!=false)
        materials.each {|key, data|
          empl_name = key
          result += '<tr>'
              result += "<th colspan=2 style='text-align: right; border-bottom-width:1px;'><span class='forRes'>"+empl_name+"</span></th>"
          result += '</tr>'

            for info in data
            #data.each {|info|
              if(info['count'].to_i>0)
                result += '<tr>'
                  result += "<td>"+info['material_name'].to_s+"</td>"
                  if(info['price'].to_i>0)
                    result += "<td>"+info['count'].to_s+" x "+info['price'].to_s+" руб.</td>"
                  else
                    result += "<td>"+info['count'].to_s+"</td>"
                  end
                result += '</tr>'
              end

            #}
            end
        }
    else
       result += '<tr><td colspan=2 style="color: gray; font-style: italic; font-size: 12px;">Материалы не установлены.</td></tr>'
    end
    result += '</table>'
  end




  # Шаблон для вывода серийников (используется в Аякс)
  def self.getHTMLSerials(material_id, count, empl_name)
     result = ''
     count = count.to_i
     #serials = AssetsDB.getSerials(material_id, empl_id)
     empl_id = AssetsDB.getUserId(empl_name)
    serials = StoreReport.getSerials(material_id, empl_id, empl_name)

     if(serials!='false' && serials.size>0)
       result = '<div style="color: gray; font-size: 11px; font-style: italic;" ID="serial_'+material_id+'">Серийные номера:<br><table cellpadding="0" cellspacing="0">'
          i=0
          while i<count
            result += '<tr>'
              result += "<td class='noBorder'>"
                result += (i+1).to_s+". <select name='serial_"+material_id+"[]' class='JSserialStore' onChange='checkSerial(this);'>"
                result += "<option value='0'></option>"
                for serial in serials
                  result += "<option value='"+serial.to_s+"'>"+serial.to_s+"</option>"
                end
                result += "</select>"
            result += '</tr>'
            i+=1
          end
       result += '</table></div>'
     end
    return result
  end


  # Шаблон для работ из прайслиста.
  def self.getHTMLPricelistWorks(division_id, report_id, clientType='P')

    works = PricelistDB.getPositions(division_id, report_id, clientType)
    if(report_id.to_i>0)
      doneWorks = WorksPricelistDoneDB.getWorks(report_id)
    end
    result = '<table cellpadding="0" cellspacing="0" class="materials" ID="works">'

    if(works!=false)
        works.each {|key, data|
          section_name = key
          result += '<tr>'
              result += "<th colspan=4 style='text-align: right; border-bottom-width:1px;'><span class='forRes'>"+section_name+"</span></th>"
          result += '</tr>'


            data.each {|wid, info|
              result += '<tr>'
                result += "<td style=\"text-align: left;\">"+info['name'].to_s+""
                if(info['price'].to_i>0)
                  result += "<div class='clientPrice'>Стоимость для клиента: <span class='JS_clientprice'>"+info['price'].to_s+"</span> руб</div>"
                else
                  result += "<div class='clientPrice'><span class='JS_clientprice' style='display: none;'>0</span></div>"
                end
                result += "</td>"
                if(division_id != "151" && division_id != "251")
                  result += "<td><input type=\"text\" name=\"workprice_"+wid+"\" style=\"width: 45px;\" value=\""+info['rate'].to_s+"\"readonly></td>"
                else
                  result += "<td><input type=\"hidden\" name=\"workprice_"+wid+"\" style=\"width: 45px;\" value=\""+info['rate'].to_s+"\"></td>"
                end
                value = (doneWorks && doneWorks[wid.to_i]!=nil) ? doneWorks[wid.to_i].to_s : ""
                result += "<td><input type=\"text\" ID=\"work_"+wid+"\" name=\"work_"+wid+"\" style=\"width: 25px;\" value=\""+value+"\" onkeyup=\"this.value=this.value.replace(/[^0-9]/ig, ''); setTotalSum();\"></td>"
                result +="<td style=\"white-space: nowrap;\"><input type=\"button\" value=\"+\" onClick=\"plusButton('work_"+wid+"', '1'); setTotalSum();\" style=\"width: 20px;\">&nbsp;&nbsp;<input type=\"button\" value=\"-\" onClick=\"minusButton('work_"+wid+"', '1'); setTotalSum();\" style=\"width: 20px;\"></td>"
              result += '</tr>'

            }
        }
    else
       result += '<tr><td colspan=2 style="color: gray; font-style: italic; font-size: 12px;">Работы не установлены.</td></tr>'
    end
    result += '</table>'


    return result

  end


   # Шаблон для работ из не из прайслиста.
  def self.getHTMLAddWorks(division, report_id, category=false, isAddPrice=false)

    works = WorksDB.getWorks(division, category)
    if(report_id.to_i>0)
      doneWorks = WorksDoneDB.getWorks(report_id)
    end
    result = '<table cellpadding="0" cellspacing="0" class="materials" ID="addworks">'
    result += '<tr>'
           result += "<th colspan=4 style='text-align: right; border-bottom-width:1px;'><span class='forRes'>Дополнительные работы</span></th>"
    result += '</tr>'




    if(works!=false && works.size>1)
        for info in works
          if(info && info['id'])

              wid = info['id'].to_s
              result += '<tr>'
                result += "<td style=\"text-align: left;\">"+info['name'].to_s+""
                if(info['price'].to_i>0)
                  result += "<div class='clientPrice'>Стоимость для клиента: <span class='JS_clientprice'>"+info['price'].to_s+"</span> руб</div>"
                else
                  result += "<div class='clientPrice'><span class='JS_clientprice' style='display: none;'>0</span></div>"
                end
                result += "</td>"

                emplPrice = (isAddPrice) ? info['addrate'].to_s : info['rate'].to_s
                if(division!="ams" && division!="soft")
                  result += "<td><input type=\"text\" name=\"addworkprice_"+wid+"\" style=\"width: 45px;\" value=\""+emplPrice+"\"readonly></td>"
                else
                  result += "<td><input type=\"hidden\" name=\"addworkprice_"+wid+"\" style=\"width: 45px;\" value=\""+emplPrice+"\"></td>"
                end
                value = (doneWorks && doneWorks[wid.to_i]!=nil) ? doneWorks[wid.to_i].to_s : ""
                if(division=="mod")
                  result += "<td><input type=\"text\" maxlength=\"3\" ID=\"addwork_"+wid+"\" name=\"addwork_"+wid+"\" style=\"width: 25px;\" value=\""+value+"\" onkeyup=\"this.value=this.value.replace(/[^0-9.]/ig, ''); setCountCable('addwork_"+wid+"'); setTotalSum();\"></td>"
                  result +="<td style=\"white-space: nowrap;\"><input type=\"button\" value=\"+\" onClick=\"plusButton('addwork_"+wid+"', '"+info['step'].to_s+"'); setCountCable('addwork_"+wid+"'); setTotalSum();\" style=\"width: 20px;\">&nbsp;&nbsp;<input type=\"button\" value=\"-\" onClick=\"minusButton('addwork_"+wid+"', '"+info['step'].to_s+"'); setCountCable('addwork_"+wid+"');\" style=\"width: 20px;\"></td>"
                else
                  result += "<td><input type=\"text\" maxlength=\"3\" ID=\"addwork_"+wid+"\" name=\"addwork_"+wid+"\" style=\"width: 25px;\" value=\""+value+"\" onkeyup=\"this.value=this.value.replace(/[^0-9.]/ig, ''); setTotalSum();\"></td>"
                  result +="<td style=\"white-space: nowrap;\"><input type=\"button\" value=\"+\" onClick=\"plusButton('addwork_"+wid+"', '"+info['step'].to_s+"'); setTotalSum();\" style=\"width: 20px;\">&nbsp;&nbsp;<input type=\"button\" value=\"-\" onClick=\"minusButton('addwork_"+wid+"', '"+info['step'].to_s+"'); setTotalSum();\" style=\"width: 20px;\"></td>"
                end
              result += '</tr>'
          end
        end
    else
       result += '<tr><td colspan=2 style="color: gray; font-style: italic; font-size: 12px;">Работы не установлены.</td></tr>'
    end
    result += '</table>'


    return result

  end


end



# Класс формирует шаблоны для отправки сообщений на почту
class HTMLtemplatesMail

  # Только з/п
  def self.template1(empl_id, department, day, month, year)
    result = ""
    zp = 0

    info = EmployeesDoneDB.getDateEmployee(empl_id, department, day, month, year)
    for data in info
      zp += data['sum'].to_f
    end
    empl_name = EmployeesDB.getUserName(empl_id)
    result += "Здравствуйте, "+empl_name.to_s+"!\n\n\n"
    result += (day.to_i>0) ? "За период: "+day.to_s+"/"+month.to_s+"/"+year.to_s+"" : "За период: xx/"+month.to_s+"/"+year.to_s+"\n"
    result += "Ваша з/п составила: "+zp.to_s+" руб."
    result += "\n\n\n\n\n\n\n Служба информации компании РИНЕТ."
  end

  # з/п + расшифровка
  def self.template2(empl_id, department, day, month, year)
    result = ""
    zp = 0
    log = ""

    info = EmployeesDoneDB.getDateEmployee(empl_id, department, day, month, year)
    for data in info
      log += ""+data['date_create_report'].to_s+" - "+data['sum'].to_s+" руб.\n"
      zp += data['sum'].to_f
    end
    log += "Итого: "+zp.to_s+" руб."
    result += (day.to_i>0) ? "За период: "+day.to_s+"/"+month.to_s+"/"+year.to_s+"" : "За период: xx/"+month.to_s+"/"+year.to_s+"\n"
    result += "Ваша з/п составила: "+log.to_s+" руб."
    result += "\n\n\n\n\n\n\n Служба информации компании РИНЕТ."
  end

end










end


