$(document).ready(function() {
	/* Отображение главной */
	if ($('.index_new').size() > 0) {
		index_view.init();
	}
	/* /Отображение главной */

	/* Блок картинок на главной */
	if ($('.index_new .image_block').size() > 0) {
		image_block.init();
	}
	/* /Блок картинок на главной */

	/* Поиск недвижимости */
	if ($('.index_new .search').size() > 0) {
		search_block.init();
	}
	/* /Поиск недвижимости */

	/* Подписка */
	if ($('.index_new .subscr_link').size() > 0) {
		subscribe.init();
	}
	/* /Подписка */

});

$(window).resize(function() {
	if ($('.index_new').size() > 0) {
		index_view.set_page_width();
	}
});

var index_view = {
	init: function() {
		index_view.move_center_block();
		index_view.set_page_width();
	},
	move_center_block: function() {
		var center_block = $('.index_new .center_block');
		var center_h = center_block.height();
		var center_t = center_block.position().top;
		var content_block = $('.index_new .content_in');
		var content_h = content_block.height();
		//content_block.css({'marginBottom': Math.max(20, center_h + center_t - content_h + 20) + 'px'});
		content_block.height(Math.max(center_h + center_t + 80, content_h) + 20);
	},
	set_page_width: function() {
		$('.body_m').width('100%');
		$('.body_m').width(Math.max($('.body_m').width(), 960));
	}
};

var image_block = {
	block: '',
	images: '',
	active: '',
	init: function() {
		image_block.block = $('.index_new .image_block');
		image_block.images = image_block.block.find('img');
		image_block.block.find('img').not('.active').css({'opacity': 0});
		image_block.active = image_block.images.index(image_block.block.find('img.active'));
		image_block.update(true);
	},
	update: function(skip) {
		if (!skip) {
			var a = image_block.images.eq(image_block.active),
				n = (image_block.active + 1 < image_block.images.size()) ? image_block.active + 1 : 0,
				b = image_block.images.eq(n);
			$(b).css({'zIndex': 1}).animate({'opacity': 1}, 100);
			$(a).css('zIndex', 2).animate({'opacity': 0}, 2000, function(el) {
				return function() {
					$(el).css('zIndex', 0);
				}
			}(a));
			image_block.active = n;
		}
		setTimeout(image_block.update, 5500);
	}
};

var search_block = {
	lnk: '',
	block: '',
	init: function() {
		search_block.lnk = $('.index_new .search .search_link');
		search_block.block = $('.index_new .search .search_block');
		
		search_block.lnk.bind('click', function() { search_block.show_block(); });
		search_block.block.find('.search_go').bind('click', function() {
			var url = '';
			switch (sessvars['index']['radio']) {
				case 'cat_1':
					url = '/catalog_elite'
					break;
				case 'cat_2':
					url = '/catalog_new'
					break;
				case 'cat_4':
					url = '/catalog_rentelite'
					break;
			}
			
			document.location = url;
		});
		search_block.block.find('.search_close').bind('click', function() { search_block.hide_block(); });

		search_block.init_sessvars();
		search_block.init_radios();
		search_block.init_selects();
		search_block.init_sliders(search_block.block.find('.slider'));
	},
	show_block: function() {
		search_block.block.parents('.header').css({'zIndex': 10});
		search_block.block.show();
		search_block.lnk.hide();
	},
	hide_block: function() {
		search_block.block.hide();
		search_block.lnk.show();
		search_block.block.parents('.header').css({'zIndex': 1});
	},
	radio_check: function(radio) {
		radio.parents('.radio').removeClass('radio_off').addClass('radio_on');
		radio.parents('.radio_wrap').addClass('radio_sel');
	},
	radio_uncheck: function(radio) {
		radio.parents('.radio').removeClass('radio_on').addClass('radio_off');
		radio.parents('.radio_wrap').removeClass('radio_sel');
	},
	init_sessvars: function() {
		// Инициализация переменных сессии при первом заходе
		if (typeof(sessvars['index']) == 'undefined' || sessvars['index'] == '')
			sessvars['index'] = {};
		if (typeof(sessvars['index']['radio']) == 'undefined' || sessvars['index']['radio'] == '')
			sessvars['index']['radio'] = 'cat_1';

		search_block.block.find('.radio input[type=radio]').each(function() {
			if (typeof(sessvars[$(this).attr('value')]) == 'undefined' || sessvars[$(this).attr('value')] == '')
				sessvars[$(this).attr('value')] = {};
			if (typeof(sessvars[$(this).attr('value')]['price_from']) == 'undefined' || sessvars[$(this).attr('value')]['price_from'] == '')
				sessvars[$(this).attr('value')]['price_from'] = $(this).attr('def_price_from');
			if (typeof(sessvars[$(this).attr('value')]['price_to']) == 'undefined' || sessvars[$(this).attr('value')]['price_to'] == '')
				sessvars[$(this).attr('value')]['price_to'] = $(this).attr('def_price_to');
			if (typeof(sessvars[$(this).attr('value')]['space_from']) == 'undefined' || sessvars[$(this).attr('value')]['space_from'] == '')
				sessvars[$(this).attr('value')]['space_from'] = $(this).attr('def_space_from');
			if (typeof(sessvars[$(this).attr('value')]['space_to']) == 'undefined' || sessvars[$(this).attr('value')]['space_to'] == '')
				sessvars[$(this).attr('value')]['space_to'] = $(this).attr('def_space_to');
		});

		search_block.block.find('#slider_price').attr('from', sessvars[sessvars['index']['radio']]['price_from']);
		search_block.block.find('#slider_price').attr('to', sessvars[sessvars['index']['radio']]['price_to']);
		search_block.block.find('#slider_square').attr('from', sessvars[sessvars['index']['radio']]['space_from']);
		search_block.block.find('#slider_square').attr('to', sessvars[sessvars['index']['radio']]['space_to']);
	},
	init_radios: function() {
		$('.radio input').attr('checked', false);
		$('.radio input[value="'+sessvars['index']['radio']+'"]').attr('checked', true);

		search_block.block.find('.radio input[type=radio]').each(function() {
			if ($(this).attr('checked')) {
				search_block.radio_check($(this));

				search_block.block.find('#slider_price').attr('min', $(this).attr('def_price_from'));
				search_block.block.find('#slider_price').attr('max', $(this).attr('def_price_to'));
				search_block.block.find('#slider_square').attr('min', $(this).attr('def_space_from'));
				search_block.block.find('#slider_square').attr('max', $(this).attr('def_space_to'));
			}
			else {
				search_block.radio_uncheck($(this));
			}
		});
		search_block.block.find('.radio input[type=radio]').bind('change', function() {
			$(this).parents('.radios').find('.radio').each(function() {
				search_block.radio_uncheck($(this).find('input'));
			});
			if ($(this).attr('checked')) {
				search_block.radio_check($(this));
			}
			
			if ($(this).attr('name') == 'radio_type') {
				search_block.change_type($(this));
			}
		});
	},
	init_selects: function() {
		var units = search_block.block.find('#slider_price').parents('.slider_wrap').find('.slider_units');
		var type = sessvars['index']['radio'];
		if (type == 'cat_4') {
			search_block.block.find('.filter p').eq(0).html('Арендная ставка');
			search_block.block.find('#slider_price_units option.rur').val('1000').html('тыс. руб.');
		}
		else {
			search_block.block.find('.filter p').eq(0).html('Стоимость квартиры');
			search_block.block.find('#slider_price_units option.rur').val('1000000').html('млн. руб.');
		}

		units.html(search_block.block.find('#slider_price_units option.rur').html());

		search_block.block.find('.select').not('.inited').each(function() {
			$(this).find('select').sSelect();
			$(this).addClass('inited');
		});
		
		search_block.block.find('#slider_price_units').bind('change', function() {
			units.html($(this).find('option:selected').html());
			search_block.change_units($(this));
		});
	},
	init_sliders: function(sliders) {
		sliders.each (function (id, item) {
			if ($(item).hasClass('inited')) {
				$(item).slider('destroy');
			}
			
			var min = parseInt ($(item).attr('min'));
			var max = parseInt ($(item).attr('max'));
			if ((typeof ($(item).attr('from')) != 'undefined') && ($(item).attr('from') != '')) {
				var from = parseInt ($(item).attr('from'));
			} else {
				var from = min;
			}
			if ((typeof ($(item).attr('to')) != 'undefined') && ($(item).attr('to') != '')) {
				var to = parseInt ($(item).attr('to'));
			} else {
				var to = max;
			}
			var step = parseInt($(item).attr('step'));
			var item_min = $(item).attr('id') + '_min';
			var item_max = $(item).attr('id') + '_max';
			search_block.block.find('#' + item_min).val(from);
			search_block.block.find('#' + item_max).val(to);
			$(item).slider({
				range: true,
				min: min,
				max: max,
				values: [from, to],
				step: step,
				slide: function(event, ui) {
					var o0 = search_block.block.find('#' + item_min).val();
					var o1 = search_block.block.find('#' + item_max).val();
					search_block.block.find('#' + item_min).val(ui.values[0]);
					search_block.block.find('#' + item_max).val(ui.values[1]);
					if (o0 != ui.values[0])
						search_block.block.find('#' + item_min).change();
					if (o1 != ui.values[1])
						search_block.block.find('#' + item_max).change();

					if ($(item).attr('id') == 'slider_price') {
						sessvars[sessvars['index']['radio']]['price_from'] = ui.values[0];
						sessvars[sessvars['index']['radio']]['price_to'] = ui.values[1];
					}
					else if ($(item).attr('id') == 'slider_square') {
						sessvars[sessvars['index']['radio']]['space_from'] = ui.values[0];
						sessvars[sessvars['index']['radio']]['space_to'] = ui.values[1];
					}
				}
			});
			
			var label_step = ((max - min) / 5000 >= 1) ? 5000 : ((max - min) / 500 >= 1) ? 100 : ((max - min) / 100 >= 1) ? 50 : ((max - min) / 10 >= 1) ? 10 : 1; 
			var labels = $(item).parents('.slider_wrap').find('.slider_labels');
			labels.empty();
			var labels_num = parseInt((max - min) / label_step);
			for (var i=0; i<=labels_num; i++) {
				labels.append('<span class="slider_label">' + ((i<labels_num)?i*label_step:('&gt;' + i*label_step)) + '</span>');
			}
			var label = labels.find('.slider_label');
			var labels_coef = (max - min) / $(item).width();
			label.each(function(ind) {
				var left = parseInt(label_step * ind / labels_coef - $(this).width() / 2) + 3;
				$(this).css('left', left + 'px');
			});
			
			if (!$(item).hasClass('inited')) {
				$(item).addClass('inited');
			}
		});
	},
	change_type: function(radio) {
		var select_type = search_block.block.find('select#slider_price_units')
		var type = radio.val();
		if (type == 'cat_4') {
			search_block.block.find('.filter p').eq(0).html('Арендная ставка');
			select_type.find('option.rur').val('1000').html('тыс. руб.');
			select_type.parents('.select').find('ul li').eq(0).html('тыс. руб.');
		}
		else {
			search_block.block.find('.filter p').eq(0).html('Стоимость квартиры');
			select_type.find('option.rur').val('1000000').html('млн. руб.');
			select_type.parents('.select').find('ul li').eq(0).html('млн. руб.');
		}

		sessvars['index']['radio'] = radio.val();

		search_block.block.find('#slider_square').attr('min', radio.attr('def_space_from'));
		search_block.block.find('#slider_square').attr('max', radio.attr('def_space_to'));
		search_block.block.find('#slider_square').attr('from', sessvars[sessvars['index']['radio']]['space_from']);
		search_block.block.find('#slider_square').attr('to', sessvars[sessvars['index']['radio']]['space_to']);
		search_block.init_sliders(search_block.block.find('#slider_square'));

		select_type.change();
	},
	change_units: function(sel) {
		var curr = (sel.val() != sel.find('option.rur').val()) ? (sel.val() / sel.find('option.rur').val()) : 1;
		var radio = search_block.block.find('.radio_on input');
		search_block.block.find('#slider_price').attr('min', Math.ceil(radio.attr('def_price_from') / curr));
		search_block.block.find('#slider_price').attr('max', Math.ceil(radio.attr('def_price_to') / curr));
		var from = Math.ceil(sessvars[sessvars['index']['radio']]['price_from'] / curr);
		var to = Math.ceil(sessvars[sessvars['index']['radio']]['price_to'] / curr);
		search_block.block.find('#slider_price').attr('from', from);
		search_block.block.find('#slider_price').attr('to', to);
		search_block.init_sliders(search_block.block.find('#slider_price'));
	}
};

var subscribe = {
	lnk: '',
	block: '',
	init: function() {
		subscribe.lnk = $('.index_new .subscr_link');
		subscribe.block = $('.index_new .subscr_block');
		
		subscribe.lnk.bind('click', function() { subscribe.show_block(); });
		subscribe.block.find('.subscr_close').bind('click', function() { subscribe.hide_block(); });
		subscribe.block.find('.subscr_go').bind('click', function() { subscribe.send_form(); });
	},
	show_block: function() {
		subscribe.block.find('form').show();
		subscribe.block.find('.subscr_mes').hide();
		subscribe.block.css('top', $(document).scrollTop() - 50 + 'px').show();
	},
	hide_block: function() {
		subscribe.block.hide();
	},
	send_form: function() {
		// тут отправляется форма
		$.get('/subscribe.php', {'email': this.block.find('input[type=text]').val()}, function (data){
			subscribe.block.find('form').hide();
			var mes = data.substr(1);//'Спасибо! Ваш адрес включен в список рассылки.';
			var res = data.substr(0,1);
			if (res > 0) {
				setTimeout(subscribe.show_block, 1500);
				subscribe.block.find('.subscr_mes').html(mes).css('color', '#DC1921').show(); // 
			} else {
				subscribe.block.find('.subscr_mes').html(mes).css('color', '').show(); // 
			}
		});
	}
};

