/** Инициализируем анимированный счетчик товаров на отгрузке в шапке */
function initCounter(day, counterInc, counterStart, counterEnd, counterSpeed) {
    var cookieName;
    if (day == 'saturday')      { cookieName = 'startCounterSaturday'; }
    else if (day == 'sunday')   { cookieName = 'startCounterSunday'; }
    else                        { cookieName = 'startCounter'; }
    
    var updateTime = 1000;
    var setCounter = function () {
        var counterValue = $('#goods_counter_value').text();
        if (!isNaN(counterValue) && counterValue) {
            $.cookie(cookieName, counterValue, { expires: 70, path: '/', domain: 'test2.santech.ru', secure: false });
        }
    };
    var counterTimer;
    counterTimer = setInterval(setCounter, updateTime);
    
    $('.good_counter .counter').jOdometer({
          increment: counterInc,
          numbersImage: '/pic/design/digs.gif',
          spaceNumbers: 0,
          offsetRight: 0,
          heightNumber: 35,
          widthNumber: 32,
          counterStart: counterStart,
          counterEnd: counterEnd,
          delayTime: 10000,
          speed: counterSpeed
    });
}


/**
 * Устанавливаем выбранный город по умолчанию, подставляем соответствующий
 * телефон в шапке в блоке телефона.
 */
function setDefaultCity(data) {
    $('#city_select a').removeClass('hidden');
    data = $.extend({}, data);
    var id    = data.id;
    var name  = data.name;
    var code  = data.code;
    var phone = data.phone;
    $.cookie('defaultCity', id, { expires: 70, path: '/', domain: 'test2.santech.ru', secure: false });
    $('#defaultCity').html(name);
    if (code) {
        code = "("+code+")";
    }
    $('.phone').html('<span class="code">'+code+'</span><b>[</b>'+phone+'<b>]</b>');
    $('#city_select a[title='+name+']').addClass('hidden');
}


function splash(sp, link){
  $(link).click(function(){
        $(sp).fadeIn('fast'); 
        $('body').bind('click', function(event){
                if ($(event.target).parents(sp).length == 0) {
                    $(sp).fadeOut('fast');
                    $('body').unbind('click');
                }
            });
        return false;
    });
  if ($(sp+' .close').size()){
    $(sp+' .close').click(function(){
      $(sp).fadeOut('fast');
      return false;
    });
  }
}

function zindexation(id){
        var sz = id.size();
        for (var i=0; i<sz; i++){               
                $(id[i]).css('z-index', 5+sz-i)             
        }
}

/**
 * Переключаем видимость слоёв по таймеру.
 * 
 * @var string  items   селектор блоков для переключения
 * @var integer time    время для переключения (сек)
 */
function autoSwitcher(items, time) {
    if (!items || !time) return;
    items = $(items);
    if ($(items).length<=1) return;
    if (items.data('timer')) clearInterval(items.data('timer'));
    items.data('timer', setInterval( function () {
                                            var cur  = items.filter(':visible');
                                            var next = items.filter(':visible').next(items.selector);
                                            if (!next.length) next = items.first();
                                            next.show();
                                            cur.hide();
                                        },
                                        time*1000
                                    )
    );
}


$(document).ready(function(){
  $('#search_catoptions').css('display', 'none');
  $('.search_form select').change(function(){
    var selected=$(this).find('option:selected').text()
    if (  selected=='каталог' || selected=='Каталог' || selected=='catalog' || selected=='Catalog' ){
      $('#search_catoptions').fadeIn('medium');
    }
    else $('#search_catoptions').fadeOut('medium');
    
  });
  
	$('.open_all_similar a').click(function(){
		$(this).parent().next('.similar').find('.nice_list').slideDown('medium');
		return false;
	});
	 
  $('.form .file,.form .text, .form textarea, .form select').focus(function(){$(this).addClass('focused')});
  $('.form .file,.form .text, .form textarea, .form select').blur(function(){$(this).removeClass('focused')});
    
  $('.jqtrans, .form .field.jqt').jqTransform();     
  $('.jqTransformSelectWrapper div span').css('width', 'auto');
  $('.jqTransformSelectWrapper ul').css('height', 'auto');


  (function(form){
    form.find('.submit').hide(0).addClass('button bd-radius15');
    form.find('select').change(function() {
      form.submit();
    });
  })($('.faq_category_form')); 

  zindexation($('.jqTransformSelectWrapper'));
  $('.main_cat .item .description ').hover(
    function(){
      $(this).animate({height: 131}, 200).addClass('open');
    },
    function(){
      $(this).animate({height: 32}, 200).removeClass('open');
    }
  );

  
  $('.catalog_item .similar .nice_list, .vacancies .item .details').hide(0);
  if (location.hash) $('a'+location.hash).next('.nice_list, .details').show(0); // раскрываем пояснение к записи, если ссылка с якорем на нужную запись
  else $('.catalog_item .similar .nice_list.opened, .vacancies .item .details.opened').show(0);
  $('.catalog_item .similar .title').click(function(){
    $(this).next('.nice_list').slideToggle('medium');
    return false;
  })
	


  $(' .vacancies .item .title').click(function(){
    $(this).next('.details').slideToggle('medium');
    return false;
  })
  splash('#signin_block','#signin_link');
  splash('#call_form_block','.call_order');
  
  $('.thumbs .items_block').scrollable({prev: '.scroll.left', items: '.items', item: 'li'});
  var gallery = $('.thumbs .items_block').data('scrollable');
  $('.thumbs .scroll.right').click(function(){
    if (gallery.getIndex()+3 < gallery.getSize()) gallery.next();
  });
              
  $('.news_gallery a[rel=gal1], .thumbs .item a[rel=item_gal]').fancybox({
                showCloseButton: true
  });
  
	if(jQuery.browser.msie && jQuery.browser.version<7){
		$('.brands_block .items li img').each(function(){
			if ($(this).width()>171) {
				$(this).width('100%');
				$(this).height('auto');
			}
		});
	}
  // CAROUSELL
  /*
  if(sLang=='rus'){
      setExxAnonce('Эксклюзивные бренды');
  }else{
      setExxAnonce('Exclusive brands');
  }*/
  
  
  var items = $('.imagination .items li');
  var current = $(items[1]).addClass('current');
  $('.imagination .items li:not(.current) .description').css('height', 0);
  
  function elem_click(){
    $('.imagination .items li').unbind('click');
    $('.imagination .items li.current').prev().click(function(){  $('.imagination .scroll.left').trigger('click'); return false;});
    $('.imagination .items li.current').next().click(function(){  $('.imagination .scroll.right').trigger('click'); return false;});
  }
  $('.imagination .scroll').click(function(){
    if (!$('.imagination .items li:animated').size()){
      $('.imagination .items li.current .description').css('height', 0);
      $('.imagination .items li.current').animate({ 'top' : 27, 'width' : 120 },400, function(){
          $(this).removeClass('current');
        });
      if ( $(this).hasClass('next')){
        $('.imagination .items li.current').prev().animate({'marginLeft': '-120px'}, 400,function(){
         $(this).appendTo('.imagination .items').css('margin', 0); 
         
        });

        $('.imagination .items li.current').next().animate({ 'top' : 0, 'width' : 160 }, 400, function(){
          $(this).addClass('current');
          $(this).find('.description').css('height', 'auto');
          elem_click();
        });
      }
      else{
        var last = $('.imagination li:last');
        last.css({
          'marginLeft' : '-120px'
        });
        last.prependTo('.imagination .items').animate({'marginLeft':0}, 400);
 
        $('.imagination .items li.current').prev().animate({ 'top' : 0, 'width' : 160 },400, function(){
          $(this).addClass('current');
          $(this).find('.description').css('height', 'auto');
          elem_click();
        });
      }
    }
  });
  elem_click();
  
  //FAQ
  $('.faq .answer').hide(0);
  $('.faq .quest .title').click(function(){
    $(this).parents('.item').find('.answer').slideToggle('medium');
    return false;
  });
	
	$('#city_select').hover(function(){
		$(this).find('ul').show(300);
	},function(){
		$(this).find('ul').hide(300);
	});
	
	$('#city_select ul a').click(function(){
		$(this).closest('ul').hide(300);
	});
	
});


