$(function() {
	//Выбор района
	$('.district .new_name strong').click(function() {
		$(this).parents('.district').find('input').val('');
		$(this).parents('.district').find('input[name=district]').val($(this).text());
	});
	$('.district .old_name strong').click(function() {
		$(this).parents('.district').find('input').val('');
		$(this).parents('.district').find('input[name=districtOld]').val($(this).text());
	});
	$('.district .other-city strong').click(function() {
		$(this).parents('.district').find('input').val('');
		$(this).parents('.district').find('input[name=rayObl]').val($(this).text());
	});
	$('.district h3').click(function() {
		$(this).parents('.district').find('input').val('');
	})
	//Сортировка
	$('.sort li strong, .table-list th strong').live('click', function() {
		$('.content').fadeTo(0, 0.5);
		var dir = $(this).attr('data-dir');
		var query = $.parseJSON($('#query').val());
		var action = $('.filter .this form[style*=block] input[name=action]').val();
		query.orderField = $(this).attr('data-order');
		query.orderDir = dir;
		$.post(baseUrl + '/realty/' + action + '/', {params: JSON.stringify(query)}, function(html) {
			$('.content').replaceWith(html);
			$('.content').fadeTo(0, 1);
		});
	});
	//Отображение
	$('.display-mode a').live('click', function() {
		$('.content').fadeTo(0, 0.5);
		var query = $.parseJSON($('#query').val());
		var action = $('.filter .this form[style*=block] input[name=action]').val();
		query.template = $(this).attr('data-template');
		$.post(baseUrl + '/realty/' + action + '/', {params: JSON.stringify(query)}, function(html) {
			$('.content').replaceWith(html);
			$('.content').fadeTo(0, 1);
		});
	});
	//Сабмит фильтра
	$('.filter form').live('submit', function() {
		$('.content').fadeTo(0, 0.5);
		var query = $.parseJSON($('#query').val());
		var filter = $(this).serializeForm();
		var action = $(this).find('input[name=action]').val();
		$.extend(query, filter);
		query.page = 0;
		$.post(baseUrl + '/realty/' + action + '/', {params: JSON.stringify(query)}, function(html) {
			$('.content').replaceWith(html);
			$('.content').fadeTo(0, 1);
		});
		return false;
	});
	$('#paginator.e a').live('click', function() {
		$('.content').fadeTo(0, 0.5);
		var action = $('.filter .this form[style*=block] input[name=action]').val();
		var query = $.parseJSON($('#query').val());
		query.page = $(this).attr('data-page');
		$.post(baseUrl + '/realty/' + action + '/', {params: JSON.stringify(query)}, function(html) {
			$('.content').replaceWith(html);
			$('.content').fadeTo(0, 1);
		});
		return false;
	});

	$('#paginator.ne a').live('click', function() {
		$('.content').fadeTo(0, 0.5);
		$.post(location, {page: $(this).attr('data-page')}, function(html) {
			$('.content').replaceWith(html);
			$('.content').fadeTo(0, 1);
		});
		return false;
	});

	/*$('.filter .rbls a, .filter .hacnb a').click(function() {
		$('.filter .this form[style*=block] .submit').click();
	});*/
	//Голосование
	$('.vote-but').click(function() {
		var answerId =  $(':input[name=answer]:checked').val();
		if (!answerId) {
			return false;
		}
		$.post(baseUrl + '/poll/widget/', {answerId: answerId}, function(html) {
			$('.votes').replaceWith(html);
		});
		return false;
	});
	//Форма входа
	$('.log_inn form').submit(function() {
		$('.log_inn dd').removeClass('error');
		$.post(baseUrl + '/my/login/', $(this).serialize(), function(json) {
			if (!json.success) {
				for (var key in json.errors) {
					$('input[name*=' + key + ']').parent().addClass('error');
				}
			} else {
				location.reload();
			}
		}, 'json');
		return false;
	});
	//Кабинет риэтора
	$('.riel-room-inn').submit(function() {
		$('.error span').remove();
		$('.riel-room-inn .error').removeClass('error');
		$.post(baseUrl + '/my/saveInfo/', $(this).serialize(), function(json) {
			if (!json.success) {
				for (var key in json.errors) {
					$(':input[name*="[' + key + ']"]').parent().addClass('error');
					$(':input[name*="[' + key + ']"]').parent().append('<span>' + json.errors[key] + '</span>');
				}
			} else {
				location.reload();
			}
		}, 'json');
		return false;
	});

	$('.comments-add').submit(function() {
		$('.error span').remove();
		$('.comments-add .error').removeClass('error');
		$.post(baseUrl + '/realty/saveComment/', $(this).serialize(), function(json) {
			if (!json.success) {
				for (var key in json.errors) {
					$(':input[name*="[' + key + ']"]').parent().addClass('error');
					$(':input[name*="[' + key + ']"]').parent().append('<span>' + json.errors[key] + '</span>');
				}
			} else {
				location.reload();
			}
		}, 'json');
		return false;
	});

	$('#analytics .period:eq(1) .rbls a, #analytics .period:eq(1) .hacnb a').live('click', function() {
		$('.ht.error').remove();
		var from = {};
		var to = {};
		from['month'] = $('#analytics .period:eq(1) .i_want_perech:eq(0) > li:eq(0) .active a').attr('data-id');
		from['year'] = $('#analytics .period:eq(1) .i_want_perech:eq(0) > li:eq(1) .active a').text();
		to['month'] = $('#analytics .period:eq(1) .i_want_perech:eq(1) > li:eq(0) .active a').attr('data-id');
		to['year'] = $('#analytics .period:eq(1) .i_want_perech:eq(1) > li:eq(1) .active a').text();
		$.post(baseUrl + '/analytics/rebuild/', {from: from, to: to}, function(html) {
			if (!html) {
				$('.period .i_want_perech:last').after('<span class="ht error">Некорректный период</span>');
			} else {
				$('#rep').html(html);
			}
		});
	});

	$('#sortable').sortable({
		update: function() {
			$('.content').fadeTo(0, 0.5);
			var arr = $(this).sortable('toArray');
			var sorted = [];
			for (var key in arr) {
				sorted.push({
					id: $('#' + arr[key]).attr('data-id'),
					type: $('#' + arr[key]).attr('data-type')
				});
			}
			$.post(baseUrl + '/my/order/', {items: sorted}, function() {
				$('.content').fadeTo(0, 1);
			});
		}
	});

	if ($('.mask_upl_foto').length) {
		var uploader = new qq.FileUploader({
			element: $('.mask_upl_foto')[0],
			action: baseUrl + '/admin/file/upload/',
			params: {
				thumb: true,
				thumbPreset: '78x78',
				folder: 'agents',
				allowed: ['jpg', 'jpeg', 'png']
			},
			multiple: false,
			template: '<div class="qq-uploader qq-upload-button" style="width: 78px; height: 78px;"><div class="qq-upload-drop-area"></div><ul class="qq-upload-list" style="display: none;"></ul></div>',
			onComplete: function(id, fileName, responseJSON) {
				if (!responseJSON.success) {
					return false;
				}
				$('.foto img').remove();
				$('.foto').append('<img src="' + responseJSON.thumb + '" alt="" data-fileName="' + responseJSON.fileName + '"/>');
				$('.foto-wrap > a').show();
				$.post(baseUrl + '/my/saveInfo/', {'Agent[image]': responseJSON.fileName}, function(json) {

				});
			}
		});

		$('.foto-wrap > a').click(function() {
			$.post(baseUrl + '/admin/file/delete/', {file: 'agents/' + $('.foto img').attr('data-fileName')}, function() {
				$.post(baseUrl + '/my/saveInfo/', {'Agent[image]': ''}, function(json) {
					$('.foto img').remove();
					$('.foto-wrap > a').hide();
				});
			});
		});
	}

	if ($('#datepicker2').length) {

		var el = $('#datepicker2');

		$(el).datepicker({
			showOn: "button",
			buttonImage: baseUrl + '/static/img/picker.png',
			buttonImageOnly: true,
			dateFormat: 'dd.mm.yy',
			altField: '#' + $(el).attr('data-id'),
			altFormat: '@'
		});

		$.datepicker.regional['ru'] = {
			closeText: 'Закрыть',
			prevText: '&#x3c;Пред',
			nextText: 'След&#x3e;',
			currentText: 'Сегодня',
			monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
			monthNamesShort: ['января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря'],
			dayNames: ['Воскресенье','Понедельник','Вторник','Среда','Четверг','Пятница','Суббота'],
			dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
			dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
			weekHeader: 'Не',
			dateFormat: 'd M, yy',
			firstDay: 1,
			isRTL: false,
			showMonthAfterYear: false,
			yearSuffix: ''};
		$.datepicker.setDefaults($.datepicker.regional['ru']);

		var date = new Date();
		date.setTime(parseInt($('#' + $(el).attr('data-id')).val()) * 1000);
		$(el).datepicker('setDate', date);
	}

	$('#tipok').parent().submit(function() {
		$('#tipok').parent().find('.error span').remove();
		$('#tipok').parent().find('*').removeClass('error');
		$.post(baseUrl + '/realty/search/', {rid:$('#tipok').parent().find('input[name=rid]').val(), type:$('#tipok').parent().find('input[name=type]').val()}, function(url) {
			if (url) {
				window.location = url;
			} else {
				$('#tipok').parent().find('input[name=rid]').parent().addClass('error');
				$('#tipok').parent().find('input[name=rid]').parent().append('<span>Объект не найден</span>');
			}
		});
		return false;
	});

	$.reject({
		reject: {
			msie5: true,
			msie6: true,
			msie7: true
		},
		display: ['firefox','chrome','msie','safari','opera'],
		browserInfo: { // Settings for which browsers to display
			firefox: {
				text: 'Firefox'
			},
			safari: {
				text: 'Safari'
			},
			opera: {
				text: 'Opera'
			},
			chrome: {
				text: 'Chrome'
			},
			msie: {
				text: 'Internet Explorer'
			}
		},
		imagePath: baseUrl + '/static/img/',
		close: false,
		header: 'Вы знаете что ваш браузер устарел?',
		paragraph1: 'Ваш браузер устарел и не совместим с нашим сайтом. Список самых популярных веб-браузеров можно найти ниже.',
		paragraph2: ''
	});

	$('.fancy').fancybox({
		overlayShow: true,
		hideOnContentClick: true,
		showCloseButton: false,
		transitionIn: 'elastic',
		transitionOut: 'elastic',
		padding: 0,
		speedIn: 200,
		speedOut: 200
	});

	$('.aff-carousel li a').click(function() {
		$('.aff-carousel div a').attr('href', $(this).attr('data-original'));
	});

	$('.type-of-apart a').click(function() {
		$('input[name=communal]').val($(this).attr('data-val'))
	});

	$('input[name=street]').each(function() {
		$(this).autocomplete({
			serviceUrl: baseUrl + '/realty/autocomplete/type/street/',
			width: 300
		});
	});
	
	$('input[name=rayObl]').each(function() {
		$(this).autocomplete({
			serviceUrl: baseUrl + '/realty/autocomplete/type/rayObl/',
			width: 300
		});
	});
	
	$('input[name=city]').each(function() {
		$(this).autocomplete({
			serviceUrl: baseUrl + '/realty/autocomplete/type/city/',
			width: 300
		});
	});
	
});
//Сериализация формы
$.fn.serializeForm = function() {
	var o = {};
	$(this).find(':input').each(function() {
		if (this.name) {
			if (this.name.match(/\[.*\]/)) {
				var name = this.name.replace(/\[.*\]/, '');
				if (o[name] == undefined) {
					o[name] = {};
				}
				if (($(this).attr('type') == 'checkbox' && $(this).attr('checked')) || $(this).attr('type') != 'checkbox') {
					var key = this.name.match(/\[(.*)\]/);
					key = key[1];
					if (!key) {
						key = Object.keys(o[name]).length;
					}
					o[name][key] = this.value;
				}
			} else if (o[this.name] !== undefined) {
				if (!o[this.name].push) {
					o[this.name] = [o[this.name]];
				}
				o[this.name].push(this.value || '');
			} else {
				if (($(this).attr('type') == 'checkbox' && $(this).attr('checked')) || $(this).attr('type') != 'checkbox') {
					o[this.name] = this.value || '';
				} else if ($(this).attr('type') == 'checkbox') {
					o[this.name] = '';
				}
			}
		}
	});
	return o;
};
