$(function()
 {
  /*---------------------------------------------------------------------------------------*/
  /*---------------------------------------------------------------------------------------*/
  // Для отображения списка городов
   $('.towncontent').hide();
   $('.townbox').html(   $('.towncontent').html()  );
   $('.towncontent').html('');
  /*---------------------------------------------------------------------------------------*/
  /*---------------------------------------------------------------------------------------*/
  // Для поиска города
  function wordend(cnt)
   {
    if(cnt > 10 && cnt <= 20 ) return 'городов';
    cnt = cnt%10;
    if(cnt == 0 ) return 'городов';
    if(cnt <=1 ) return 'город';
    if(cnt > 1 && cnt <= 4 ) return 'города';
    if(cnt > 4 && cnt <= 9 ) return 'городов';
   }
  /*---------------------------------------------------------------------------------------*/
  $.fn.extend({
    SearchTown: function(str)
     {
      return this.each(function()
                  {
                   var thist = $(this).text().toLowerCase();
                   //str = $.trim( str ).toLowerCase();
                   if( thist.indexOf(str)<0 )
                      {
                       $(this).hide();
                      }
                   else
                      {
                       if(str.length>0 && thist.indexOf(str)<2)
                          $(this).show();
                       else
                       if(str.length>0)
                          $(this).hide();
                       if(0==str.length)
                          $(this).show();
                      }
                  });
     }
  });
  /*---------------------------------------------------------------------------------------*/
  var gorCapt = new Array();
  var gorObj = new Array();
  var tmpind=0;
  $(".townlink").each(function()
        {
         gorCapt[tmpind] = $(this).text().toLowerCase();
         gorObj[tmpind]  = $(this);
         tmpind++;
        });
  //alert(gorCapt.join(" | "));
  //alert(gorObj.join(" # "));

  $.fn.extend({
    SearchTown1Beta: function(str)
     {
      var GorSize = gorCapt.length;
      var StrIndex = 0;
      var FirstLtr = 2;
      if($.browser.msie) FirstLtr = 1;

      for(i=0;i<GorSize;i++)
                  {
                   StrIndex = gorCapt[i].indexOf(str);
                   if( StrIndex < 0 )
                      {
                       gorObj[i].hide();
                      }
                   else
                      {
                       if(str.length>0 && StrIndex < FirstLtr)
                          gorObj[i].show();
                       else
                       if(str.length>0)
                          gorObj[i].hide();
                       if(0==str.length)
                          gorObj[i].show();
                      }
                  }
     }
  });
  /*---------------------------------------------------------------------------------------*/
  // кешируем объекты
  var Obj_townlink = $(".townlink");
  var Obj_search_town_text = $('#search_town_text');
  var Obj_div_towncount = $('div#towncount')

  $('#search_town_text').change( function()
    {
     var str =  $.trim(  Obj_search_town_text.val().toLowerCase() );
     Obj_townlink.SearchTown1Beta( str );

     var towncount = $('.townlink:visible').size();
     var title1 = 'Найдено ' + towncount + ' ' + wordend(towncount) + ' похожих на '+str;
     //$('#search_town_text').attr('title',title1);
     $(this).attr('title',title1);

     if(0==towncount)
       Obj_div_towncount.html( 'Города начинающегося на <b>'+str+'</b> не найдено' ).show();
     else
       Obj_div_towncount.hide();
/*
     if(str.length > 0)
       $('.townlink:visible:first').focus();
     else
       $(this).focus();
*/

    });

  $('#search_town_text').keydown ( function() { $(this).change(); } );
  $('#search_town_text').keyup   ( function() { $(this).change(); } );
  $('#search_town_text').keypress( function() { $(this).change(); } );
  /*---------------------------------------------------------------------------------------*/
  //$(".townlink").SearchTown( $.trim(  $('#search_town_text').val().toLowerCase() ) );
  $('#search_town_text').change();
  /*---------------------------------------------------------------------------------------*/
   $("#search_town_text").focus( function()
          {
           $(this).addClass('search_town_textsel');
          });
   $("#search_town_text").blur( function()
          {
           $(this).removeClass('search_town_textsel');
          });
  /*---------------------------------------------------------------------------------------*/
  /*---------------------------------------------------------------------------------------*/
  // Для отображения списка городов
   $('div#showtown a').text('выбрать город');
   $('div#showtown a').click( function() {
           //$('.townbox').toggle();
           if('none' == $('.townbox').css('display') )
               {
                $('.townbox').show();
                $('#search_town_text').focus();
               }
           else
               $('.townbox').fadeOut('slow');


           return false;
         });

   $('a#closetownlist').click( function() {
           $('.townbox').fadeOut(
                         function()
                           {
                            $('#search_town_text').val('');
                            $('#search_town_text').change();
                           });
           return false;
         });

   $('.townlink').click( function() {
           $('.townbox').fadeOut('fast');
         });
  /*---------------------------------------------------------------------------------------*/
   $('.hidelogo').click( function() {
           if('cars' == $('#cars').attr('class') )
             {
              $(this).text('показать логотипы');
              $('#cars').removeClass('cars');
              $('#cars').addClass('auto');
             }
           else
             {
              $(this).text('убрать логотипы');
              $('#cars').removeClass('auto');
              $('#cars').addClass('cars');
             }
           return false;
         });
  /*---------------------------------------------------------------------------------------*/
  /*---------------------------------------------------------------------------------------*/
   /*просмотр изображений в объявлениях*/
   $('.closeimg').click( function() {
     $('.showimgbox').slideUp("slow",function()
        {
         $('#bigimg').removeAttr('src').hide();
         $('.prvimg').removeAttr('src').hide();
         $('.prvimgsel').removeAttr('src').hide();
        });
    });
   //------------------------------
   //$("#bigimg").load( function() { $(this).fadeIn("slow"); $('#imgboxpre').hide(); } );
   $("#bigimg").load( function() { $(this).fadeIn("slow",function(){ $('#imgboxpre').hide(); }); });

   //------------------------------
   $('img[imgbox]').click( function() {
          $('.prvimg').hide();
          var imgbox = $(this).attr('imgbox');
          var curimg = $(this).attr('curimg');
          var srcdir = $('.showimgbox').attr('srcdir');
          var imgbpref = $('.showimgbox').attr('imgbpref');
          var imgarr=imgbox.split(";");
          var imgsrc = '';
          var imgclass = ''

          for(i=0; i< imgarr.length; i++)
             {
              imgclass = 'prvimg';
              if(curimg == imgarr[i]) imgclass = 'prvimgsel';
              $('img[preimg='+i+']').attr('class',imgclass).attr('src',srcdir+imgarr[i]+'.jpg').attr('curimg',imgarr[i]).show();
             }
          $('#imgboxpre').css('opacity',0.7);
          $('.imgboxpre').show();
          $('.showimgbox').show();
          //alert(document.documentElement.scrollTop);
          if(document.getElementById('showimgbox').scrollTop)
             document.getElementById('showimgbox').scrollTop = 0;




          $('#bigimg').attr('src',srcdir+imgbpref+curimg+'.jpg');
          return false;
         });
   //------------------------------
   $('img[class=prvimg]').click( function() {
            if('prvimgsel'==$(this).attr('class')) return false;
            var prvimgsel = $('.prvimgsel')
            prvimgsel.removeClass('prvimgsel');
            prvimgsel.addClass('prvimg');
            $(this).removeClass('prvimg');
            $(this).addClass('prvimgsel');

            var curimg = $(this).attr('curimg');
            var srcdir = $('.showimgbox').attr('srcdir');
            var imgbpref = $('.showimgbox').attr('imgbpref');

            $('#bigimg').fadeOut("slow",function(){
                         $('.imgboxpre').show();
                         $('#bigimg').attr('src',srcdir+imgbpref+curimg+'.jpg');
                        });

        });
  /*---------------------------------------------------------------------------------------*/
  /*---------------------------------------------------------------------------------------*/
  // Перехват ESC
  var code;
  function getESC(KeyPressed)
    {
     if (!KeyPressed) KeyPressed = window.event;
     if (KeyPressed.keyCode) code = KeyPressed.keyCode;
     else if (KeyPressed.which) code = KeyPressed.which;

     var AltPressed = false;
     if(KeyPressed.altKey) AltPressed = KeyPressed.altKey;
     //alert(AltPressed)


     if(27 == code)
       {
        $('*[esc]').click();
        $('.closeimg').click();
       }
     if(AltPressed)
     if(84 == code)
       {
        //$('div#showtown a').text();
        $('div#showtown a').click();
       }

     //$('div#showtown a').text(code);
    }
  function townKey(KeyPressed)
    {
     if (!KeyPressed) KeyPressed = window.event;
     if (KeyPressed.keyCode) code = KeyPressed.keyCode;
     else if (KeyPressed.which) code = KeyPressed.which;

     //$('div#showtown a').text(code);
     if(40 == code) // вниз
       {
        var next = $(this).next('.townlink:visible');
        //alert($('.townlink:visible').next('.townlink:visible').text() + ' l=' + next.text().length + ' sz=' + next.size());

        if($(this).is('input'))
           {
            $('.townlink:visible:first').focus();
            return false;
           }
        if(0 < next.text().length)
           next.focus();

        return false;
       }
     if(38 == code) // вверх
       {
        if(0 < $(this).prev('.townlink:visible').text().length)
           $(this).prev('.townlink:visible').focus();
        else
           $('#search_town_text').focus();

        return false;
       }
     if($(this).is('a.townlink'))
       {
        if(36 == code) // home
          {
           $('.townlink:visible:first').focus();
           return false;
          }
        if(35 == code) // end
           {
            $('.townlink:visible:last').focus();
            return false;
           }

        var pKey = String.fromCharCode(code).toLowerCase();
        if('а' <= pKey && pKey  <='я' || 32 == code || 45 == code)
           {
            //$('.townhead b').text(code+ ' : ' + pKey+ ' ок');
            $('#search_town_text').val( $('#search_town_text').val()+pKey );
            $('#search_town_text').change();
            if(!$(this).is('.townlink:visible')) $('#search_town_text').focus();

            return false;
           }
        if(8 == code)
           {
            var str = $('#search_town_text').val();
            $('#search_town_text').val( str.substring(0,str.length-1) );
            $('#search_town_text').change();
            if(!$(this).is('.townlink:visible')) $('#search_town_text').focus();

            return false;
           }
/*
        if(32 == code)
           {
            $('#search_town_text').val( $('#search_town_text').val()+' ');
            $('#search_town_text').change();
            $('#search_town_text').focus();

            return false;
           }
*/
       }

/*
     if($(this).is('input'))
       {
        $(this).change();

        $(this).keydown(function() {
         $('.townhead b').text(code+ ' : ' + pKey+ ' ||'+$(this).val()  );
         });


        var pKey = String.fromCharCode(code).toLowerCase();
        if('а' <= pKey && pKey  <='я' || 32 == code)
           {
            var l = ($('#search_town_text').val().length+1);
            $('.townhead b').text(code+ ' : ' + pKey+ ' input и l='+l  );

            if( ($('#search_town_text').val().length+1) > 0 )
               {
                $('#search_town_text').change();
                $('.townlink:visible:first').focus();
               }
            else
               $(this).focus();
           }
       }
*/

    }

    document.onkeydown=getESC;
  /*---------------------------------------------------------------------------------------*/
  // перехват фокуса для списка городов
  $('.townlink').keypress(townKey );
  $('#search_town_text').keypress(townKey );
  /*---------------------------------------------------------------------------------------*/
   $('#show_rubr_filter').click( function() {
         //if('filterdn'==$(this).attr('class'))
         var rubrfilter = $('#rubrfilter');
         if('none'==rubrfilter.css('display'))
           {
            rubrfilter.show();
            $(this).removeClass('filterdn');
            $(this).addClass('filterup');
            $(this).text('Спрятать фильтр авто объявлений');
           }
         else
           {
            var thisI = $(this);
            rubrfilter.slideUp('slow', function() {
              thisI.removeClass('filterup');
              thisI.addClass('filterdn');
              thisI.text('Настроить вид авто объявлений');
             });

           }
         return false;
        });
  /*---------------------------------------------------------------------------------------*/
  /*---------------------------------------------------------------------------------------*/
  // Для странички с объявлением
    $('.svetofor').hover(function(){
      var sv = $(this).attr('sv');
      $(this).removeClass('sv'+sv);
      $(this).addClass('svb'+sv);
    },function(){
      var sv = $(this).attr('sv');
      $(this).removeClass('svb'+sv);
      $(this).addClass('sv'+sv);
    });
  /*---------------------------------------------------------------------------------------*/
   $('#sendpm').click( function() {
         $('#sendpmform').toggle();
         return false;
        });
   $('#closesendpm').click( function() {
         $('#sendpmform').slideUp();
         return false;
        });
  /*---------------------------------------------------------------------------------------*/
  /*---------------------------------------------------------------------------------------*/
/*
  $('input[type=submit]').click(function(){
   //alert(  $(this).attr('name')  );
   //alert(  $(this).parents('form').attr('name') );
   $(this).parents('form').append('<input name="'+ $(this).attr('name') +'" type="hidden" value="1" />');
   $(this).attr('disabled',1);
  });
*/
  /*---------------------------------------------------------------------------------------*/
  $('#hdsearch').focus( function() {
     var ThisObj = $(this);
     if('Поиск по сайту'==ThisObj.val())
       ThisObj.val('');
  });
  $('#hdsearch').blur( function() {
     var ThisObj = $(this);
     if(''==ThisObj.val())
       ThisObj.val('Поиск по сайту');
  });
  $('form[name=hsearch]').submit( function() {
     var st = $('#hdsearch').val();
     if( ''==st || 'Поиск по сайту'==st )
        {
         $('#hdsearch').focus();
         return false;
        }
  });

  /*---------------------------------------------------------------------------------------*/
 });
