// Растягиваем высоту документа до разрешения экрана пользователя
$(document).ready(function(){
	// Проверяем высоту страницы и растягиваем её если она слишком маленькая
	if(document.body.style.height < screen.height){
		document.body.style.height = screen.height+"px";
	}
	// ф-ция динамического ресайза центр.таба б/у авто
	var bu_auto_list_width = $(window).width() - 590;
	$("#last_bu_list").width(bu_auto_list_width);
	
	$(document).mousemove(function(e){
		window.mouseX = e.pageX;
		window.mouseY = e.pageY;
	});
	/* Обработчик плагина lazyload
	$("img").lazyload({
		effect : "fadeIn",
		placeholder : "http://mir46.ru/IMGS/tpl/grey.gif"
	});
	*/
});

// Функции для работы с формой Яндекс поиска по сайту
function clearYaSearchField(){
	$("#ya_search_field").css({"background":"none"});
	$("#ya_search_field").val("");
}

function refreshYaSearchField(){
	if($("#ya_search_field").val() == ""){
		$("#ya_search_field").css({"background":"url(http://mir46.ru/IMGS/search_ico.png) no-repeat","background-position":"left center"});
		$("#ya_search_field").val("Поиск..");
	}
}

// функция раскрытия/сворачивания эксперс-сервисов и каталогов
function exp_exp(name){
	if($("#"+name+"_expand").css("visibility") == "hidden"){
		js_expand(name);
	}else{
		js_collapse(name);
	}
}
function js_expand(target){
	var menu;
	if (target == "express"){
		menu = document.getElementById("express_expand");
		menu.style.width = (document.getElementById("exp_button").clientWidth-7)+"px";		
		menu.style.left = getAbsPos(document.getElementById("exp_button")).x + 3 + "px";
		menu.style.top = getAbsPos(document.getElementById("exp_button")).y + 25 + "px";
	}else{
		menu = document.getElementById("cat_expand");
		menu.style.width = (document.getElementById("cat_button").clientWidth-7)+"px";		
		menu.style.left = getAbsPos(document.getElementById("cat_button")).x + 3 + "px";
		menu.style.top = getAbsPos(document.getElementById("cat_button")).y + 25 + "px";
	}
	menu.style.visibility = "visible";
	document.getElementById("bg").style.width = document.body.clientWidth + "px";
	document.getElementById("bg").style.height = document.body.clientHeight + "px";
	document.getElementById("bg").style.visibility = "visible";
}
function js_collapse(target){
	var menu;
	if (target == "express"){
		menu = document.getElementById("express_expand");		
	}else{
		menu = document.getElementById("cat_expand");	
	}
	menu.style.visibility = "hidden";
	document.getElementById("bg").style.visibility = "hidden";
}
function getAbsPos(p) {
	var s = { x:0, y:0 };
        while (p.offsetParent) {
        	s.x += p.offsetLeft;
                s.y += p.offsetTop;
                p = p.offsetParent;
	}
        return s;
}

// Функции показа меню авторизации на сайте
function js_show_popup_panel(){
	$("#login_form").css({"position":"fixed","top":"0px","left":"0px"});
	document.getElementById("email").focus();
}

function js_hide_popup_panel(){
	$("#login_form").css({"top":"-9999px","left":"-9999px","position":"absolute"});
}

// Функция-аналог urlencode(). Использование: escape(строка) 
var trans = [];
for (var i = 0x410; i <= 0x44F; i++) trans[i] = i - 0x350;
trans[0x401] = 0xA8;
trans[0x451] = 0xB8;
var escapeOrig = window.escape;

window.escape = function(str){
	var ret = [];
	for(var i = 0; i < str.length; i++){
		var n = str.charCodeAt(i);
		if (typeof trans[n] != 'undefined') n = trans[n];
		if (n <= 0xFF) ret.push(n);
	}
	return escapeOrig(String.fromCharCode.apply(null, ret));
}

// Функции модуля голосования
function vote_for_opt(vote_id){
	if($.cookie("v"+vote_id) == null){
		var voteurl = "/ajax/?mod=vote&id="+vote_id+"&opt_id="+$("#optid").val();
		$("#votetab").hide();
		$("#voteresults").load(voteurl);
		$("#voteresults").fadeIn("fast");
	}else{
		alert("Вы уже голосовали в этом опросе.");
	}
}

function show_vote_results(vote_id){
	$("#votetab").hide();
	$("#voteresults").load("/ajax/?mod=vote&id="+vote_id+"&rand="+new Date().getTime());
	$("#voteresults").fadeIn("fast");
}

// Функции гороскопа
function show_horo(img, key){
	img.stop().animate({width:"50px",height:"50px",left:"0",top:"0"}, 200);
	$("#h4z").html($("#zz"+key).html());
}
function delight_horo(img){
	img.stop().animate({width:"40px",height:"40px",left:"0",top:"0"}, 300);
}

// Функции для работы и для приведения формы поиска б/у авто каталога cat_auto к нормальному виду в зависимости от разрешения экрана
function style_asf(fid, mid){
	var tbl_width = ($(document).width() - 606); // 606px - это боковые табы + отступы в сумме
	var tbl_free_width = tbl_width - 20; // отнимаем 20, т.к. внутри таблицы 5 td блоков с паддингом 2px.
	//$("#asf_tbl").width() - 20;
	var asf_fid_width  = parseInt(tbl_free_width / 5);
	var asf_sost_width = asf_fid_width;
	var asf_fyear_width = parseInt(asf_fid_width / 2) - 8; // отнимаем 8px, из-за тире между селектами
	var asf_tyear_width = asf_fyear_width;
	var asf_cenadodo_width = asf_fid_width - 10;
	
	if(fid == 68){
		alert($(document).width()+" - "+tbl_width+" - "+asf_fid_width);
	}
	
	if(fid >= 0){
		$("#asf_mid_div").load("/ajax/?rand="+new Date().getTime()+"&w="+asf_fid_width+"&mod=cat_auto&act=modelselect&fid="+fid+"&mid="+mid);
	}
	
	$("#asf_fid").width(asf_fid_width);
	$("#asf_sost").width(asf_sost_width);
	$("#asf_fyear").width(asf_fyear_width);
	$("#asf_tyear").width(asf_tyear_width);
	$("#asf_cenado").width(asf_fid_width);
}
function asf_load_models(fid, width){
	$("#asf_mid_div").html("<img width=16 height=16 src=http://mir46.ru/IMGS/system_loading.gif>");
	$("#asf_mid_div").load("/ajax/?rand="+new Date().getTime()+"&w="+width+"&mod=cat_auto&act=modelselect&fid="+fid);
}
function asf_submit(){
	window.location = $("#auto_sf_action").val()+"&fid="+$("#asf_fid").val()+"&mid="+$("#asf_mid").val()+"&sost="+$("#asf_sost").val()+"&fyear="+$("#asf_fyear").val()+"&tyear="+$("#asf_tyear").val()+"&cenado="+$("#asf_cenado").val();
}

// Ф-ция cat_auto переключения фото внутри объявления
function cat_auto_show_big_img(t, i){
	var ai = $("#active_thumb_id").val();
	$("#bigimg").attr("src", t.attr("src"));
	$("#biga").attr("href", t.attr("src"));
	$("#ca_thumb"+ai).removeClass("active_thumb");
	$("#ca_thumb"+ai).addClass("thumb");
	t.parent().removeClass("thumb");
	t.parent().addClass("active_thumb");
	$("#active_thumb_id").val(i);
}

// ф-ция скрытия/показа элементов формы поиска недвижимости
function realt_sf_refresh(cat_id){
	if(cat_id == "1" || cat_id == "5" || cat_id == "2"){
		$("#komnat_select").show();
	}else{
		$("#komnat_ot").val(0);
		$("#komnat_do").val(0);
		$("#komnat_select").hide();
	}
}

// Ф-ции cat_job
function sfe_expand(t, obj_id, sfe_id){
	if($("#sfe"+sfe_id).is(":hidden")){
		t.css({
			"background" : "url(http://job.mir46.ru/IMGS/minus.gif) no-repeat",
			"background-position" : "center center"
		});
		$("#sfe"+sfe_id).html("<img width=16 height=16 src=http://mir46.ru/IMGS/system_loading.gif>");
		$("#sfe"+sfe_id).load("/ajax/cat_job/?object="+obj_id+"&act=listspec&sfe_id="+sfe_id+"&rand="+Math.random());
		$("#sfe"+sfe_id).fadeIn("fast");
	}else{
		t.css({
			"background" : "url(http://job.mir46.ru/IMGS/plus.gif) no-repeat",
			"background-position" : "center center"
		});
		$("#sfe"+sfe_id).slideUp("fast");
	}
}

// Ф-ция открытия объкта в новом окне, в частности, увеличенного изображения
// При повторном вызове с той же страницы, вместо открытия ещё одного окна, используется уже имеющееся окно,
// в которое и подгружается новое содержимое, после чего ему передаётся фокус
function in_new_window(url, title, width, height){
	newWindow = window.open(url, title, "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,width="+width+",height="+height);
	if(newWindow == null){
		alert("Ваш браузер блокирует всплывающие окна! Отключите эту блокировку, чтобы просматривать фото большого размера.");
	}else{
		newWindow.focus();
	}
}

// Ф-ции доски
// открытие/скрытие формы подачи жалобы
function doska_complain(obj_id){
	if($("#complain").is(":visible")){
		$("#complain").fadeOut(300);
	}else{
		$("#compid").attr("value", obj_id);
		$("#complain").width(400).css({"left":"290px", "top":"300px"});
		$("#complain").fadeIn(400);
	}
}
// Подсказка HowToVIP и HowToUp
function show_howtovip(){
	if($("#howtovip").is(":hidden")){
		$("#howtovip").fadeIn(300);
		$("#howtovip").css({
			"display" : "block",
			"left" : (mouseX + 15)+"px",
			"top" : (mouseY + 15)+"px"
		});
	}else{
		$("#howtovip").css({
			"left" : (mouseX + 15)+"px",
			"top" : (mouseY + 15)+"px"
		});
	}
}
function show_howtoup(){
	if($("#howtoup").is(":hidden")){
		$("#howtoup").fadeIn(300);
		$("#howtoup").css({
			"display" : "block",
			"left" : (mouseX + 15)+"px",
			"top" : (mouseY + 15)+"px"
		});
	}else{
		$("#howtoup").css({
			"left" : (mouseX + 15)+"px",
			"top" : (mouseY + 15)+"px"
		});
	}
}
function doska_add_form_submit(){
	if(document.getElementById("title").value.length < 3){
		alert("Вы не заполнили поле ЗАГОЛОВОК ОБЪЯВЛЕНИЯ!");
	}else if(document.getElementById("text").value.length < 1){
		alert("Вы не заполнили поле ТЕКСТ ОБЪЯВЛЕНИЯ!");
	}else if(document.getElementById("city").value.length < 1){
		alert("Вы не заполнили поле ГОРОД!");
	}else if(document.getElementById("salername").value.length < 3){
		alert("Вы не заполнили поле ИМЯ!");
	}else if(document.getElementById("phone").value.length < 3){
		alert("Вы не заполнили поле ТЕЛЕФОН!");
	}else if(!document.getElementById("acceptrules").checked){
		alert("Вы не подтвердили своё согласие с правилами размещения объявлений!");
	}else{
		document.getElementById("addobj").submit();
	}
}
function doska_tree_expand(gid){
	if($("#suborggroups"+gid).is(":hidden")){
		$("#garrow"+gid).css({
			"background" : "url(http://job.mir46.ru/IMGS/minus.gif) no-repeat",
			"background-position" : "left center"
		});
		if($("#suborggroups"+gid).html() == ""){
			$("#suborggroups"+gid).show();
			$("#suborggroups"+gid).html("<img width=16 height=16 src=http://mir46.ru/IMGS/system_loading.gif>");
			$("#suborggroups"+gid).load("/ajax/?mod=doska&act=list_childs&gid="+gid+"&rand="+Math.random());
		}else{
			$("#suborggroups"+gid).slideDown(300);
		}
	}else{
		$("#garrow"+gid).css({
			"background" : "url(http://job.mir46.ru/IMGS/plus.gif) no-repeat",
			"background-position" : "left center"
		});
		$("#suborggroups"+gid).slideUp(300);
	}
}

function alb2fav(t, alb_id){
	if($("#isfavalb"+alb_id).val() == 0){
		$("#isfavalb"+alb_id).val(1);
		t.attr({
			"src" : "http://mir46.ru/IMGS/system_red_heart.gif",
			"title" : "Этот альбом был добавлен вами в избранное."
		});
		$.get("/ajax/?mod=cat_photos&act=addfava&alb_id="+alb_id+"&rand="+Math.random());
	}else{
		$("#isfavalb"+alb_id).val(0);
		t.attr({
			"src" : "http://mir46.ru/IMGS/system_white_heart.gif",
			"title" : "Добавить альбом в избранное?"
		});
		$.get("/ajax/?mod=cat_photos&act=delfava&alb_id="+alb_id+"&rand="+Math.random());
	}
}

function try_alb_pwd(alb_id, pho_id){
	$.cookie("alb"+alb_id+"pwd", $("#pwd").val());
	window.location = "/?mod=cat_photos&act=showalb&alb_id="+alb_id+"&pho_id="+pho_id+"&rand="+Math.random();
}

function cat_photos_refresh_inf_and_comments(pho_id){
	$("#pho_inf_container").fadeOut(150).load("/ajax/?mod=cat_photos&act=pho_inf_tbl&pho_id="+pho_id+"&rand="+Math.random()).slideDown(300);
	if($("div").is("#pho_comments_list")){
		$("#pho_comments_list").html("загружаем...");
	}
	$(document).ready(function(){
		$("#pho_id").val(pho_id);
		$("#pho_comments_list").load("/ajax/?mod=cat_photos&act=pho_comments&pho_id="+pho_id+"&rand="+Math.random());
	});
	
}

function cat_photos_rate_pho(pho_id, val){
	$.get("/ajax/?mod=cat_photos&act=rate&pho_id="+pho_id+"&rate="+val+"&rand="+Math.random());
	setTimeout('cat_photos_refresh_inf_and_comments('+pho_id+')', 200);
}

function cat_photos_list_voted(){
	if($("#voted_list_tbl").is(":hidden")){
		$("#voted_list_tbl").css({
			"display" : "block",
			"left" : (mouseX - 220)+"px",
			"top" : (mouseY + 7)+"px",
			"width" : "220"
		});
	}
}

function show_contest_info(block_id){
	$.each({
		1 : "terms",
		2 : "prizes",
		3 : "winers"
		}, function(i, b_id){ 
			if(block_id == b_id){
				if($("#"+b_id).is(":visible")){
					$("#"+b_id).hide();
				}else{
					$("#"+b_id).slideDown(400);
				}
			}else{
				$("#"+b_id).hide();
			}
		}
	);
}

function show_contests_addform(cont_id){
	if($("#addform").is(":hidden")){
		$("#contests").hide();
		$("#addform").slideDown(300);
	}else{
		$("#addform").hide();
		$("#contests").slideDown(300);
	}
	
	$("#cont_id").val(cont_id);
}

function show_contest_bigpho(cpho_id){
	if($("#img"+cpho_id).is(":hidden")){
		
	}else{
		$("#img"+cpho_id).hide();
		$("#contests").fadeIn(300);
	}
}

/* poputchik */
function poputchik_search(){
	$("#poplist").html("<center style=\"margin-top:7px;\">Загрузка<br><img width=16 height=16 src=http://mir46.ru/IMGS/system_loading.gif></center>");
	$("#poplist").load("/ajax/poputchik/?ya="+$("#Ya:checked").val()+"&napr_iz="+$("#napriz").val()+"&napr_v="+$("#naprv").val()+"&rand="+Math.random());
}

function poputchik_add_exp(){
	if($("#addpredmenu").is(":hidden")){
		$("#addpredmenu").slideDown("300");
	}else{
		$("#addpredmenu").slideUp("300");
	}
}

/* cat_nahodki */
function nahodki_load_objs(cat_id){
	if(parseInt(cat_id) == 0){
		$("#obj_info").html("<span class=num_obj>укажите категорию...</span>");
	}else{
		$("#obj_info").html($("#obj_"+cat_id).html());
	}
}

function list_otkliki(obj_id){
	if($("#rt"+obj_id).is(":hidden")){
		$("#rt"+obj_id).slideDown(300);
	}else{
		$("#rt"+obj_id).slideUp(300);
	}
}
