<?php
/**
 * The buildform view of search module of ZDOO.
 *
 * @copyright   Copyright 2009-2018 青岛易软天创网络科技有限公司(QingDao Nature Easy Soft Network Technology Co,LTD, www.cnezsoft.com)
 * @license     ZPL (http://zpl.pub/page/zplv12.html)
 * @author      Chunsheng Wang <chunsheng@cnezsoft.com>
 * @package     search
 * @version     $Id: buildform.html.php 4129 2013-01-18 01:58:14Z wwccss $
 * @link        http://www.zdoo.com
 */
?>
<?php include '../../../sys/common/view/picker.html.php';?>
<?php js::set('likeFields', $likeFields);?>
<?php js::set('usePicker', $usePicker);?>
<div class='container'>
  <style>
  #featurebar .nav {z-index: 999; position: relative;}
  #querybox {margin-bottom: 10px;}
  #querybox > .container {padding: 0 20px;}
  #querybox form {position: relative; background: #FFFFFF; box-shadow: 0 0 8px 2px rgba(225,225,225,0.50); border-radius: 4px; padding: 10px; padding-right: 50px;}
  #querybox .table {border: none; table-layout: fixed;}
  #querybox .table-form td {border: none; vertical-align: middle; line-height: 1}
  #querybox .btn {padding: 6px 8px;}
  #querybox .table-form td td {padding: 2px;}
  #querybox .table .table {margin: 0;}
  .outer #querybox .table tr > th:first-child, .outer #querybox .table tr > td:first-child,
  .outer #querybox .table tr > th:last-child, .outer #querybox .table tr > td:last-child,
  .outer #querybox .table tbody > tr:last-child td {padding: 2px}
  #querybox a:hover {text-decoration: none;}

  #selectPeriod {padding: 4px; height: 197px; min-width: 120px}
  #selectPeriod > .dropdown-header {background: #f1f1f1; display: block; text-align: center; padding: 4px 0; line-height: 20px; margin-bottom: 5px; font-size: 14px; border-radius: 2px; color: #333; font-size: 12px}
  #selectPeriod li > a {padding: 3px 15px; border-radius: 2px}

  #moreOrLite {position: absolute; right: 0; top: 0; bottom: 0}
  #searchlite, #searchmore {width: 50px; padding: 0 5px; line-height: 70px; text-align: center; opacity: 0.7}
  #searchlite {line-height: 140px}
  #searchform.showmore #searchmore, #searchform #searchlite {display: none;}
  #searchform.showmore #searchlite, #searchform #searchmore {display: inline-block;}
  #searchlite > i, #searchmore > i {font-size: 14px;}

  .bootbox-prompt .modal-dialog {width: 500px; margin-top: 10%;}
  #groupAndOr {display: inline-block;}

  .outer > #querybox {margin: -20px -20px 20px; border-top: none; border-bottom: 1px solid #ddd}
  .table-form td + td, .table-form th + th {padding-left: 0;}
  .search-field input.date::-webkit-input-placeholder{color: #000000; opacity: 1;}
  .search-field input.date::-moz-placeholder{color: #000000; opacity: 1;}
  .search-field input.date:-ms-input-placeholder{color: #000000; opacity: 1;}
  .search-field .chosen-container{display: block;}

  .trader_chosen .chosen-results > li.no-results {cursor: pointer;}
  .trader_chosen .chosen-results > li.no-results:hover {color: #1a4f85; background-color: #ddd;}
  .trader_chosen .chosen-results > li.no-results > span {font-weight: bold;}

  .contract_chosen .chosen-results > li.no-results {cursor: pointer;}
  .contract_chosen .chosen-results > li.no-results:hover {color: #1a4f85; background-color: #ddd;}
  .contract_chosen .chosen-results > li.no-results > span {font-weight: bold;}

  .contact_chosen .chosen-results > li.no-results {cursor: pointer;}
  .contact_chosen .chosen-results > li.no-results:hover {color: #1a4f85; background-color: #ddd;}
  .contact_chosen .chosen-results > li.no-results > span {font-weight: bold;}

  .order_chosen .chosen-results > li.no-results {cursor: pointer;}
  .order_chosen .chosen-results > li.no-results:hover {color: #1a4f85; background-color: #ddd;}
  .order_chosen .chosen-results > li.no-results > span {font-weight: bold;}

  .batch_chosen .chosen-results > li.no-results {cursor: pointer;}
  .batch_chosen .chosen-results > li.no-results:hover {color: #1a4f85; background-color: #ddd;}
  .batch_chosen .chosen-results > li.no-results > span {font-weight: bold;}

  .w-380px {width: 380px !important;}
  </style>
  <script>
  var $selectedItem;
  var selectItem = function(item)
  {
      $selectedItem = $(item).first();
      $('#searchModal').modal('hide');
  };

  var selector  = '';
  var relation  = '';
  var orderType = '';
  var batchType = '';
  var trader    = 'customer';
  var contract  = 'contract';
  var contact   = 'contact';
  var order     = 'order';
  var batch     = 'batch';

  $(document).ready(function()
  {
      switch(config.currentModule)
      {
          case 'contact':
              relation = 'client';
              trader   = 't2.customer';
              break;
          case 'batch' :
              trader = 'trader';
              break;
          case 'feedback':
              relation = 'client';
              trader   = 'customer';
              break;
          case 'invoice':
              relation = 'client';
              break;
          case 'order':
              relation = 'client';
              trader   = 'o.customer';
              break;
          case 'payable':
              relation  = 'provider';
              orderType = 'purchase';
              batchType = 'in';
              trader    = 't1.trader';
              contract  = 't1.contract';
              order     = 't1.order';
              batch     = 't1.batch';
              break;
          case 'purchase':
              relation  = 'provider';
              trader    = 'trader';
              break;
          case 'receivable':
              relation  = 'client';
              orderType = 'sale';
              batchType = 'out';
              trader    = 't1.trader';
              contract  = 't1.contract';
              order     = 't1.order';
              batch     = 't1.batch';
              break;
          case 'sale':
              relation = 'client';
              trader   = 'trader';
              break;
          case 'trade':
              relation = v.modeType == 'in' ? 'client' : '';
              trader   = 'trader';
              break;
      }

      var showSearchModal = function(e)
      {
          $('#searchform .trader.selected').removeClass('selected');
          $('#searchform .contract.selected').removeClass('selected');
          $('#searchform .contact.selected').removeClass('selected');
          $('#searchform .order.selected').removeClass('selected');
          $('#searchform .batch.selected').removeClass('selected');

          if(e.hasClass('no-results'))
          {
              var key = e.parents('.chosen-container').find('.chosen-results > li.no-results > span').text();
              e.parents('.chosen-container').prev('select').addClass('selected');
          }
          else
          {
              var key = e.next('.chosen-container').find('.chosen-results > li.no-results > span').text();
              e.addClass('selected');
          }

          var link = '';
          if(selector == 'trader')   link = createLink('customer', 'ajaxSearchCustomer', 'key=' + key + '&relation=' + relation);
          if(selector == 'contract') link = createLink('crm.contract', 'ajaxSearchContract', 'key=' + key);
          if(selector == 'contact')  link = createLink('crm.contact', 'ajaxSearchContact', 'key=' + key);
          if(selector == 'batch')    link = createLink('psi.batch', 'ajaxSearchBatch', 'key=' + key + '&type=' + batchType);
          if(selector == 'order')
          {
              if(config.currentModule == 'receivable' || config.currentModule == 'payable' || config.currentModule == 'batch') link = createLink('psi.order', 'ajaxSearchOrder', 'key=' + key + '&type=' + orderType);
              if(config.currentModule == 'contract' || config.currentModule == 'trade') link = createLink('crm.order', 'ajaxSearchOrder', 'key=' + key);
          }

          $.zui.modalTrigger.show({name: 'searchModal', url: link, backdrop: 'static'});
      };

      $(document).on('change', '#searchform .trader', function()
      {
          if($(this).val() === 'ajax_search_more')
          {
              selector = 'trader';
              showSearchModal($(this));
          }
      });

      $(document).on('change', '#searchform .contract', function()
      {
          if($(this).val() === 'ajax_search_more')
          {
              selector = 'contract';
              showSearchModal($(this));
          }
      });

      $(document).on('change', '#searchform .contact', function()
      {
          if($(this).val() === 'ajax_search_more')
          {
              selector = 'contact';
              showSearchModal($(this));
          }
      });

      $(document).on('change', '#searchform .order', function()
      {
          if($(this).val() === 'ajax_search_more')
          {
              selector = 'order';
              showSearchModal($(this));
          }
      });

      $(document).on('change', '#searchform .batch', function()
      {
          if($(this).val() === 'ajax_search_more')
          {
              selector = 'batch';
              showSearchModal($(this));
          }
      });

      $(document).on('click', '#searchform .trader_chosen .chosen-results > li.no-results', function()
      {
          if($(this).closest('tr').find('select[id^=field]').val() == trader)
          {
              selector = 'trader';
              showSearchModal($(this));
          }
      });

      $(document).on('click', '#searchform .contract_chosen .chosen-results > li.no-results', function()
      {
          if($(this).closest('tr').find('select[id^=field]').val() == contract)
          {
              selector = 'contract';
              showSearchModal($(this));
          }
      });

      $(document).on('click', '#searchform .contact_chosen .chosen-results > li.no-results', function()
      {
          if($(this).closest('tr').find('select[id^=field]').val() == contact)
          {
              selector = 'contact';
              showSearchModal($(this));
          }
      });

      $(document).on('click', '#searchform .order_chosen .chosen-results > li.no-results', function()
      {
          if($(this).closest('tr').find('select[id^=field]').val() == order)
          {
              selector = 'order';
              showSearchModal($(this));
          }
      });

      $(document).on('click', '#searchform .batch_chosen .chosen-results > li.no-results', function()
      {
          if($(this).closest('tr').find('select[id^=field]').val() == batch)
          {
              selector = 'batch';
              showSearchModal($(this));
          }
      });

      $(document).on('hide.zui.modal', '#searchModal', function()
      {
          if(selector)
          {
              var key       = '';
              var $selector = $('#searchform .' + selector + '.selected');
              if($selectedItem && $selectedItem.length)
              {
                  key = $selectedItem.data('key');
                  if(!$selector.children('option[value="' + key + '"]').length)
                  {
                      $selector.prepend('<option value="' + key + '">' + $selectedItem.text() + '</option>');
                  }

                  $('#searchform .' + selector).each(function()
                  {
                      if(!$(this).children('option[value="' + key + '"]').length)
                      {
                          $(this).prepend('<option value="' + key + '">' + $selectedItem.text() + '</option>');
                          $(this).trigger('chosen:updated');
                      }
                  });

                  if(!$('#querybox [id^=box] .' + selector).children('option[value="' + key + '"]').length)
                  {
                      $('#querybox [id^=box] .' + selector).prepend('<option value="' + key + '">' + $selectedItem.text() + '</option>');
                  }
              }
              $selector.val(key).trigger('chosen:updated');
              $selectedItem = null;
          }
      });
  });

  var dtOptions =
  {
      language: '<?php echo $this->app->getClientLang();?>',
      weekStart: 1,
      todayBtn:  1,
      autoclose: 1,
      todayHighlight: 1,
      startView: 2,
      minView: 2,
      forceParse: 0,
      format: 'yyyy-mm-dd'
  };

  var datetimeOptions =
  {
      language: '<?php echo $this->app->getClientLang();?>',
      weekStart: 1,
      todayBtn:  1,
      autoclose: 1,
      todayHighlight: 1,
      startView: 2,
      forceParse: 0,
      format: 'yyyy-mm-dd hh:ii'
  };

  $(function()
  {
      $('.date').each(function()
      {
          time = $(this).val();
          if(!isNaN(time) && time != ''){
              var Y = time.substring(0, 4);
              var m = time.substring(4, 6);
              var d = time.substring(6, 8);
              time = Y + '-' + m + '-' + d;
              $('.date').val(time);
          }
          setDateField(this, undefined, 'date');
      });

      $('.datetime').each(function()
      {
          time = $(this).val();
          if(!isNaN(time) && time != ''){
              var Y = time.substring(0, 4);
              var m = time.substring(4, 6);
              var d = time.substring(6, 8);
              var h = time.substring(8, 10);
              var i = time.substring(10, 12);
              time = Y + '-' + m + '-' + d + ' ' + h + ':' + i;
              $('.datetime').val(time);
          }
          setDateField(this, undefined, 'datetime');
      });

      $(document).on('change', '[name*=operator]', function()
      {
          currentField = $(this).parent('td').prev('td').children('select').val();
          if(currentField.indexOf('.') !== -1) currentField = currentField.substr(currentField.indexOf('.') + 1);

          if(v.likeFields.indexOf(currentField) !== -1)
          {
              $valueTD = $(this).parent('td').next('td');
              if($(this).val() == 'include' || $(this).val() == 'notinclude')
              {
                  $valueTD.find('select').attr('disabled', 'true');
                  $valueTD.find('input.searchInput').show();
                  if($valueTD.find('.chosen-container').length)
                  { 
                      $valueTD.find('.chosen-container').hide();
                  }
                  else
                  {
                      $valueTD.find('.picker').hide();
                  }
              }
              else
              {
                  $valueTD.find('input.searchInput').hide();
                  if($valueTD.find('.chosen-container').length)
                  {
                      $valueTD.find('select').removeAttr('disabled').trigger("chosen:updated");
                      $valueTD.find('[id*=_chosen]').show();
                  }
                  else
                  {
                      $valueTD.find('.picker').show();
                  }
              }
          }
          if($(this).val() == 'between' && $(this).parent('td').next('td').find('input').val() != '' && $(this).parent('td').next('td').find('input').val().indexOf('$') == -1) $(this).val('<=');
      });

      $(document).on('change', '[name*=field]', function()
      {
          $(this).parent('td').next('td').find('[name*=operator]').change();
      });
  });

  var params        = <?php echo json_encode($fieldParams);?>;
  var groupItems    = <?php echo $config->search->groupItems;?>;
  var setQueryTitle = '<?php echo $lang->search->setQueryTitle;?>';
  var module        = '<?php echo $module;?>';
  var actionURL     = '<?php echo $actionURL;?>';

  /**
   * Set date field
   *
   * @param  string $query
   * @return void
   */
  function setDateField(query, fieldNO, type)
  {
      var $query = $(query);
      if(fieldNO === undefined) fieldNO = $query.closest('.search-field').data('id');
      var $period = $('#selectPeriod');

      if(type == 'date') var options = dtOptions;
      if(type == 'datetime') var options = datetimeOptions;

      if(!$period.length)
      {
          $period = $("<ul id='selectPeriod' class='dropdown-menu'><li class='dropdown-header'><?php echo $lang->datepicker->dpText->TEXT_OR . ' ' . $lang->datepicker->dpText->TEXT_DATE;?></li><li><a href='#lastWeek'><?php echo $lang->datepicker->dpText->TEXT_PREV_WEEK;?></a></li><li><a href='#thisWeek'><?php echo $lang->datepicker->dpText->TEXT_THIS_WEEK;?></a></li><li><a href='#yesterday'><?php echo $lang->datepicker->dpText->TEXT_YESTERDAY;?></a></li><li><a href='#today'><?php echo $lang->datepicker->dpText->TEXT_TODAY;?></a></li><li><a href='#lastMonth'><?php echo $lang->datepicker->dpText->TEXT_PREV_MONTH;?></a></li><li><a href='#thisMonth'><?php echo $lang->datepicker->dpText->TEXT_THIS_MONTH;?></a></li><li><a href='#thisYear'><?php echo $lang->datepicker->dpText->TEXT_THIS_YEAR;?></a></li><li><a href='#lastYear'><?php echo $lang->datepicker->dpText->TEXT_PREV_YEAR;?></a></li></ul>").appendTo('body');
          $period.find('li > a').click(function(event)
          {
              var target = $('#' + $period.data('target'));
              if(target.length)
              {
                  if(target.next('input[type=hidden]').length)
                  {
                      target.next('input[type=hidden]').val($(this).attr('href').replace('#', '$'));
                      target.attr('placeholder', $(this).attr('href').replace('#', '$'));
                  }
                  else
                  {
                      target.val($(this).attr('href').replace('#', '$'));
                  }
                  $('#operator' + $period.data('fieldNO')).val('between');
                  $period.hide();
              }
              event.stopPropagation();
              return false;
          });
      }
      $query.datetimepicker('remove').datetimepicker(options).on('show', function(e)
      {
          var $e = $(e.target);
          var ePos = $e.offset();
          $period.css({'left': ePos.left + 211, 'top': ePos.top + 29, 'min-height': $('.datetimepicker').outerHeight()}).show().data('target', $e.attr('id')).data('fieldNO', fieldNO).find('li.active').removeClass('active');
          if($e.attr('placeholder'))
          {
              $period.find("li > a[href='" + $e.attr('placeholder').replace('$', '#') + "']").closest('li').addClass('active');
          }
          else
          {
              $period.find("li > a[href='" + $e.val().replace('$', '#') + "']").closest('li').addClass('active');
          }
      }).on('changeDate', function()
      {
          var opt = $('#operator' + $period.data('fieldNO'));
          var target = $('#' + $period.data('target'));
          if(target.length)
          {
              if(target.next('input[type=hidden]').length)
              {
                  target.next('input[type=hidden]').val(target.val());
              }
          }
          if(opt.val() == 'between') opt.val('<=');
          $period.hide();
      }).on('hide', function(){setTimeout(function(){$period.hide();}, 200);});
  }

  /**
   * When the value of the fields select changed, set the operator and value of the new field.
   *
   * @param  string $fieldName
   * @param  int    $fieldNO
   * @access public
   * @return void
   */
  function setField(fieldName, fieldNO)
  {
      $('#operator' + fieldNO).val(params[fieldName]['operator']);   // Set the operator according the param setting.
      $('#operator' + fieldNO).trigger("chosen:updated");
      $('#valueBox' + fieldNO).html($('#box' + fieldName.replace('.', '\\.')).children().clone());
      $('#valueBox' + fieldNO).children().attr({name : 'value' + fieldNO, id : 'value' + fieldNO});

      if(typeof(params[fieldName]['class']) != undefined && (params[fieldName]['class'] == 'date' || params[fieldName]['class'] == 'datetime'))
      {
          var type = params[fieldName]['class'];
          setDateField("#value" + fieldNO, fieldNO, type);
          $("#value" + fieldNO).addClass(type);   // Shortcut the width of the datepicker to make sure align with others.
          var groupItems = <?php echo $config->search->groupItems?>;
          var maxNO      = 2 * groupItems;
          var nextNO     = fieldNO > groupItems ? fieldNO - groupItems + 1 : fieldNO + groupItems;
          var nextValue  = $('#value' + nextNO).val();
          if(nextNO <= maxNO && fieldNO < maxNO && (nextValue == '' || nextValue == 0))
          {
              $('#field' + nextNO).val($('#field' + fieldNO).val()).trigger('chosen:updated');
              $('#operator' + nextNO).val('<=').trigger('chosen:updated');
              $('#valueBox' + nextNO).html($('#box' + fieldName.replace('.', '\\.')).children().clone());
              $('#valueBox' + nextNO).children().attr({name : 'value' + nextNO, id : 'value' + nextNO});
              setDateField("#value" + nextNO, nextNO, type);
              $("#value" + nextNO).addClass(type);
          }
      }

      var attr = {'data-no_results_text': '<?php echo $lang->searchMore;?>', 'data-max_drop_width': '300', 'data-no_wrap': 'true'};
      if(fieldName == trader)   $('#valueBox' + fieldNO).children().addClass('trader').attr(attr);
      if(fieldName == contract) $('#valueBox' + fieldNO).children().addClass('contract').attr(attr);
      if(fieldName == contact)  $('#valueBox' + fieldNO).children().addClass('contact').attr(attr);
      if(fieldName == order)    $('#valueBox' + fieldNO).children().addClass('order').attr(attr);
      if(fieldName == batch)    $('#valueBox' + fieldNO).children().addClass('batch').attr(attr);

      if(params[fieldName]['control'] == 'select' && (typeof(params[fieldName]['class']) == 'undefined' || params[fieldName]['class'] == 'chosen'))
      {
          var $select = $('select#value' + fieldNO);
          initSelect($select);

          if(fieldName == trader)   $select.next('.chosen-container').addClass('trader_chosen');
          if(fieldName == contract) $select.next('.chosen-container').addClass('contract_chosen');
          if(fieldName == contact)  $select.next('.chosen-container').addClass('contact_chosen');
          if(fieldName == order)    $select.next('.chosen-container').addClass('order_chosen');
          if(fieldName == batch)    $select.next('.chosen-container').addClass('batch_chosen');
      }
  }

  /**
   * Reset forms.
   *
   * @access public
   * @return void
   */
  function resetForm()
  {
      for(i = 1; i <= groupItems * 2; i ++)
      {
          $value = $('[name=value' + i + ']');
          if($value.data('zui.picker'))
          {
              $value.data('zui.picker').setValue('');
          }
          else
          {
              $value.val('').trigger("chosen:updated");
          }
          $('#dateValue' + i).attr('placeholder', '');
      }
  }

  /**
   * Show more fields.
   *
   * @access public
   * @return void
   */
  function showmore()
  {
      for(i = 1; i <= groupItems * 2; i ++)
      {
          if(i != 1 && i != groupItems + 1 )
          {
              $('#searchbox' + i).removeClass('hidden');
          }
      }

      $('#formType').val('more');
      $('#searchform').addClass('showmore');
      $.zui.store.pageSet('showMode', 'more');
  }

  /**
   * Show lite search form.
   *
   * @access public
   * @return void
   */
  function showlite()
  {
      $('[name*=operator]').change();
      for(i = 1; i <= groupItems * 2; i ++)
      {
          if(i != 1 && i != groupItems + 1)
          {
              $('#value' + i).val('');
              $('#searchbox' + i).addClass('hidden');
          }
      }
      $('#searchform').removeClass('showmore');
      $('#formType').val('lite');
      $.zui.store.pageSet('showMode', 'lite');
  }

  /**
   * Save the query.
   *
   * @access public
   * @return void
   */
  function saveQuery()
  {
      bootbox.prompt(setQueryTitle, function(r)
      {
          if(!r) return;
          saveQueryLink = createLink('search', 'saveQuery');
          $.post(saveQueryLink, {title: r, module: module}, function(data)
          {
              if(data == 'success') location.reload();
          });
      });
  }

  /**
   * Execute a query.
   *
   * @param  int    $queryID
   * @access public
   * @return void
   */
  function executeQuery(queryID)
  {
      if(!queryID) return;
      location.href = createLink('search', 'buildQuery', 'queryID=' + queryID);
  }

  /**
   * Delete a query.
   *
   * @access public
   * @return void
   */
  function deleteQuery()
  {
      queryID = $('#queryID').val();
      if(!queryID) return;
      hiddenwin.location.href = createLink('search', 'deleteQuery', 'queryID=' + queryID);
  }
  </script>

  <div class='hidden'>
  <?php
  $trader   = '';
  $contract = '';
  $contact  = '';
  $order    = '';
  $batch    = '';
  switch($module)
  {
      case 'batch' :
          $trader = 'trader';
          $order  = 'order';
          break;
      case 'contact' :
          $trader = 't2.customer';
          break;
      case 'feedback' :
          $trader = 'customer';
          break;
      case 'invoice' :
          $trader   = 'customer';
          $contract = 'contract';
          $contact  = 'contact';
          break;
      case 'order' :
          $trader = 'o.customer';
          break;
      case 'receivable' :
      case 'payable' :
          $trader   = 't1.trader';
          $contract = 't1.contract';
          $order    = 't1.order';
          $batch    = 't1.batch';
          break;
      case 'sale' :
      case 'purchase' :
          $trader   = 'trader';
          $contract = 'contract';
          break;
      case 'trade' :
          $trader   = 'trader';
          $contract = 'contract';
          $order    = 'order';
          break;
  }
  /* Print every field as an html object, select or input. Thus when setFiled is called, copy it's html to build the search form. */
  foreach($fieldParams as $fieldName => $param)
  {
      $class = $fieldName == $trader ? 'trader' : '';
      $class = (!$class && $fieldName == $contract) ? 'contract' : $class;
      $class = (!$class && $fieldName == $contact)  ? 'contact'  : $class;
      $class = (!$class && $fieldName == $order)    ? 'order'    : $class;
      $class = (!$class && $fieldName == $batch)    ? 'batch'    : $class;

      echo "<span id='box$fieldName'>";
      $realField = strpos($fieldName, '.') !== false ? substr($fieldName, strpos($fieldName, '.') + 1) : $fieldName;
      if(in_array($realField, $config->search->likeFields))
      {
          $inputStyle  = ($param['operator'] != 'include' and $param['operator'] != 'notinclude') ? "style='display:none'" : '';
          $selectStyle = ($param['operator'] == 'include' or $param['operator'] == 'notinclude') ? "style='display:none'" : '';
          echo html::input($fieldName, '', "class='form-control searchInput' autocomplete='off' $inputStyle");
          echo html::select($fieldName, $param['values'], '', "class='form-control searchSelect chosen $class' $selectStyle");
      }
      else
      {
          if($param['control'] == 'select') echo html::select($fieldName, $param['values'], '', "class='form-control searchSelect $class'");
          if($param['control'] == 'input')  echo html::input($fieldName, '', "class='form-control searchInput' autocomplete='off'");
      }
      echo '</span>';
  }
  ?>
  </div>
  <form method='post' action='<?php echo $this->createLink('search', 'buildQuery');?>' target='hiddenwin' id='searchform'>
    <table class='table table-condensed table-form' style='max-width: 1200px; margin: 0 auto'>
      <tr>
        <td>
          <table class='table active-disabled'>
          <?php
          $formSessionName = $module . 'Form';
          $formSession     = $this->session->$formSessionName;

          $fieldNO = 1;
          for($i = 1; $i <= $groupItems; $i ++)
          {
              $spanClass = $i == 1 ? '' : 'hidden';
              echo "<tr id='searchbox$fieldNO' data-id='$fieldNO' class='search-field $spanClass'>";

              /* Get params of current field. */
              $currentField = $formSession["field$fieldNO"];
              if(!isset($fieldParams[$currentField]))
              {
                  reset($fieldParams);
                  $currentField = key($fieldParams);
                  $formSession["operator{$fieldNO}"] = $fieldParams[$currentField]['operator'];
                  $formSession["value{$fieldNO}"]    = '';
              }
              $param = $fieldParams[$currentField];

              /* Print and or. */
              echo "<td class='w-90px'>";
              if($i == 1) echo "<span id='searchgroup1'><strong>{$lang->search->group1}</strong></span>" . html::hidden("andOr$fieldNO", 'AND');
              if($i > 1)  echo html::select("andOr$fieldNO", $lang->search->andor, $formSession["andOr$fieldNO"], "class='form-control'");
              echo '</td>';

              /* Print field. */
              echo "<td class='w-100px'>" . html::select("field$fieldNO", $searchFields, $formSession["field$fieldNO"], "onchange='setField(this.value, $fieldNO)' class='form-control'") . '</td>';

              /* Print operator. */
              echo "<td class='w-90px'>" . html::select("operator$fieldNO", $lang->search->operators, $formSession["operator$fieldNO"], "class='form-control'") . '</td>';

              /* Print value. */
              echo "<td id='valueBox$fieldNO'>";
              if($param['control'] == 'select')
              {
                  $extraClass    = isset($param['class']) ? $param['class'] : 'chosen';

                  $selectorClass = $currentField == $trader ? 'trader' : '';
                  $selectorClass = (!$selectorClass && $currentField == $contract) ? 'contract' : $selectorClass;
                  $selectorClass = (!$selectorClass && $currentField == $contact)  ? 'contact'  : $selectorClass;
                  $selectorClass = (!$selectorClass && $currentField == $order)    ? 'order'    : $selectorClass;
                  $selectorClass = (!$selectorClass && $currentField == $batch)    ? 'batch'    : $selectorClass;

                  $noResults     = $currentField == $trader ? "data-no_results_text='{$lang->searchMore}'" : '';
                  $noResults     = (!$noResults && $currentField == $contract) ? "data-no_results_text='{$lang->searchMore}'" : $noResults;
                  $noResults     = (!$noResults && $currentField == $contact)  ? "data-no_results_text='{$lang->searchMore}'" : $noResults;
                  $noResults     = (!$noResults && $currentField == $order)    ? "data-no_results_text='{$lang->searchMore}'" : $noResults;
                  $noResults     = (!$noResults && $currentField == $batch)    ? "data-no_results_text='{$lang->searchMore}'" : $noResults;

                  $realField = strpos($formSession["field$fieldNO"], '.') !== false ? substr($formSession["field$fieldNO"], strpos($formSession["field$fieldNO"], '.') + 1) : $formSession["field$fieldNO"];
                  if(in_array($realField, $config->search->likeFields))
                  {
                      echo html::input("value$fieldNO", $formSession["value$fieldNO"], "class='form-control searchInput' autocomplete='off'");
                  }

                  echo html::select("value$fieldNO", $param['values'], $formSession["value$fieldNO"], "data-max_drop_width='300' data-no_wrap='true' class='form-control searchSelect $extraClass $selectorClass' $noResults");
              }
              if($param['control'] == 'input')
              {
                  $fieldName  = $formSession["field$fieldNO"];
                  $fieldValue = $formSession["value$fieldNO"];
                  $extraClass = isset($param['class']) ? $param['class'] : '';

                  if($fieldValue && strpos(',$lastWeek,$thisWeek,$today,$yesterday,$thisMonth,$lastMonth,$thisYear,$lastYear,', ",{$fieldValue},") !== false)
                  {
                      echo html::input("dateValue$fieldNO", '', "class='form-control $extraClass searchInput' placeholder='{$fieldValue}' autocomplete='off'");
                      echo html::hidden("value$fieldNO", $fieldValue);
                  }
                  else
                  {
                      echo html::input("value$fieldNO", $fieldValue, "class='form-control $extraClass searchInput' autocomplete='off'");
                  }
              }
              echo '</td>';

              $fieldNO ++;
              echo '</tr>';
          }
          ?>
          </table>
        </td>
        <td class='w-90px'><?php echo html::select('groupAndOr', $lang->search->andor, $formSession['groupAndOr'], "class='form-control'")?></td>
        <td>
          <table class='table active-disabled'>
          <?php
          for($i = 1; $i <= $groupItems; $i ++)
          {
              $spanClass = $i == 1 ? '' : 'hidden';
              echo "<tr id='searchbox$fieldNO' data-id='$fieldNO' class='search-field $spanClass'>";

              /* Get params of current field. */
              $currentField = $formSession["field$fieldNO"];
              if(!isset($fieldParams[$currentField]))
              {
                  reset($fieldParams);
                  $currentField = key($fieldParams);
                  $formSession["operator{$fieldNO}"] = $fieldParams[$currentField]['operator'];
                  $formSession["value{$fieldNO}"]    = '';
              }
              $param = $fieldParams[$currentField];

              /* Print and or. */
              echo "<td class='w-90px'>";
              if($i == 1) echo "<span id='searchgroup2'><strong>{$lang->search->group2}</strong></span>" . html::hidden("andOr$fieldNO", 'AND');
              if($i > 1)  echo html::select("andOr$fieldNO", $lang->search->andor, $formSession["andOr$fieldNO"], "class='form-control'");
              echo '</td>';

              /* Print field. */
              echo "<td class='w-100px'>" . html::select("field$fieldNO", $searchFields, $formSession["field$fieldNO"], "onchange='setField(this.value, $fieldNO)' class='form-control'") . '</td>';

              /* Print operator. */
              echo "<td class='w-90px'>" .  html::select("operator$fieldNO", $lang->search->operators, $formSession["operator$fieldNO"], "class='form-control'") . '</td>';

              /* Print value. */
              echo "<td id='valueBox$fieldNO'>";
              if($param['control'] == 'select')
              {
                  $extraClass    = isset($param['class']) ? $param['class'] : 'chosen';

                  $selectorClass = $currentField == $trader ? 'trader' : '';
                  $selectorClass = (!$selectorClass && $currentField == $contract) ? 'contract' : $selectorClass;
                  $selectorClass = (!$selectorClass && $currentField == $contact)  ? 'contact'  : $selectorClass;
                  $selectorClass = (!$selectorClass && $currentField == $order)    ? 'order'    : $selectorClass;
                  $selectorClass = (!$selectorClass && $currentField == $batch)    ? 'batch'    : $selectorClass;

                  $noResults     = $currentField == $trader ? "data-no_results_text='{$lang->searchMore}'" : '';
                  $noResults     = (!$noResults && $currentField == $contract) ? "data-no_results_text='{$lang->searchMore}'" : $noResults;
                  $noResults     = (!$noResults && $currentField == $contact)  ? "data-no_results_text='{$lang->searchMore}'" : $noResults;
                  $noResults     = (!$noResults && $currentField == $order)    ? "data-no_results_text='{$lang->searchMore}'" : $noResults;
                  $noResults     = (!$noResults && $currentField == $batch)    ? "data-no_results_text='{$lang->searchMore}'" : $noResults;

                  $realField = strpos($formSession["field$fieldNO"], '.') !== false ? substr($formSession["field$fieldNO"], strpos($formSession["field$fieldNO"], '.') + 1) : $formSession["field$fieldNO"];
                  if(in_array($realField, $config->search->likeFields))
                  {
                      $fieldValue = $formSession["value$fieldNO"];
                      echo html::input("value$fieldNO", $fieldValue, "class='form-control searchInput' autocomplete='off'");
                  }
                  echo html::select("value$fieldNO", $param['values'], $formSession["value$fieldNO"], "data-max_drop_width='300' data-no_wrap='true' class='form-control searchSelect $extraClass $selectorClass' $noResults");
              }

              if($param['control'] == 'input')
              {
                  $fieldName  = $formSession["field$fieldNO"];
                  $fieldValue = $formSession["value$fieldNO"];
                  $extraClass = isset($param['class']) ? $param['class'] : '';
                  if($fieldValue && strpos(',$lastWeek,$thisWeek,$today,$yesterday,$thisMonth,$lastMonth,$thisYear,$lastYear,', ",{$fieldValue},") !== false)
                  {
                      echo html::input("dateValue$fieldNO", '', "class='form-control $extraClass searchInput' placeholder='{$fieldValue}' autocomplete='off'");
                      echo html::hidden("value$fieldNO", $fieldValue);
                  }
                  else
                  {
                      echo html::input("value$fieldNO", $fieldValue, "class='form-control $extraClass searchInput' autocomplete='off'");
                  }
              }
              echo '</td>';

              $fieldNO ++;
              echo '</tr>';
          }
          ?>
          </table>
        </td>
        <td class='w-150px'>
          <?php
          echo html::hidden('module',     $module);
          echo html::hidden('actionURL',  $actionURL);
          echo html::hidden('groupItems', $groupItems);
          echo "<div class='btn-group w-200px'>";
          echo html::submitButton($lang->search->common, 'btn-primary btn', '');
          echo html::commonButton($lang->search->reset, 'btn', 'onclick=resetForm();');
          echo html::commonButton($lang->save, 'btn', 'onclick=saveQuery()');
          echo '</div>';
          ?>
        </td>
        <td class='w-140px'>
          <div class='input-group'>
          <?php
          echo html::select('queryID', $queries, $queryID, 'onchange=executeQuery(this.value) class=form-control');
          if(commonModel::hasPriv('search', 'deleteQuery')) echo "<span class='input-group-btn'>" . html::a('javascript:deleteQuery()', '<i class="icon-remove"></i>', 'class=btn') . '</span>';
          ?>
          </div>
        </td>
      </tr>
    </table>
    <div id='moreOrLite'>
      <a id="searchmore" href="javascript:showmore()"><i class="icon-double-angle-down"></i></a>
      <a id="searchlite" href="javascript:showlite()"><i class="icon-double-angle-up"></i></a>
      <?php echo html::hidden('formType', 'lite');?>
    </div>
  </form>
  <script>
  function initSelect($selector)
  {
      if(v.usePicker && $selector.find('option[value=ajax_search_more]').length == 1)
      {
          $selector.find('option[value=ajax_search_more]').remove();

          var field = $selector.closest('tr').find('[id^=field]').val();
          var url   = createLink('flow', 'ajaxGetPairs', 'module=' + module + '&field=' + field + '&options=&search={search}');

          var options = {disableEmptySearch: true, maxListCount: 0, searchDelay: 500, remote: url};
          initPicker($selector, {remote: url});
      }
      else
      {
          $selector.addClass('chosen').chosen();
      }
  }

  $('#searchform select[id^=value]').each(function()
  {
      initSelect($(this));
  });
  $('#searchform .trader').each(function()
  {
      $(this).next('.chosen-container').addClass('trader_chosen');
  });
  $('#searchform .contract').each(function()
  {
      $(this).next('.chosen-container').addClass('contract_chosen');
  });
  $('#searchform .contact').each(function()
  {
      $(this).next('.chosen-container').addClass('contact_chosen');
  });
  $('#searchform .order').each(function()
  {
      $(this).next('.chosen-container').addClass('order_chosen');
  });
  $('#searchform .batch').each(function()
  {
      $(this).next('.chosen-container').addClass('batch_chosen');
  });

  $('#searchform .input-group,#searchform .btn-group').fixInputGroup();

  $('[name*=operator]').change();
  var showMode = $.zui.store.pageGet('showMode');
  if(showMode == 'more')
  {
      showmore();
  }
  else if(showMode == 'lite')
  {
      showlite();
  }
  else
  {
      <?php if(isset($formSession['formType'])) echo "show{$formSession['formType']}();";?>
  }
  </script>
  <iframe id='hiddenwin' name='hiddenwin' class='hidden'></iframe>
</div>
