  $(document).ready(function() {

    $('#search_form input, #search_form select').change(function(){
      if ($(this).attr('name') == 'order') return;
      get_results();
    });

    $('#search_form input[type=checkbox]').live('click', function(){
      get_results();
    });

    $('#add_row a').click(function(){
      add_row();
    });


    $('#search_form').submit(function(){
      document.location.href = '/stock.php?' + makeUrl();
      return false;
    });


    $('#sales_search_full_link a').click(function(){
      drawFullSearch();
    });


    $('#search-field-cnt').click(function(){
      $('#cnt_list').toggle();
      if (!$('#cnt_list').is(':visible')) {
        setCountries();
      };
      return false;
    });

    $('body').click(function(e){
      if (!$('#cnt_list').is(':visible')) {
        return;
      }
      if ($(e.target).parents('#cnt_list').length == 0) {
        $('#search-field-cnt').click();
      }

    });

    selectCountries();
    setCountriesFromHidden();

  });


  var searchFieldCntAll = $('#search-field-cnt').text();

  function setCountriesFromHidden() {
    if ($('#search_field_cnt').val() == '') return;

    var cnts = $('#search_field_cnt').val().split(';');
    if (cnts.length > 0) {
      for (var i = 0; i < cnts.length; i++) {
        $('#cnt_list input[value=' + cnts[i] + ']').attr('checked', 'checked');
      }
    }
    setCountries();
  }

  function setCountries() {
      var countries = { 'vals': [], 'titles': [] };
      var checked = $('#cnt_list input:checked');
      if (checked.length > 0) {
        $.each(checked, function(){
          countries['vals'].push($(this).val());
          countries['titles'].push($(this).parent().text());
        });
      }
      if (countries.vals.length > 0) {
        $('#search_field_cnt').removeClass('sf-def-option');
        $('#search_field_cnt').val(countries.vals.join(';'));
        var text = countries.titles.join(',');
      } else {
        $('#search_field_cnt').addClass('sf-def-option');
        $('#search_field_cnt').val('');
        var text = searchFieldCntAll;
      }
      $('#search-field-cnt').attr('title', text);
      $('#search-field-cnt').text(text);
      get_results();
  }


  function selectCountries() {
    var tks = new Array();
    if ($('#search_form [name=tk]').length > 0) {
      $.each($('#search_form [name=tk]'), function(){
        tks.push($(this).val());
      })

      if (tks.length > 0) {
        $.ajax({
          type: 'GET',
          url: '/ajax/search_cnts.php',
          data: {cat: $('[name=cat]').val(), tks: tks.join(',')},
          dataType: 'json',
          success: function(data){
            if (data) {
              var selected = new Array();
              $.each($('#cnt_list [type=checkbox]:checked'), function(){
                selected.push($(this).val());
              })
              $('#cnt_list').html('');
              for(var i in data) {
                $('#cnt_list').append('<div><input type="checkbox" style="width: auto;" value="' + i + '" id="opts_cnt_' + i + '" /> <label for="opts_cnt_' + i + '">' + data[i] + '</label></div>');
              }
              for(var i in selected) {
                $('#opts_cnt_' + selected[i]).attr('checked', 'checked');
              }
              setCountries();
              var height = $('#cnt_list [type=checkbox]').length * 20;
              if (height > 250) {
                height = 250;
              }
              //alert($('#cnt_list [type=checkbox]').length + ', ' + height);
              $('#cnt_list').height(height + 10);
            }
          }
        });
      }
    }
  }


  $('#search_form').ready(function(){
    get_results();
    $.each($('#search_form .glob_row'), function(){
      selectMarks($(this));
    });
    setSelectedVals();
  });

  $('[name=tk]').change(function(){
    selectCountries();
    selectMarks($(this).parents('.glob_row'));
    var i = 0;
    $.each($('[name=tk]'), function(){
      if (i++ == 0) return;
      assignCatTypes($(this));
    });
  });

  $('[name=spare]').change(function(){
    selectCountries();
    selectMarks($('[name=tk]').parents('.glob_row'));
  });


  $('#sort').click(function(){
    var sorted = $('[name=sort]');
    if (sorted.val() == 'down') {
      $(this).children().attr('src', 'http://images.autoline.com.ua/icons/search/asc_enable.gif');
      $('[name=sort]').val('up');
    } else {
      $(this).children().attr('src', 'http://images.autoline.com.ua/icons/search/desc_enable.gif');
      $('[name=sort]').val('down');
    }
  });


  function selectMarks(row) {
    var tk = row.find('[name=tk]');
    if (tk.length > 0) {
      var tm_selected = row.find('[name=tm] :selected');
      var tm_selected_val = tm_selected.val();
      var tm_selected_title = tm_selected.text();
      var marks_query_data = { cat: $('[name=cat]').val(), tk: tk.val() };
      if ($('#search_form select[name=spare]').length>0) {
        marks_query_data.spare = $('#search_form select[name=spare]').val();
      }
      $.ajax({
        url: '/ajax/search_marks.php',
        type: 'get',
        data: marks_query_data,
        dataType: 'json',
        success: function(data){
          if (data.length <= 0) {
            return false;
          }
          var tm = row.find('[name=tm]');
          if (tm.length > 0) {
            var js_tm = tm.get(0);
            var i, j, opts;
            js_tm.length = 1;

            for (i in data) {
              if (data[i].block_code!=undefined) {
                if (data.length > 1 && data[i].title) {
                  tm.append('<option value="all_' + data[i].block_code + '" style="background: #ddd;">' + data[i].title + '</option>');
                }
                if (data[i].opts.length > 0) {
                  for (j in data[i].opts) {
                    tm.append('<option value="' + data[i].opts[j].value + '">&nbsp;&nbsp;' + data[i].opts[j].title + '</option>');
                  }
                }
              } else {
                tm.append('<option value="' + data[i].value + '">&nbsp;&nbsp;' + data[i].title + '</option>');
              }
            }
          }
          if (tm_selected) {
            tm.val(tm_selected_val);
            if (tm_selected_val !== tm.val()) {
              tm.append('<option value="' + tm_selected_val + '">' + tm_selected_title + '</option>');
              tm.val(tm_selected_val);
            }
          }
        }
      });
    }
  }


  /*
  row - jQuery object
  vals = { tm, model, tk }
  */
  function set_row_vals(row, vals) {
    $.each(vals, function(field, val){
      row.find(':input[name=' + field + ']').val(val);
    })
    if ($('[name=tm]').length > 1) {
      calcRowResults(row.find(':input:first'));
    }
  }

  $('.row_del').live('click', function(){
    $(this).parent().remove();
    if (undefined != document.setTypeBlocks) {
      setTypeBlocks();
    }
    get_results();
    var other_dels = $('.row_del');
    if (other_dels.length == 1) {
      other_dels.remove();
      $('.row_res').remove();
    }
    if (other_dels.length <= 2) {
      $('#add_row span').hide();
      $('#add_row a').show();
      $('#add_row').removeClass('grey').addClass('blue');
    }
  });

  function add_row() {
    var mark_rows = $('.row_del').length;
    if (mark_rows >= 3) {
      return false;
    } else if (mark_rows == 2) {
      $('#add_row a').hide();
      if ($('#add_row span').length) {
        $('#add_row span').show();
      } else {
        $('#add_row').append('<span class="grey u">' + $('#add_row a').text() + '</span>');
      }
      $('#add_row').removeClass('blue').addClass('grey');
    } else {
      if (mark_rows == 0) {
        if ($($('#add_row').parent().find('.glob_row:first .row_res')).length > 0) {
          $('<a href="javascript:void(0);" title="' + strs.del + '" class="row_del"><img src="http://images.autoline.com.ua/icons/del_border.png" /></a>')
            .insertBefore($('#add_row').parent().find('.glob_row:first .row_res'));
        } else {
          calcRowResults($('#add_row').parent().find('select:first'));
          $('<a href="javascript:void(0);" title="' + strs.del + '" class="row_del"><img src="http://images.autoline.com.ua/icons/del_border.png" /></a>')
            .appendTo($('#add_row').parent().find('.glob_row:first'));
        }
      }
    }

    var new_row = $('#add_row').parent().find('.glob_row:first').clone(true);
    new_row.find('.row_res').text('').end().find(':input').val('').end().insertBefore('#add_row')
      .find(':input').change(function(){
        calcRowResults($(this));
    });

    if (mark_rows == 0 && $('#add_row').parent().find('.glob_row:first [name=tk]').length > 0) {
      assignCatTypes(new_row.find('[name=tk]'));
    }

    selectCountries();

    return new_row;
  }


  function assignCatTypes(tk_field) {
    var selected_cat = $('[name=tk]:first :selected').attr('className').substr(4);
    if (!selected_cat) {
      selected_cat = $('[name=tk]:first :selected').next().attr('className').substr(4);
    }
    var cur_block = { obj: null, used: false };
    var selected_type = tk_field.val();

    tk_field.get(0).length = 0;
    $.each($('[name=tk]:first option'), function(){
      if (!$(this).attr('value')) {
        tk_field.append($(this).clone().attr('selected', false));
        return;
      }
      if (!$(this).attr('className')) {
        if (cur_block.obj !== null && !cur_block.used) {
          cur_block.obj.remove();
        }
        cur_block.obj = $(this).clone().attr('selected', false);
        cur_block.used = false;
        tk_field.append(cur_block.obj);
      } else {
        if ($(this).attr('className') == 'cat_' + selected_cat) {
          tk_field.append($(this).clone().attr('selected', false));
          cur_block.used = true;
        }
      }
    });
    if (cur_block.obj !== null && !cur_block.used) {
      cur_block.obj.remove();
    }

    tk_field.val(selected_type);
  }


  function drawFullSearch() {
    $('#sales_search_full').toggle();
    $('#sales_search_full_link').toggleClass('down_arrows').toggleClass('up_arrows');
    $('#sales_search_full_link a').text($('#sales_search_full:hidden').length ? strs.full_search : strs.short_search);
    if ($('#sales_search_full:hidden').length > 0) {
      setSelectedVals();
    } else {
      $('#selected_vals').hide();
    }

  }

  function setSelectedVals() {
    $('#selected_vals').html('<div></div>');
    $.each($('#sales_search_full select,#sales_search_full input[type=checkbox]:checked'), function(){
      if ($(this).attr('name') == 'order' || $(this).attr('name') == 'on_page') {
        return;
      }

      if ($(this).val().length > 0) {

        var title = '', before = '', val = '', after = '';

        if ($(this).attr('type') == 'checkbox') {

          if ($(this).attr('id') == 'o_trailer') {
            title = $(this).parent().parent().find('label').text();
          } else {
            title = $(this).parent().find('label').text();
          }
        } else {
          var first_opt = $(this).find('option:first');
          before = first_opt.text().search(strs.from + '|' + strs.till) >= 0 ? first_opt.text() + ' ' : before;
          before = ($(this).find('option:selected').text().search(strs.more) >= 0 ? '' : before);
          val = $(this).find('option:selected').text();

          title = (first_opt.text() == strs.till && $('[name=' + $(this).attr('name').replace(/1/, '0') + ']').val() ? '' : $(this).parent().parent().find('.f_title').text());

          after = $(this).parent().find('span').text();

        }

        var val_name = $(this).attr('name');

        $('<span></span>')
          .append(title + before + ' ' + val + after)
          .append($('<a href="javascript:void(0);" title="' + strs.del + '"><img src="http://images.autoline.com.ua/icons/del.png" /></a>')
            .click(function(){
              $('select[name=' + val_name + ']').val('');
              $('input[type=checkbox][name=' + val_name + ']').attr('checked', false);
              $('#search_form').submit();
            }))
          .appendTo('#selected_vals div');

      }
    });
    if ($('#selected_vals div').text().length > 0) {
      //$('#selected_vals').append();
      $('#selected_vals').prepend(strs.dop + ':<br />');
      $('<a href="javascript:void(0)" id="clear_parameters">' + strs.clear_parameters + '</a>')
        .click(function(){
          document.location.href = '/stock.php?' + makeUrl('#search_short');
        })
        .prependTo('#selected_vals');
      $('#selected_vals').show();
    }
  }

  event_date = null;

  function get_results() {
    if ($('[name=tm]').length > 1) {
      $.each($('[name=tm]'), function(){
        calcRowResults($(this));
      })
    }

    $.ajax({
      url: '/ajax/search.php?' +  makeUrl(),
      type: 'GET',
      dataType: 'json',
      success: function(data) {
        $('#results,.results').html(strs.found + ': ' + data.result);
      }
    });
  }

  function calcRowResults(obj) {
    var row = obj.parent().parent().parent();

    if (row.find('[name=tm]').val() == '' && row.find('[name=model]').val() == '' && row.find('[name=tk]').val() == '') {
      row.find('.row_res').text('');
      return;
    }

    if (row.find('[name=tk] :selected').length > 0) {
      var row_cat = row.find('[name=tk] :selected').attr('className').substr(4);
      if (!row_cat) {
        row_cat = $('[name=cat]');
      }
    }

    var url = makeUrl().replace(/tm=[^&]+/, 'tm=' + row.find('[name=tm]').val()).replace(/tk=[^&]+/, 'tk=' + row.find('[name=tk]').val()).replace(/model=[^&]+/, 'model=' + row.find('[name=model]').val());

    $.ajax({
      url: '/ajax/search.php?' + url,
      type: 'GET',
      dataType: 'json',
      success: function(data) {
        if (row.find('.row_res').length == 0) {
          row.append('<span class="row_res"></span>');
        }
        row.find('.row_res').text('(' + data.result + ')');
        //$('#results,.results').html(strs.found + ': ' + data.result);
      }
    });

  }

  function makeUrl(region) {
      if (region !== undefined) {
        var form = $(region);
      } else {
        var form = $('#search_form');
      }

      var spec = {tm: new Array(), tk: new Array(), model: new Array()};
      var url = '';

      $.each(form.find('input,select'), function(){
        if ($(this).attr('name') == '') return;

        if ($(this).attr('name') == 'tm') {
          spec.tm.push($(this).val());
          return true;
        }
        if ($(this).attr('name') == 'tk') {
          spec.tk.push($(this).val());
          return true;
        }
        if ($(this).attr('name') == 'model') {
          spec.model.push($(this).val());
          return true;
        }
        if ($(this).attr('type') != 'checkbox' && $(this).val() != '' && $(this).attr('name') != '') {
          url += $(this).attr('name') + '=' + $(this).val() + '&';
        } else if ($(this).attr('type') == 'checkbox' && $(this).is(':checked')) {
          url += $(this).attr('name') + '=1&';
        }
      });

      if (spec.tm.length > 0) {
        url += 'tm=' + spec.tm.join(';') + '&';
      }
      if (spec.tk.length > 0) {
        url += 'tk=' + spec.tk.join(';') + '&';
      }
      if (spec.model.length > 0) {
        url += 'model=' + spec.model.join(';') + '&';
      }

      return url;
  }