  var global_length = 0;

  function basket_status_update() {
      $('#basket_caption').html(' обновляется...');
  }
  function basket_refresh() {
    var timestamp = Number(new Date());
    basket_status_update();
    $.get('/basket/count/'+timestamp,{},
        function(ret){
            $('#basket_caption').html(ret);
            if (ret == '0') {$('.kro').hide();}
            else $('.kro').show();
        }
    );
  }

  basket_recalculate = function (){
      $('#basket_price_all').html(0);
      global_length = $('#basket_form').find('input[name="basket_item_count[]"]').length;
      $('#basket_form').find('input[name="basket_item_count[]"]').each(function(index){
          var id = $(this).parent().parent().attr('id');id = id.substr(2,id.length-2);
	        var price = $('#card_'+id+' .item_list ul.selected li.item_price').text()*1.0;
	        var cnt = $(this).val();
	        var sum = Math.round(cnt*price*100)/100;
	        if (isNaN(sum)) sum=0;
	        var sum = Math.round(($('#basket_price_all').html()*1.0+sum)*100)/100;
	        if (isNaN(sum)) sum = 0;
	        $('#basket_price_all').html(sum);
	        $('#basket_price_all_field').html(sum);
	        if (index==global_length-1) {basket_refresh();}
      });

      return false;
  }

  basket_weight_change = function() {
    var item = $('#item_'+$(this).val());
    var num_card = $('.id_basket',item.parent().parent()).text();
    $('ul',item.parent()).removeClass('selected');
    item.addClass('selected');
    var price = $('.item_price',item).text();
    $('.basket_item_title',$(this).parent().parent()).html($('.item_title',item).text()+'<br />Цена: '+$('.item_price',item).text()+' руб.');
    return false;
  }

  function tobasket(id_card,id_item) {
    basket_status_update();
    $.post('/basket/add/'+id_card+'/'+id_item+'/',function(ret){
      if (ret=='0') {
          basket_refresh();
	        $('.kro').attr('display','block');
	        alert('Товар добавлен в корзину.');
      }else{
	;
      }
    });
    return false;
  }

  function basket_bind(){
      $('#basket_error').hide();

      $('#basket_refresh_captcha').click(function(){
          $('#basket_cap_img').html('');
          $.post('/basket/refresh/',{},function(ret){$('#basket_cap_img').html(ret);});
          return false;
      });

      $('.korzina').find('.btn_ok').click(function(){
          $('#basket_form').submit();
          return false;
      });

      $('#basket_form').submit(function(){
	        $('.reg_state0').hide();
	        $('.reg_state1').html('Идет отправка формы, подождите').show();
	        $.fancybox.resize();
          $.post('/basket/submit/',$('#basket_form').serialize(),function(ret){
	            switch (ret.status) {
		              case '0':
		                  $('#basket_error').hide();
		                  $('.reg_state0').hide();
		                  $('.reg_state1').html('<p>Ваше сообщение успешно отправлено.</p>').show();
		                  break;
		              case '1':
		                  $('#basket_error').html(ret.err).show();
		                  $('.reg_state1').hide();
		                  $('.reg_state0').show();
		                  break;
	            }
	            $.fancybox.resize();
	        },'json');
          return false;
      });

      $('a.del',$('#basket_container')).click(function(){
          var id = $(this).attr('href');
	        id = id.substr(1,id.length-1)*1;
          $.post('/basket/del/'+(id+1),{},function(ret){
	            $('#bi'+ret).remove();
	            basket_recalculate();
	            basket_refresh();
	            $.fancybox.resize();
          });
          return false;
      });

      $('a.del_all',$('#basket_container')).click(function(){
  	      if (!confirm('Удалить всё из корзины?')) return false;
          $.post('/basket/del/',{},function(ret){
              $('#basket_form').remove();
	            basket_refresh();
	            $('#basket_error').html('В корзине ничего нет. Выберите какой-либо товар и нажмите ссылку "Заказать".').show();
	            $.fancybox.resize();
          });
          return false;
      });

      $('#basket_form').find('input[name="basket_item_count[]"]').change(basket_recalculate);
      $('#basket_form').find('select[name="basket_item_id[]"]').change(basket_weight_change);
      basket_recalculate();
      $.fancybox.resize();
  }

$(document).ready(function()
{
  basket_refresh();

    $("div.top_menu a, div.top_menu span").png_link();
  /* --- select_city ---*/

  var city_hover = false;

  $('div.select_city').hide();

  $('a.city').click(function(){
      if ( $('div.select_city').is(':hidden') ){
          $('div.select_city').slideDown(400);
      } else {
          $('div.select_city').slideUp(400);
      }
      return false;
	}).hover(
      function () {
        city_hover = true;
      },
      function () {
        city_hover = false;
      }
    );;

	$(document).click(function(){
    if(!city_hover)
      $('div.select_city').slideUp(400);
  });

//  $('div.select_city a').click(function(){
//	    var st = $(this).text();
//	    var val = $(this).attr('href');
//	    val = val.substr(1,val.length-1);
//
//	    if (val == "all"){
//          st = "выбери город";
//          val = null;
//      }
//
//      $('a.city').html(st);
//      $('div.select_city').slideUp(400);
//
//      $.cookies.set("city_select", val);
//      document.location.reload();
//      return false;
//	});

	//$("div.main_r img").pngFix();

  /* --- end select_city ---*/

  /* -- mailto -- */

// Обратная связь
  function fos_bind(){
    $('#sendmail_cap_refresh').click(function(){
      $('#sendmail_cap_img').html('');
      $.post('/feedback/refresh/',{},function(ret){$('#sendmail_cap_img').html(ret);});
      return false;
    });
  }
  var sendmail_busy = false;
      fos_default_content = $('#fos').html();

  function sendmail_fos(){
    if(sendmail_busy) return false;
    sendmail_busy = true;
    var ser = $('#form_fos').serialize();
    $('#fos').html('<h2>Идёт отправка сообщения ...</h2>');
    $.fancybox.resize();
    $.post('/feedback/',ser,function(ret){
            $('#fos').html(ret);
            if($('#form_fos').serialize()===''){$('.btn_ok').hide();$('.btn_otmena').hide();alert('Ваше сообщение отправлено.\nМы свяжемся с вами в ближайшее время.');$.fancybox.close();$('#fos').html(fos_default_content);return false;}
            sendmail_busy = false;
            on_mailto_open();
            $.fancybox.resize();
    });
  }

  on_mailto_open = function()
  {
          $('#sendmail_wait').hide();
          $('#fos').find('.btn_ok').click(function(){
            $('#form_fos').submit();
            return false;
          });
          fos_bind();

          $('#form_fos').submit(function(){
            sendmail_fos();
            return false;
          });
          $.fancybox.resize();

  }

  $("p.mailto_open a").fancybox({
      autoScale: false,
      scrolling: 'visible',
      type: 'ajax',
      padding: 45,
      onComplete: on_mailto_open
  });



  on_korzina_open = function()
  {
      $('#basket_error').hide();
      basket_bind();
  }

  on_korzina_close = function()
  {
     if ($('#basket_form')[0] == undefined) return true;
     $.post('/basket/save/',$('#basket_form').serialize(),function(){basket_refresh();});
     return true;
  }

  $("a.korzina_open").fancybox({
      autoScale: false,
      scrolling: 'visible',
      type: 'ajax',
      padding: 45,
      onComplete: on_korzina_open,
      onCleanup: on_korzina_close
  });

  $("a.btn_otmena").live('click', function(){
      $.fancybox.close();
      return false;
  });

  /* -- end mailto -- */

  $("a.gal").fancybox();

  $("#lightbox-nav").hide();

})


