$(function()
    {
function change_pos(el, text) {
		var w_w = $(window).scrollLeft() + $(window).width();
		var w_h = $(window).scrollTop() + $(window).height();
		var el_lc = el.offset().left + el.width()/2;
		var el_tc = el.offset().top + el.height()/2;
		var text_w = text.outerWidth();
		var text_h = text.outerHeight();
		var i = 0;
				
		if ((el_lc + text_w) > w_w) {
			if (el_tc + text_h > w_h) i = 3;
			else i = 2
		}
		else {
			if ((el_tc + text_h) > w_h) i = 4;
			else i = 1;
		}

		switch (i) {
			case 1:
				text.css({
					'left' : el_lc + 'px',
					'top' : el_tc
				});			
				break;
			case 2:
				text.css({
					'left' : el_lc - text_w + 'px',
					'top' : el_tc + 'px'
				});
				break;
			case 3:
				text.css({
					'left' : el_lc - text_w + 'px',
					'top' : el_tc - text_h + 'px'
				});
				break;
			case 4:
				text.css({
					'left' : el_lc + 'px',
					'top' : el_tc - text_h + 'px'
				});
				break;
		}
}

	$('.list_item .discount_img').hover(
          function () {
            var el = $(this);
			var text = el.parents('.list_item').find('.discount_text');
			change_pos(el, text);
			text.show();
          },
          function () {
            $('.discount_text').hide();
          }
        );
		//Если курсор перешел со скидки к тексту, то текст показываем. Если курсор ушел из текста то текст скрываем
		$('.discount_text').hover(
          function () {
			$(this).show();
          },
          function () {
            $('.discount_text').hide();
          }
        );
        
    $('#detail_top .discount_img').hover(
          function () {
            var el = $(this);
			var text = el.parents('#detail_top').find('.discount_text');
			change_pos(el, text);
			text.show();
          },
          function () {
            $('.discount_text').hide();
          }
        );
		//Если курсор перешел со скидки к тексту, то текст показываем. Если курсор ушел из текста то текст скрываем
		$('.discount_text').hover(
          function () {
			$(this).show();
          },
          function () {
            $('.discount_text').hide();
          }
        );
        
        
});
