
$(function() {
	send_request(1);
});

$.fn.extend({
	init_fs: function() {
		return this.each(function() {
			var fs = $(this);

			// Observe activation cb onclick
			var cb = fs.attr('id') === 'ours_fs'? fs.find('input:checkbox') : fs.find('.activation input:checkbox');
			cb.click(function(e) {
				$(this).parents('fieldset').update_fs();
			});

			// Initialize region
			if (fs.attr('id') === 'property_area_id_fs') {
				$('.region').init_region();
			}
		});
	},
	update_fs: function() {
		return this.each(function() {
			var fs = $(this);

			// Activation event
			var cb = fs.attr('id') === 'ours_fs'? fs.find('input:checkbox') : fs.find('.activation input:checkbox');
			cb.each(function() {
				if ($(this).is(':checked')) {
					fs.removeClass('notactive');
				} else {
					fs.addClass('notactive');
				}
			});
		});
	},
	init_region: function() {
		return this.each(function() {
			var region = $(this);

			// Add show area link
			if (region.find('.areas input:checkbox').length > 1) {
				var region_id = region.attr('rel');
				var value = ($.inArray(parseInt(region_id), app_config.regions_shown_areas) === -1? '0' : '1');
				region.children('label').append(''
					+' <a href="#" class="show_areas_a">show areas</a>'
					+' <input type="hidden" name="s[regions]['+region_id+'][show_areas]" class="show_areas" value="'+value+'" />'
					+'');
			}

			// Observe show area link click
			region.find('.show_areas_a').click(function(e) {
				$(this).siblings('input.show_areas').each(function() {
					$(this).val($(this).val() === '0'? '1' : '0');
					region.update_region();
					changed();
				});
				return false;
			});

			// Observe show area link click
			region.find('input').click(function(e) {
				region.update_region();
				changed();
			});

			// Update the region
			region.update_region();
		});
	},
	update_region: function() {
		return this.each(function() {
			var region = $(this);
			region.find('.regions_active').each(function() {

				// Deactivate
				if (!this.checked) {

					// Hide UL
					region.find('ul').css('display', 'none');

					region.find('.show_areas').val('0');

					// Check all areas
					region.find('ul input:checkbox').attr('checked', true);

					// Hide link
					region.find('a').css('display', 'none');
				}

				// Activate
				else {

					// Show link
					region.find('a').css('display', 'inline').text('choose individual areas');

					region.find('.show_areas').each(function() {
						if ($(this).val() === '0') {
							region.find('ul').css('display', 'none');
							region.find('a').text('show areas');
							region.select_areas(true);
						} else {
							region.find('ul').css('display', 'block');
							region.find('a').text('hide areas');
						}
					});
				}
			});
		});
	},
	select_areas: function(all_none) {
		return this.each(function() {
			$(this).find('ul input:checkbox').attr('checked', all_none);
		});
	}
});

var search_string;
function send_request(init) {

	// Set search_string as hash in browser
	if (typeof init === 'undefined') {
		search_string = $('form').serialize();
	} else if (window.location.hash.match(/^#id=(\d+)$/) !== null) {
		search_string = { id: window.location.hash.match(/^#id=(\d+)$/)[1] };
	} else {
		search_string = '';
	}

	// Hide everything
	$('#mls_search').hide();
	$('#properties ul').hide();
	$('#search_summary').hide();
	$('.more_link').hide();
	$('#remembered_properties_link').hide();

	// Reset title
	$('h1 span.text').text('Property Listings');

	// Call AJAX
	var url = 'http://'+app_config.my_app.site_host+'/listings/index/json'+(typeof init !== 'undefined'? '/1' : '');
	$.ajax({
		url: url,
		type: 'POST',
		data: search_string,
		dataType: 'json',
		success: function(data, textStatus) {

			// Has the form changed? If so, do it again
			if (t !== false) {
				send_request();
				return;
			}
			if (typeof init === 'undefined') {
				window.location.hash = '#id='+data.property_search_id;
			}
			$('#loading span').text('Rendering');

			// False alarm - it's the same search
			if (data.search_summary !== $('#search_summary').html()) {

				// Insert meta content
				$('h1 span.text').text(data.h1);
				$('#search_summary').html(data.search_summary);

				// Insert properties
				$('#properties ul.properties_ul').html(data.properties_html);

				// Init properties
				$('.property').prepend('<a class="remember_link">remember</a>');
				$('.property.remembered').each(function() {
					its_remembered($(this).attr('rel'));
				});
				$('.property.forgotten').each(function() {
					its_forgotten($(this).attr('rel'));
				});
				$('.more_link').remove();
				$('.properties_ul').after(''
					+'<div class="more_link">'
					+'<a href="javascript:more_properties(2);">'
					+'Load 20 more listings'
					+'</a>'
					+'</div>'
					+'');
				if (data.properties.length < app_config.properties_page_size) {
					$('.more_link a').attr('href', 'javascript:void(0);').addClass('disabled').text('No more listings to show');
				}

				// Controls were passed
				if (typeof data.controls_html !== 'undefined') {

					// Insert controls
					$('#controls').html(data.controls_html);

					// Init controls
					replace_text_images();
					$('#property_form input[type=submit]').click(function() {
						send_request();
						return false;
					});
					$('#mls_search').submit(check_mls_form);
					$('#property_form').click(function() {
						changed();
					});
					app_config.regions_shown_areas = data.regions_shown_areas;
					$('fieldset').init_fs();
				}

				// Not loading page
				$('#page_loading').hide();

				// Show everything
				$('h1').show();
				$('#mls_search').show();
				$('#remembered_properties_link').show();
			}

			// Show everything
			$('#mls_search').show();
			$('#properties ul').show();
			$('#search_summary').show();
			$('.more_link').show();
			$('#remembered_properties_link').show();

			// Reset title
			$('h1 span.text').text(data.h1);

			// Not loading results
			$('#loading').hide();

			// Has the form changed? If so, do it again
			if (t !== false) {
				send_request();
			}
		},
		error: function(x, txt, e) {

			// Has the form changed? If so, do it again
			if (t !== false) {
				send_request();
			}
		}
	});
}

function check_mls_form(e) {
	$('#mls_search_message').removeClass('error').html('<img src="/img/loading_sm_red_on_beige.gif" />');
	var url = 'http://'+app_config.my_app.site_host+'/listings/view_by_mls?mls='+$('input[name=mls]').val();
	$.ajax({
		url: url,
		data: {},
		success: function(data, textStatus) {
			window.location.href = url;
		},
		error: function(x, txt, e){
			$('#mls_search_message').addClass('error').html('Invalid');
		}
	});
   e.preventDefault();
}

function more_properties(page) {
	$('.more_link a').attr('href', 'javascript:void(0);').html('<img src="/img/loading_sm_white_on_pink.gif" style="vertical-align: middle;" /> Loading');
	$.ajax({
		url: 'http://'+app_config.my_app.site_host+'/listings/index/json',
		dataType: 'json',
		type: 'POST',
		data: $('form').serialize()+'&s[page]='+page,
		success: function(data, textStatus) {
			$('#properties .properties_ul').append('<li class="more_message">Loaded 20 more listings</li>');
			$('#properties .properties_ul').append(data.properties_html);
			$('.property').each(function() {
				if ($(this).find('.remember_link').length === 0) {
					$(this).prepend('<a class="remember_link">remember</a>');
				}
			});
			$('.property.remembered').each(function() {
				its_remembered($(this).attr('rel'));
			});
			$('.property.forgotten').each(function() {
				its_forgotten($(this).attr('rel'));
			});
			if (data.properties.length < app_config.properties_page_size) {
				$('.more_link a').attr('href', 'javascript:void(0);').addClass('disabled').text('No more listings to show');
			} else {
				$('.more_link a').attr('href', 'javascript:more_properties('+(page + 1)+');').text('Load 20 more listings');
			}
		},
		error: function(x, txt, e) {}
	});
}

var t = false;
function changed() {
	$('#loading span').text('Querying');
	$('#loading').show();
	if (t !== false) {
		resetTimout();
	}
	t = setTimeout('execute()', 2000);
}
function resetTimout() {
	clearTimeout(t);
	t = false;
}
function execute() {
	resetTimout();
	send_request();
}

function update_remembered_properties_link(count) {
	if (count === 0) {
		$('#remembered_properties_link a').text('No remembered properties');
	} else {
		$('#remembered_properties_link a').text(count+' remembered propert'+(count === 1? 'y' : 'ies'));
	}
}

function its_remembered(property_id) {
	$('.property[rel='+property_id+'] .remember_link').replaceWith('<a class="remember_link" href="javascript:forget('+property_id+');">forget <img src="/img/pin_on.png" /></a>');
	$('.property[rel='+property_id+']').removeClass('forgotten');
	$('.property[rel='+property_id+']').addClass('remembered');
}

function its_forgotten(property_id) {
	$('.property[rel='+property_id+'] .remember_link').replaceWith('<a class="remember_link" href="javascript:remember('+property_id+');">remember <img src="/img/pin_off.png" /></a>');
	$('.property[rel='+property_id+']').removeClass('remembered');
	$('.property[rel='+property_id+']').addClass('forgotten');
}

function remember(property_id) {
	$('.property[rel='+property_id+'] .remember_link').html('<img src="/img/loading_sm.gif" />').blur();
	$.ajax({
		url: 'http://'+app_config.my_app.site_host+'/listings/remember_ajax/'+property_id,
		dataType: 'json',
		success: function(data, textStatus) {
			its_remembered(property_id);
			update_remembered_properties_link(data.count);
		},
		error: function(x, txt, e) {}
	});
}

function forget(property_id) {
	$('.property[rel='+property_id+'] .remember_link').html('<img src="/img/loading_sm.gif" />').blur();
	$.ajax({
		url: 'http://'+app_config.my_app.site_host+'/listings/forget_ajax/'+property_id,
		dataType: 'json',
		success: function(data, textStatus) {
			its_forgotten(property_id);
			$('#remembered_properties .property[rel='+property_id+']').remove();
			update_remembered_properties_link(data.count);
		},
		error: function(x, txt, e) {}
	});
}

