var prwin;

function preparePrintWin () {
	prwin = window.open('', 'printWin', 'width=760,height=540,toolbar=no,Scrollbars=1');
}

function printPage (obj) {
	if (typeof prwin == 'object') {
		var txt = '<html><link href="css/all.css" rel="stylesheet" type="text/css" /><body><table cellpadding="0" cellspacing="20" width="100%" class="print_table"><tr><td>' + obj.html() + '</td></tr></table></body></html>';
		prwin.window.focus();
		prwin.document.open();
		prwin.document.write(txt);
		prwin.document.close();
		prwin.window.print();
		//prwin.window.close();
	}
}

function sendOrder () {
	$('div#order').find('div.msg').show();
	$('div#order').find('div.msg').html('Заявка отправляется...');
	var fio = $('input[name="fio"]').val();
	var phone = $('input[name="phone"]').val();
	var email = $('input[name="email"]').val();
	var msg = $('textarea[name="message"]').val();
	var flat_id = $('input[name="order_flat_id"]').val();
	$.post('order_js.php', {'fio': fio, 'phone': phone, 'email': email, 'msg': msg, 'flat_id': flat_id}, function (result) {
		if (result == 1) {
			$('div#order').find('div.msg').html('<span class="b">Ваша заявка отправлена</span>');
		} else if (result == 2) {
			$('div#order').find('div.msg').html('<span class="b">Не все обязательные поля заполнены!</span>');
		} else if (result == 3) {
			$('div#order').find('div.msg').html('<span class="b">Ошибка при отправке заявки!</span>');
		} else {
			$('div#order').find('div.msg').text(result);
		}
	}, 'text');	
}

function setHeight() {
	var winH = $(window).height();
	
	if($('#main').size()) {
		var main = $('#main');
		var mainH = main.height();
		$('#main').css('height', winH < 1020 ? 1020 + 'px' : winH + 'px');
	}
	
	if($('#main_in').size()) {
		var block = $('.block_white');
		var blockH = block.height();
		block.css('height', blockH < 760 ? '760px' : 'auto');
		$('.abs_b').css('top', blockH - 75 + 'px');
		
		var main = $('#main_in');
		var mainH = main.height();
		$('#main_in').css('height', mainH < winH ? winH + 'px' : 'auto');
	}
	
	$('#footer').css('top', mainH - 150 + 'px');
}

function overImage(id) {
	$('#' + id + ' img').attr('src', '/img/' + id + '_h.png');
	fixPNG(document.getElementById(id).getElementsByTagName('img').item(0));
}

function outImage(id) {
	$('#' + id + ' img').attr('src', '/img/' + id + '.png');
	fixPNG(document.getElementById(id).getElementsByTagName('img').item(0));
}

var curPhotoID, maxPhotoID, prevPhotoID, nextPhotoID;

function setCurPhoto (parent_obj, id) {
	var obj = $(parent_obj).find('.ph_preview[rel=' + id + ']');
	var src = obj.attr('img');
	var w = obj.attr('w');
	var h = obj.attr('h');
	var date = obj.attr('date');
	var title = obj.attr('title');
	if (title != "") {
		title = " | ".title;
	}

	$('#win .pad_l22').html('');
	$('#win .ph_info').html('');

	$('#win .pad_l22').html('<img src="' + src + '" width="' + w + '" height="' + h + '" />');
	$('#win .ph_info').html(date + title);
	$('#win .ph_info').width(w);
	
	$('#win').css({'width': w*1 + 44 + 'px', 'height': h*1 + 108 + 'px'});
	$('#win .ph_bg').css({'width': w*1 + 14 + 'px', 'height': h*1 + 78 + 'px'});
	$('#win .ph_l, #win .ph_r').css({'height': h*1 + 48 + 'px'});
	$('#win .ph_t, #win .ph_b').css({'width': w*1 - 16 + 'px'});
	$('#win .ph_l_b, #win .ph_r_b').css({'top': h*1 + 78 + 'px'});

	var top = Math.max($(document).scrollTop(), $(document).scrollTop() + ($(window).height() - $('#win').height()) / 2);
	top = Math.min(top, $(document).height() - $('#win').height());
	$('#win').css({'top': top + 'px', 'marginLeft': - $('#win').width()/2 + 'px'});

	if (id == maxPhotoID) {
		nextPhotoID = 1;
	} else {
		nextPhotoID = id*1+1;
	}
	
	if (id == 1) {
		prevPhotoID = maxPhotoID;
	} else {
		prevPhotoID = id*1-1;
	}
	
	curPhotoID = id;
}

function showPhoto (obj) {
	$('#win_bg').css('height', $('#main_in').height() + 'px');
	$('#win_bg').show();

	maxPhotoID = $(obj).find('span.ph_preview').size();

	setCurPhoto (obj, 1); 
	if(maxPhotoID > 1) {
		$('#win .prev').show();
		$('#win .next').show();
		$('#win .prev').click(function(){ setCurPhoto (obj, prevPhotoID); });
		$('#win .next').click(function(){ setCurPhoto (obj, nextPhotoID); });
	}
	
	$('#win').show();
}

function hidePhoto () {
	if($('#win').css('display') == 'block') {
		$('#win').hide();
		$('#win_bg').hide();
	
		$('#win .pad_l22').html('');
		$('#win .ph_info').html('');
	}
}

function showOrder () {
	$('#win_bg').css('height', $('#main_in').height() + 'px');
	$('#win_bg').show();

	$('#order').css({'top': $(document).scrollTop() + $(window).height() / 2 - 266 + 'px'});
	$('#order').show();
}

function hideOrder () {
	if($('#order').css('display') == 'block') {
		$('#order').hide();
		$('#win_bg').hide();
		$('div#order').find('div.msg').hide();
		$('input[name="fio"]').val('');
		$('input[name="phone"]').val('');
		$('input[name="email"]').val('');
		$('textarea[name="message"]').val('');
	}
}

function setOrderInfo (id) {
	$('#order input[name="order_flat_id"]').val(id);
}

function showAnswer(id) {
	$('.quest#' + id + ' .answ').show();

	var lnk = $('.show_answ[rel=' + id + ']');
	lnk.attr('class', 'hide_answ');
	lnk.children('div').eq(0).html('скрыть ответ');
}

function hideAnswer(id) {
	$('.quest#' + id + ' .answ').hide();

	var lnk = $('.hide_answ[rel=' + id + ']');
	lnk.attr('class', 'show_answ');
	lnk.children('div').eq(0).html('показать ответ');
}

function hideImage(id) {
	$('#' + id).addClass('corp_h');
}

function showImage(id) {
	$('#' + id).removeClass('corp_h');
}

function showCorpInfo(id) {
	$('#' + id).addClass('corp_a');
	$('#' + id).removeClass('corp');

	var info = $('#' + id).attr('info');
	var infoArr = info.split('_');

	//$('input[name=sections[' + infoArr[0] + ']]').val('1');
	$('input#selcorp' + infoArr[0]).val('1');
	makeCorpInfo ();
}

function hideCorpInfo(id) {
	$('#' + id).removeClass('corp_a');
	$('#' + id).addClass('corp');

	var info = $('#' + id).attr('info');
	var infoArr = info.split('_');

	$('input[name=sections[' + infoArr[0] + ']]').val('');
	makeCorpInfo ();
}

function makeCorpInfo () {
	var sectCaption = '';
	var re = new RegExp('sections\\[(\\d+)\\]', 'i');
	$('input.sect_select').each (function (id, item) {
		if ($(item).val() == 1) {
			var vr = $(item).attr('name');
			var sectPart = re.exec (vr);
			if (sectCaption == '') {
				sectCaption = sectPart[1];
			} else {
				sectCaption = sectCaption + ',' + sectPart[1];
			}
		}
	});
	if (sectCaption.length > 18) {
		sectCaption = sectCaption.substring (0, 17) + "...";
	}
	$('#out_sect').html(sectCaption);
}

function showPlan(id) {
	var tr = $('#' + id);

	var img_src = tr.attr('img');
	if (img_src != '') {

		$('#win_bg').css('height', $('#main_in').height() + 'px');
		$('#win_bg').show();

		$('#plan').show();

		$('#plan #plan_sect').html('&nbsp;');
		$('#plan #plan_floor').html('&nbsp;');
		$('#plan .plan_img').hide();

		var td = $('#' + id + ' td');
		$('#plan_sect').html(td.eq(0).html());
		$('#plan_floor').html(td.eq(2).html());

		$('#plan' + id + ' img').attr({'src': img_src}).load(function () {  // вызовем код только после загрузки картинки
			$('#plan' + id).show();
			
			var top = Math.min($(document).scrollTop() + ($(window).height() - $('#plan').height()) / 2, $('#main_in').height() - $('#plan').height() - 60);
			$('#plan').css({'top': top + 'px', 'marginLeft': - $('#plan').width()/2 + 'px'});

			$('#plan .plan_t, #plan .plan_b').width($('#plan').width());
			$('#plan .plan_l, #plan .plan_r').height($('#plan').height());
		});
	}
}

function hidePlan() {
	if($('#plan').css('display') == 'block') {
		$('#plan').hide();
		$('#win_bg').hide();
	}
}

function showPrint (id) {
	$('#win_bg').css('height', $('#main_in').height() + 'px');
	$('#win_bg').show();

	$('#print').css({'top': $(document).scrollTop() + $(window).height() / 2 - 284 + 'px'});
	$('#print').show();

	$('div.print_content td.print_flat_row').html('&nbsp;');
	$.get('flat_js.php', {'flat_id': id}, function (result) {
		if (!result.error) {
			if (result.number != 0) {
				$('#flats_print_head').html(' ' + result.number);
			} else {
				$('#flats_print_head').html('');
			}
			$('#flats_print_tr1').html(result.section_num);
			$('#flats_print_tr2').html(result.rooms);
			$('#flats_print_tr3').html(result.floor);
			$('#flats_print_tr4').html(result.square_tot);
			$('#flats_print_tr5').html(result.square_live);
			$('#flats_print_tr6').html(result.square_kitchen);
			$('#flats_print_tr7').html(result.price + ' руб.');
			$('#flats_print_tr8').html(result.price_tot + ' руб.');
			printPage($('#print'));
		} else {
			$('#flats_print_head').html(' не найдена');
		}
	}, 'json');
	
}

function hidePrint() {
	if($('#print').css('display') == 'block') {
		$('#print').hide();
		$('#win_bg').hide();
	}
}

/**
 * при смене валюты
 */
var already_changed = false;
function сhangePriceBox (obj) {
	if (already_changed == true) {
		return;
	}

	already_changed = true;
	var currency_id = $(obj).find('option:selected').val();

	$('div.pricebox').css({'display':'none'});
	$('div.totpricebox').css({'display':'none'});
	$('div.pricebox').filter('#price' + currency_id).css({'display':'block'});
	$('div.totpricebox').filter('#totprice' + currency_id).css({'display':'block'});

	$('div.pricebox').find('input,select').each(function () {
		$(this).attr('disabled', '1');
	});
	$('div.totpricebox').find('input,select').each(function () {
		$(this).attr('disabled', '1');
	});
	$('div.pricebox').filter('#price' + currency_id).find('input,select').each(function () {
		$(this).removeAttr('disabled');
	});
	$('div.totpricebox').filter('#totprice' + currency_id).find('input,select').each(function () {
		$(this).removeAttr('disabled');
	});

	// установим для всех select ту же валюту
	$('select[name="curr"]').getSetSSValue (currency_id);
	
	$('input[name="real_curr"]').val(currency_id);

	already_changed = false;
}

$.preloadImages = function(preload) {  
   $(document.createElement('img')).bind('load', function(){ 
	if(preload[0]) this.src = preload.shift(); 
   }).trigger('load'); 
}

$(document).ready(function(){
	/* отвечает за поведение кнопки (выезжает/заезжает на место)*/
	setInterval("scrollConsultButton()",400);
	  $(".btn-consultant").hover(function(){
		$(".conslink").animate({"width": "+=170px"}, "slow");
		$(this).toggleClass("active"); return false;
	  },function(){
		$(".conslink").animate({"width": "-=170px"}, "slow");
		$(this).toggleClass("active"); return false;
	  });
	/* конец: отвечает за поведение кнопки (выезжает/заезжает на место)*/
	$('#main .menu_top a, #main_in .menu_top .unsel a').hover(function(){ overImage($(this).attr('id')); }, function(){ outImage($(this).attr('id')); });
	
	$('.ph_small').click(function () { showPhoto(this); return false; });
	$('#win_bg, #win .close').click(function(){ hidePhoto(); });
	
	$('.print').click(function(){ preparePrintWin(); printPage($('.block_white_content')); });

	$('.circle_request').click(function () { showOrder(); });
	$('#win_bg, #order .close').click(function(){ hideOrder(); });

	$('#order_button').click(function () { sendOrder (); return (false); });

	$('.show_answ').live('click', function(){ showAnswer($(this).attr('rel')); setHeight(); });
	$('.hide_answ').live('click', function(){ hideAnswer($(this).attr('rel')); setHeight(); });

	$('.submit').click(function () {
		$(this).parents('form').submit();
		return false;
	});

	/* Select Corpus */
	$('.corp').live('mouseover', function(){ hideImage($(this).attr('id')); });
	$('.corp_h').live('mouseout', function(){ showImage($(this).attr('id')); });
	$('.corp').live('click', function(){ showCorpInfo($(this).attr('id')); });
	$('.corp_a').live('click', function(){ hideCorpInfo($(this).attr('id')); });
	/* /Select Corpus */

	/* Sliders */
	$('.slider_item').each (function (id, item) {
		var min = new Number ($(item).attr('min'));
		var max = new Number ($(item).attr('max'));
		if ((typeof ($(item).attr('from')) != 'undefined') && ($(item).attr('from') != '')) {
			var from = new Number ($(item).attr('from'));
		} else {
			var from = min;
		}
		if ((typeof ($(item).attr('to')) != 'undefined') && ($(item).attr('to') != '')) {
			var to = new Number ($(item).attr('to'));
		} else {
			var to = max;
		}
		var step = new Number ($(item).attr('step'));
		var item_min = $(item).attr('item_min');
		var item_max = $(item).attr('item_max');
		$("#" + item_min).val(from);
		$("#" + item_max).val(to);
		$(item).slider({
			range: true,
			min: min,
			max: max,
			values: [from, to],
			step: step,
			slide: function(event, ui) {
				$("#" + item_min).val(ui.values[0]);
				$("#" + item_max).val(ui.values[1]);
			}
		});
	});
	/* /Sliders */

	/* Selects */
	$('.select_item').each (function (id, item) {
		$(item).sSelect();
	});
	/* /Selects */

	/* Flats Table */
	$('.flats_table .tr_odd').live('mouseover', function(){ 
		$(this).addClass('tr_h');
		$(this).removeClass('tr_odd');
		$(this).find('img').each(function(){ $(this).attr('src', '/img/' + $(this).attr('class') + '_h.gif'); });
	});
	$('.flats_table .tr_even').live('mouseover', function(){ 
		$(this).addClass('tr_h');
		$(this).removeClass('tr_even');
		$(this).find('img').each(function(){ $(this).attr('src', '/img/' + $(this).attr('class') + '_h.gif'); });
	});
	$('.tr_h').live('mouseout', function(){ 
		var ind = $('.flats_table tr').index(this);
		var ostat = Math.ceil(ind/2) - Math.floor(ind/2);
		if(ostat == 0)
			$(this).addClass('tr_even'); 
		else
			$(this).addClass('tr_odd'); 
		$(this).removeClass('tr_h');
		$(this).find('img').each(function(){ $(this).attr('src', 'img/' + $(this).attr('class') + '.gif'); });
	});
	
	$('.flats_zayav_s').click(function () { showOrder (); setOrderInfo ($(this).parents('tr').attr('id')); });
	$('.flats_plan_s').click(function () { showPlan($(this).parents('tr').attr('id')); });
	$('#win_bg, #plan .close').click(function(){ hidePlan(); });
	$('.flats_print_s').click(function () { preparePrintWin(); showPrint($(this).parents('tr').attr('id')); });
	$('#win_bg, #print .close').click(function(){ hidePrint(); });

	$('#plan .print_plan').click(function () { preparePrintWin (); printPage ($('div#plan div.plan_c')); });

	/* /Flats Table */

	/* Блоки с выбором валют */
	$('div.pricebox').filter('.hide').css({'display':'none'});
	$('div.totpricebox').filter('.hide').css({'display':'none'});

	/* Стрелки сортировки */
	$('table.flats_table span.sort_change').live('click', function () {
		$('form#search_form input[name="order"]').val($(this).attr('order'));
		$('form#search_form input[name="order_sort"]').val($(this).attr('sort'));
		$('form#search_form').submit();
	});
});

$(window).load(function(){ setHeight(); });

$(window).resize(function(){ setHeight(); });
/* Marva-system*/
var lastScrollFromTop = 0;
var blockScrollButton = false;
var lastWindowHeight = 0;
var blockRelocation = false;
var blockConsultButtonMove = false;

function scrollConsultButton(){
	if(blockScrollButton)return;
	var currentWindowHeight = parseFloat($(window).height());
	var windowScrollFromTop = parseFloat($(window).scrollTop());
	var delta =windowScrollFromTop - lastScrollFromTop;
	if(currentWindowHeight != lastWindowHeight){
		delta += (currentWindowHeight - lastWindowHeight)/2;
		lastWindowHeight = currentWindowHeight;
	};
	lastScrollFromTop = windowScrollFromTop;
	blockScrollButton = true;
	$(".btn-consultant").animate(
			{"top": "+="+delta}, "slow", function(){
				blockScrollButton = false;
			}
	);
};
/* Marva-system*/

