 function index_games(dir_id, page, category) {
	$("#box_" + dir_id).load("ajax_functions.php", {'function': 'index_games', 'dir_id': dir_id, 'page': page, 'category': category});
}

function change_category(dir_id, category) {
	if(category == 0) {
	    $("#links_bl_" + dir_id + "_new").removeClass("links");
	    $("#links_bl_" + dir_id + "_new").addClass("links_this");
	    $("#links_bl_" + dir_id + "_hit").removeClass("links_this");
	    $("#links_bl_" + dir_id + "_hit").addClass("links");
	    $("#links_bl_" + dir_id + "_preorder").removeClass("links_this");
	    $("#links_bl_" + dir_id + "_preorder").addClass("links");
	} else  if(category == 1) {
	    $("#links_bl_" + dir_id + "_new").removeClass("links_this");
	    $("#links_bl_" + dir_id + "_new").addClass("links");
	    $("#links_bl_" + dir_id + "_hit").removeClass("links");
	    $("#links_bl_" + dir_id + "_hit").addClass("links_this");
	    $("#links_bl_" + dir_id + "_preorder").removeClass("links_this");
	    $("#links_bl_" + dir_id + "_preorder").addClass("links");
	} else if(category == 2) {
	    $("#links_bl_" + dir_id + "_hit").removeClass("links_this");
	    $("#links_bl_" + dir_id + "_hit").addClass("links");
	    $("#links_bl_" + dir_id + "_new").removeClass("links_this");
	    $("#links_bl_" + dir_id + "_new").addClass("links");
	    $("#links_bl_" + dir_id + "_preorder").removeClass("links");
	    $("#links_bl_" + dir_id + "_preorder").addClass("links_this");
	}

	index_games(dir_id, 0, category);

	return false;
}

var preview_archive = new Array();
var preview_active = 0;

function preview(prod_id) {
	preview_active = prod_id;
	if(typeof(preview_archive[prod_id])=='undefined' || preview_archive[prod_id] == "") {
//		$("#preview").load("ajax_functions.php", { 'function': 'preview', 'prod_id': prod_id});
		$.post("ajax_functions.php", {'function': 'preview', 'prod_id': prod_id}, function(data) {
				preview_archive[prod_id] = data;
				if(preview_active == prod_id) {
					$("#preview").html(preview_archive[prod_id]);
					$("#preview").css("display", "block");
				}
			}
		);
	}
	if(preview_active == prod_id) {
		$("#preview").html(preview_archive[prod_id]);
		$("#preview").css("display", "block");
	}
}

function preview_close(prod_id) {
	preview_active = 0;
	$("#preview").css("display", "none");
	//preview_archive[prod_id] = $("#preview").html();
	$("#preview").html("");
}

var browser_width, browser_height;

if(window.innerHeight || window.innerWidth){
	browser_width = window.innerWidth;
	browser_height = window.innerHeight;
} else {
	browser_width = document.documentElement.clientWidth;
	browser_height = document.documentElement.clientHeight;
}

function preview_move(product) {
	var offset = $(product).offset();
//	$("#preview").css("top", parseInt(offset.top + $(product).height()) + "px");
	if(browser_width < parseInt(offset.left - 140 + 386)) {
		$("#preview").css("left", parseInt(offset.left - 140 - (offset.left - 140 + 386 - browser_width + 18)) + "px");
	} else {
		$("#preview").css("left", parseInt(offset.left - 140) + "px");
	}
	$(product).mousemove(function(e){
      $("#preview").css("top", parseInt(e.pageY + 20) + "px");
	});
}

function addComplect(complect_quantity) {
	var complect_station = '';
	if(document.getElementById('complect_station') && document.getElementById('complect_station').selectedIndex > 0) {
		if(parseInt(document.getElementById('complect_station').options[document.getElementById('complect_station').selectedIndex].value) > 0) {
			complect_station = parseInt(document.getElementById('complect_station').options[document.getElementById('complect_station').selectedIndex].value);
		}
	}
	
	complect_prods = new Array();
	i = 0;
	while($('#complect_prods_' + i).length > 0) {
		var complect_prod = $('#complect_prods_' + i).val();
		complect_prod = parseInt(complect_prod);
		if(complect_prod > 0) {
			complect_prods[i] = complect_prod;
		}
		i++;
	}
	params = new Array();
	params['complect_station'] = complect_station;
	params['complect_prods'] = complect_prods;

	return params;
}


function cart_add(cart_button, prod_id) {
//	cart.php?action=add&prod_id=prod_id

	params = new Array();
	params = addComplect();
	
	$("#cart_prods").load("ajax_functions.php", {
			'function': 'cart_add'
			, 'prod_id': prod_id
			, 'complect_station' : params['complect_station']
			, 'complect_prods[]' : params['complect_prods' ]
	});

	$(".basket").addClass("akt");

	cart_add_hide(cart_button);

	$("#added_to_cart_img").css("display", "block");
}

function cart_add_show(cart_button) {
	var offset = $(cart_button).offset();
	$("#add_to_cart_img").css("top", parseInt(offset.top) + parseInt($(cart_button).height()) + parseInt($(cart_button).css("padding-top")) + parseInt($(cart_button).css("margin-top")) + "px");
	$("#add_to_cart_img").css("left", parseInt(offset.left - $("#add_to_cart_img").width()/2) + "px");
	$("#add_to_cart_img").css("display", "block");
	$("#added_to_cart_img").css("top", parseInt(offset.top) + parseInt($(cart_button).height()) + parseInt($(cart_button).css("padding-top")) + parseInt($(cart_button).css("margin-top")) + "px");
	$("#added_to_cart_img").css("left", parseInt(offset.left - $("#add_to_cart_img").width()/2) + "px");
}

function cart_add_hide(cart_button) {
	$("#added_to_cart_img").css("display", "none");
	$("#add_to_cart_img").css("display", "none");
}

function submit_user() {
	js_client_id = parseInt($('#client_id').val());
	js_client_passwd = $('#client_passwd').val();
	if(js_client_id > 0 && js_client_passwd.length > 0) {
		$.post("ajax_functions.php", {'function': 'submit_user', 'client_id': (js_client_id), 'client_passwd': (js_client_passwd)}, function(data) {
			if(data == 'success') {
				window.location='cart.php';
			} else {
				$("#user_error").css("display", "block");
			}
		});
	} else {
		$("#user_error").css("display", "block");
	}
}

function submit_user_ajax() {
	js_client_id = parseInt($('#client_id').val());
	js_client_passwd = $('#client_passwd').val();
	if(js_client_id > 0 && js_client_passwd.length > 0) {
	    $.post("ajax_functions.php", {'function': 'submit_user', 'client_id': (js_client_id), 'client_passwd': (js_client_passwd)}, function(data) {
		if(data == 'success') {
			$("#user_error").css("display", "none");
			$("#tr_client_id").css("display", "none");
			$("#tr_client_passwd").css("display", "none");
			$("#client_ok").html('Номер клиента: ' + js_client_id);
			$.post("ajax_functions.php", {'function': 'getClientDetails'}, function(data) {
			    $('#fname').val(data.fname);
			    $('#address').val(data.address);
			    $('#h_phone').val(data.h_phone);
			    $('#m_phone').val(data.m_phone);
			    $('#email').val(data.email);
			    if(data.unsubscribe == 1) {
				$('#subscribe').attr('checked', false);
			    } else {
				$('#subscribe').attr('checked', true);
			    }
			}, "json");
		} else {
			$("#user_error").css("display", "block");
		}
	    });
	} else {
		$("#user_error").css("display", "block");
	}
}

function check_form2() {
    if($('input[name=sendType]:checked') && $('input[name=sendType]:checked').val() == 'emspost') {
     if($('#locationEmsCode').val() != '') {

     } else {
        $('#location').focus();
        check_form2_error('Выберите регион или город');
        return false;
     }
    }

        document.forms["user_info"].fname.className="none";
	if(document.forms["user_info"].fname.value=="") {
            document.forms["user_info"].fname.className="error";
            document.forms["user_info"].fname.focus();
            check_form2_error('Введите Ф.И.О.');
            return false;
	}

        document.forms["user_info"].city.className="none";
	if($("#delivery").val() == 'emspost') {
            if(document.forms["user_info"].city.value=="") {
                document.forms["user_info"].city.className="error";
                document.forms["user_info"].city.focus();
                check_form2_error('Введите Город');
                return false;
            }
        }

        document.forms["user_info"].address.className="none";
	if($("#delivery").val() == 'courier') {
            if(document.forms["user_info"].address.value=="") {
                document.forms["user_info"].address.className="error";
                document.forms["user_info"].address.focus();
                check_form2_error('Введите Адрес');
                return false;
            }
        }
	if($("#delivery").val() == 'emspost') {
            if(document.forms["user_info"].address.value=="") {
                document.forms["user_info"].address.className="error";
                document.forms["user_info"].address.focus();
                check_form2_error('Введите Адрес');
                return false;
            }
        }

	if(document.forms["user_info"].h_phone.value!="") {
		 document.forms["user_info"].h_phone.className="none";
	} else {
		document.forms["user_info"].h_phone.className="error";
		document.forms["user_info"].h_phone.focus();
		check_form2_error('Введите Телефон 1');
		return false;
	}

        document.forms["user_info"].email.className="none";
	if($("#delivery").val() == 'emspost' || $("#payType").val() == 'webmoney') {
            if(document.forms["user_info"].email.value=="") {
                document.forms["user_info"].email.className="error";
                document.forms["user_info"].email.focus();
                check_form2_error('Введите E-Mail');
                return false;
            }
        }
	if(document.forms["user_info"].email.value!="") {
		var str=document.forms["user_info"].email.value;
		var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		if (filter.test(str)) {
		} else{
			document.forms["user_info"].email.className="error";
			document.forms["user_info"].email.focus();
			check_form2_error("Введите правельный E-mail");
			return false;
		}
	}

	return true;
}

function check_form2_error(msg) {
	$("#send_form_error").css("display", "block");
	$("#send_form_error").html(msg);
}

function calcSendPrice(location) {
    if(location == "") {
        $('#delivery_addon_text').html('')
        $('#total_price_show').html('');
        $('#dostavka_text').html('');
        $('#end_price_show').html('');
    } else {
        $('#calcSendPriceLoading').show();
        $.post('/cart.php', {'action' : 'calculate', 'location' : location}, function(data) {
            if(data && data.error == 0) {
                $('#locationEms').val($('#location :selected').text());
                $('#locationEmsCode').val($('#location :selected').val());
                $('#delivery_addon_text').html('Время доставки ' + data.deliveryTime + ' дней')
                $('#total_price_show').html(Math.round(Math.round($('#total_prod_price').val()) + Math.round(data.sendPrice)) + ' руб.');
                $('#dostavka_text').html(Math.round(data.sendPrice) + ' руб.');
                $('#end_price_show').html(Math.round(Math.round($('#total_prod_price').val()) - Math.round($('#total_discont').val()) + Math.round(data.sendPrice)) + ' руб.');
            } else {
                $('#locationEms').val('');
                $('#delivery_addon_text').html('<strong style="color:red;">Ошибка подсчёта времени или стоимости доставки!</strong><br/>Отправьте Ваш заказ через <a href="/contact.php">контактную форму</a>, обязательно указав E-mail!');
                $('#total_price_show').html('');
                $('#dostavka_text').html('');
                $('#end_price_show').html('');
            }
            $('#calcSendPriceLoading').hide();
        }, 'json');
    }
}

var search_autocomplite = new Array();

$(document).ready(function() {

  $("#search").blur(function() {
    $("#search").val() == '' ? $("#search").val('Найти...') : '';
    $('#search_autocomplite_result').hide(2000);
  });

  $("#search").keyup(function() {
      $('#search_autocomplite_result').hide();
      $('#search_autocomplite_result').html('');
      if($("#search").val().length > 0) {
          if(search_autocomplite[$("#search").val()] == undefined) {
              $.post('/ajax_functions.php', {'function' : 'search_autocomplite', 'text' : $("#search").val()}, function(data) {
                    search_autocomplite_add(data)}, 'json');
          } else {
              if(search_autocomplite[$("#search").val()] != '') {
                  $('#search_autocomplite_result').html(search_autocomplite[$("#search").val()]);
                  $('#search_autocomplite_result').show();
              }
          }
      }
  });
});

function search_autocomplite_add(data) {
  if(data && data.num_rows > 0 ) {
      var results = '';
      for(prod in data.prods) {
        results += '<span style="font-size: 9px;" title="' + data.prods[prod].dir_name + '">' + data.prods[prod].dir_name_short + '</span> <a href="/product/' + data.prods[prod].prod_id + '.html" title="' + data.prods[prod].model + '">' + data.prods[prod].cut_model + (data.prods[prod].model != data.prods[prod].cut_model ? '...' : '') + '</a><br/>';
      }
      $('#search_autocomplite_result').html(results);
      $('#search_autocomplite_result').show();
    search_autocomplite[$("#search").val()] = results;
  } else {
    search_autocomplite[$("#search").val()] = '';
  }
}

