var basket_count = 0;

// прелоад картинок
function preload(page)
{  if (page == 'splash')
  {    /* Это пример прелодера картинок
    var pic_x = new Image(85, 14);
    pic_x.src = "/images/pic_x_hover.jpg";
    */
  }

  if (page == 'index')
  {    /* Это пример прелодера картинок
    var pic_x = new Image(85, 14);
    pic_x.src = "/images/pic_x_hover.jpg";
    */  }}

jQuery(document).ready(function($){  /* пример обработки меню с ховерами, если пункт является картинкой
     На все пункты меню должны быть проставлены id единого вида, в данном случае это вид - big_menu_0*, * - любое число
  $("img[id*=big_menu_0]").hover(
    function(event)
    {      var x = this.id.length - 1;
      var y = this.id.substring(x);
      var my_img_id = 'big_menu_0' + y;
      document.getElementById(my_img_id).src = '/images/big_menu_0' + y + 'a.jpg';    },
    function(event)
    {      var x = this.id.length - 1;
      var y = this.id.substring(x);
      var my_img_id = 'big_menu_0' + y;
      document.getElementById(my_img_id).src = '/images/big_menu_0' + y + '.jpg';    }
  );
  */
  $("a[id*=menu_link_3_]").click(function(event){    x = this.id;
    x = x.replace('menu_link_3_', '');
    $("div[id*=podmenu_]").slideUp(300);
    $('#podmenu_'+x).slideDown(300);
    return false;
  });

  $(".basket_input").keyup(function(event){  	calc();
  });
})

// пересчитывает общее кол-во товара
function calc()
{  basket_count = 0;
  $(".basket_input").each(function(n){
    basket_count = basket_count + parseInt(this.value);
  });
  $("#b_count_i").html(basket_count);}

// функция для отправки формы
function submit_form(name)
{
  document.getElementById(name).submit();
  return false;
}

// ставит автоматом на все ссылки blur()
function externalLinks()
{
  if (!document.getElementsByTagName) return;
  var anchors = document.links;
  for (var i=0; i < anchors.length; i++)
  {
    anchors[i].onfocus = function(e){this.blur();}
  }
}

// задает значение в Cookie
function setCookie (name, value, expires, path, domain, secure)
{
  document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

// получает значение Cookie
function getCookie(name)
{
  var cookie = " " + document.cookie;
  var search = " " + name + "=";
  var setStr = null;
  var offset = 0;
  var end = 0;
  if (cookie.length > 0)
  {
    offset = cookie.indexOf(search);
    if (offset != -1)
    {
      offset += search.length;
      end = cookie.indexOf(";", offset)
      if (end == -1)
      {
        end = cookie.length;
      }
      setStr = unescape(cookie.substring(offset, end));
    }
  }
  return(setStr);
}

// возвращает первую позицию элемента в строке
function strpos(haystack, needle, offset)
{
  var i = haystack.indexOf(needle, offset);
  return i >= 0 ? i : false;
}

// shows the block over the entire

function getClientHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

function getBodyScrollTop()
{
  return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

function getClientCenterY()
{
	return parseInt(getClientHeight()/2)+getBodyScrollTop();
}

function show_popup(id)
{
	var w = $("#"+id).width()/2;
	var h = $("#"+id).height()/2;
	if ( ($("#"+id).height()+20)>getClientHeight() ){
		$("#"+id).css('top', 30+'px');
		h=0;
	}else{
		$("#"+id).css('top', getClientCenterY()+'px');
	}
	$("#"+id).css("margin", "-"+h+"px 0 0 -"+w+"px");

	$(document).bind('mousewheel',function(e){
		var elem = $(e.target).parents('.popup_frame')[0];
		if (elem!=null){
			if (e.target.className!='reg_shadow' && (elem.scrollTop-e.wheelDelta)<=0 && e.wheelDelta>0){
				elem.scrollTop = 0;
				return false;
			}
			if (e.target.className!='reg_shadow' && (elem.scrollTop+(-1)*e.wheelDelta+$(elem).height())>=elem.scrollHeight && e.wheelDelta<0){
				elem.scrollTop = elem.scrollHeight;
				return false;
			}
		}
	});


	//$("#shadow").height($('.content_wrapper').height());
	$("#shadow").show();
	$("#"+id).show();
	return false;
}

function hide_popup(id)
{
	$("#"+id).hide();
	$("#shadow").hide()
	return false;
}

function show_message(title, text)
{
  content = '<div class="ms_title">' + title + '</div><div>' + text + '</div>';
  $('#ms_karkas').html(content);
  show_popup('message');
  setTimeout("hide_popup('message')", 5000);
}

// добавляет продукт в корзину
function add_to_basket(id)
{
  basket = getCookie("basket");
  if (basket)
  {    x = strpos(basket, id, 0);
    if (!x)
    {
      basket = basket + ',' + id;
      setCookie("basket", basket, "Mon, 01-Jan-2018 00:00:00 GMT", "/");
      basket_count = basket_count + 1;
      add_mess = 'Товар успешно добавлен в корзину.';
    }
    else {add_mess = 'Товар уже есть в корзине.';}
  }  else
  {    setCookie("basket", ','+id, "Mon, 01-Jan-2018 00:00:00 GMT", "/");
    basket_count = basket_count + 1;
    add_mess = 'Товар успешно добавлен в корзину.';
  }

  show_message('', add_mess);

  $('#b_count').html(basket_count);
}

// удаляет продукт из корзины
function delete_from_basket(id)
{  basket_list_count = basket_list.length
  new_basket_list = Array();
  y = 0;
  for (x=0; x<basket_list_count; x++)
  {    if (basket_list[x]['indexid'] == id)
    {      $('#pr_box_'+id).remove();
      $('#pr_line_'+id).remove();
      basket = getCookie("basket");
      basket = basket.replace(','+id,'');
      setCookie("basket", basket, "Mon, 01-Jan-2018 00:00:00 GMT", "/");
      basket_count = basket_count - 1;
      $('#b_count').html(basket_count);
    }
    else
    {      new_basket_list[y] = basket_list[x];
      y = y + 1;    }
  }
  basket_list = new_basket_list;
  if (basket_list.length < 1)
  {
    $('#basket_article_box').html('Корзина пуста');
    $('#basket_contact_box').remove();  }

  return false;
}

function show_pic(pic)
{
  $('a[id*=product_big_pic_]').hide();
  $('#product_big_pic_'+pic).css('display', 'block');
}

function show_infobox_error()
{
  content = '<div>Вы сможете посмотреть результаты после того, как проголосуете...</div>';
  $('#ms_karkas').html(content);
  show_popup('message');
  setTimeout("hide_popup('message')", 5000);
  return false;
}

// осуществляет переход в форум
function forum_go()
{
  id = document.getElementById('forum_select').value;
  if (id != '') window.location.href = "?f=" + id;
  return false;
}

// осуществляет сортировку в теме
function topic_go(f)
{
  x = '?f=' + f;
  topic_sort = document.getElementById('topic_sort').value;
  topic_pole = document.getElementById('topic_pole').value;
  topic_date = document.getElementById('topic_date').value;
  if (topic_sort != '') x = x + '&sort=' + topic_sort;
  if (topic_pole != '') x = x + '&pole=' + topic_pole;
  if (topic_date != '') x = x + '&date=' + topic_date;
  window.location.href = x;
  return false;
}
