$(document).ready(function() {
	$('#SearchBoxNavLinks > ul > li > a').click(function(e) {
		e.preventDefault();
		
		var index = $(this).parent().parent().children().index($(this).parent());
		$('#SearchBoxNavLinks > ul > li.SearchBoxLinks').each(function(i) {
			if(i == index)
				$(this).addClass('Active');
			else
				$(this).removeClass('Active');
		});

		var resultsForTabIndex = $('#SearchResults').data('resultsForTabIndex');
		if(resultsForTabIndex !== undefined && resultsForTabIndex == index) {
			$('#SearchResults').show();
			$('#FeaturedListingsContainer > .Active.FeaturedType').removeClass('Active');
		} else {
			$('#SearchResults').hide();
			$('#FeaturedListingsContainer > .FeaturedType').each(function(i) {
				if(i == index) {
					$(this).addClass('Active');
					$(this).find('.ListingMap').each(function() {
						var map = $(this).data('map');
						var startLatitude = $(this).data('startLatitude');
						var startLongitude = $(this).data('startLongitude');
						map.checkResize();
						map.setCenter(new GLatLng(startLatitude, startLongitude), 15);
						map.checkResize();
					});
				} else {
					$(this).removeClass('Active');
				}
			});
		}

		$('#SearchBoxInputArea > .SearchForm').each(function(i) {
			if(i == index)
				$(this).addClass('Active');
			else
				$(this).removeClass('Active');
		});
	});
	
	$('#SearchBoxInputArea > .SearchForm > form input').keypress(function(e) {
		if(e.which == 13)
			$(this).closest('form').submit();
	});

	$('#SearchBoxInputArea > .SearchForm > form div.CountySelect input:checkbox').click(function(e) {
		if($(this).attr('checked') && $('#SearchBoxInputArea > .SearchForm.Active > form div.AreaSelect input:checked').length > 0)
			return false;
			
		if($(this).is(':checked')) {
			$.ajax({ cache: true, url: '/area-map', data: { c: $(this).next('label:first').html(), n: $(this).siblings('input:checked').length + 1 }, dataType: 'script' });
		} else {
			$.ajax({ cache: true, url: '/area-map', data: { n: $(this).siblings('input:checked').length + 1 }, dataType: 'script' });
		}
	});

	$('#SearchBoxInputArea > .SearchForm > form div.AreaSelect input:checkbox').live('click', function() {
		var cityName = $(this).next('label:first').html();
		if(cityName.indexOf(' (') != -1)
			cityName = cityName.substring(0, cityName.indexOf(' ('));
		cityName = cityName.replace(/\s+/g, '').toLowerCase();
	
		var checked = $(this).is(':checked');
		$('#AreaMap > ul > li').each(function() {
			var mapCityName = $(this).attr('id');
			mapCityName = mapCityName.substring(0, mapCityName.indexOf('City'));
			if(cityName == mapCityName.toLowerCase()) {
				if(checked) 
					$(this).addClass('Selected');
				else
					$(this).removeClass('Selected');
			}
		});
	});
	
	$('#SearchBoxInputArea .SearchForm form').submit(function(e) {
		$('#SearchBoxInputArea div.SearchButtonSpinner').show();
		$('#ListingSummaries').html('<div class="Spinner"></div>')

		var map = $('#ListingMap').data('map');
		map.clearOverlays();
		
		$('#SaveSearchBubble > .Messages')
			.hide()
			.html('');
		$('#SaveSearchBubble > form input[type=text]').val('');
		$('#SaveSearchBubble > form').show();
		
		$('#SearchBoxNavLinks > ul > li').each(function(i) {
			if($(this).hasClass('Active'))
				$('#SearchResults').data('resultsForTabIndex', i);
		});
		$.ajax({ cache: true, url: $(this).attr('action'), data: $(this).serialize(), dataType: 'script' });
		e.preventDefault();
	});
	
	$('#SearchBoxInputArea .SearchForm .SearchButton')
		.hover(function() { $(this).addClass('Hover'); }, function() { $(this).removeClass('Hover'); })
		.click(function(e) {
			$(this).parents('form').trigger('submit');
		});
	
	$('#SearchBoxInputArea form .ClearButton').click(function(e) {
		var forms = $('#SearchBoxInputArea form');
		forms.find('select, input[type=text]').val('');
		forms.find('input[type=checkbox]').attr('checked', false);
		
		$('#SearchBoxInputArea div.CountySelect').scrollTop(0);
		
		$.ajax({ cache: true, url: '/area-map', dataType: 'script' });
	});
	
	$('#ListingSummaries a.SaveSearchLink').live('click', function(e) {
		e.preventDefault();
		e.stopImmediatePropagation();
		
		if($('#SaveSearchBubble:visible').length > 0)
			return; 

		$('#SaveSearchBubble')
			.css({
				left: $(this).offset().left - 35,
				top: $(this).offset().top + $(this).height() + 2
			})
			.show()
			.click(function(e) { e.stopPropagation(); });

		$(document).one('click', function(e) {
			$('#SaveSearchBubble').hide();
		});
	});
	
	$('#SaveSearchBubble form').submit(function(e) {
		e.preventDefault();
		
		$.ajax({ cache: true, url: '/save-search', data: { n: $('#SaveSearchName').val(), q: $('#SearchBoxInputArea > .SearchForm.Active > form').serialize() }, dataType: 'script' });
	});
	
	$('#SaveSearchBubble button.Cancel').click(function(e) {
		e.preventDefault();
		
		$(document).trigger('click');
	});
	
	$('#SearchBoxInputArea a.ViewSavedResultsLink').live('click', function(e) {
		e.preventDefault();
		e.stopImmediatePropagation();
		
		if($('#SavedSearchesBubble:visible').length > 0)
			return; 

		$('#SavedSearchesBubble')
			.css({
				left: $(this).offset().left - 35,
				top: $(this).offset().top + $(this).height() + 2
			})
			.show()
			.click(function(e) { e.stopPropagation(); });

		$(document).one('click', function(e) {
			$('#SavedSearchesBubble').hide();
		});
	});
	
	$('#ListingSummaries > ul > li a.ShowInMap').live('click', function(e) {
		e.preventDefault();
		
		var summary = $(this).closest('#ListingSummaries > ul > li');
		var marker = summary.data('marker');
		$('#ListingMap').data('map').setCenter(marker.getLatLng(), 15);

		$('#ListingSummaries > ul > li.Active').removeClass('Active');
		summary.addClass('Active');
	});
	
	$('#ListingSummaries > .Controls > .NextPage > a, #ListingSummaries > .Controls > .PreviousPage > a').live('click', function(e) {
		e.preventDefault();
		
		var map = $('#ListingMap').data('map');
		map.clearOverlays();
		$('#ListingSummaries').html('<div class="Spinner"></div>')
		
		$.ajax({ cache: true, url: $(this).attr('href'), dataType: 'script' });
	});
	
	var toggleSideOfTown = function(className) {
		var checked = $('ul#MetroAreaMap > li.Selected.' + className).length == 0;
		$('#SearchBoxInputArea fieldset.Location div.Column.Area div.AreaSelect > input.' + className + ':checkbox').each(function() {
			$(this).attr('checked', checked);
		});
		$('#MetroAreaMap li.' + className).each(function() {
			if(checked)
				$(this).addClass('Selected');
			else
				$(this).removeClass('Selected');
		});
	};
	$('#AreaMapControlContainer .AreaMapAllWest').click(function() { toggleSideOfTown('West'); });
	$('#AreaMapControlContainer .AreaMapAllEast').click(function() { toggleSideOfTown('East') });
	
	$('#AreaMapGoBack').click(function(e) {
		e.preventDefault();
		$.ajax({ cache: true, url: $(this).attr('href'), dataType: 'script'});
	});

	$('#CountiesAreaMap > li > a').live('click', function(e) {
		e.preventDefault();
		
		var enabling = !$(this).parent().hasClass('Selected');
		if(enabling)
			$(this).parent().addClass('Selected');
		else
			$(this).parent().removeClass('Selected');
		
		var countyName = $(this).closest('ul#CountiesAreaMap li').attr('id');
		$('#SearchBoxInputArea .CountySelect > label').each(function() {
			if(countyName.toLowerCase() == $(this).html().replace(/ /g, '').toLowerCase()) {
				var checkbox = $(this).prev('input:checkbox:first');
				if(enabling)
					checkbox.attr('checked', true);
				else
					checkbox.attr('checked', false);
				
				var pos = checkbox.position();
				var parentPos = checkbox.parent().position();
				checkbox.parent().animate({ scrollTop : (pos.top - parentPos.top + checkbox.parent().scrollTop()) }, 'slow');
			}
		});
		
		var countyCount = $('#SearchBoxInputArea > .Active.SearchForm .CountySelect > input:checked').length;
		if(countyCount == 1)
			$.ajax({ cache: true, url: '/area-map', data: { c: $(this).closest('ul').find('li.Selected:first').attr('id'), n: countyCount }, dataType: 'script' });
	});
	
	$('#CountyAreaMap > li > a').live('click', function(e) { 
		e.preventDefault();

		var liElement = $(this).closest('li');
		if(liElement.hasClass('MadisonMap')) {
			$.ajax({ cache: true, url: '/area-map', data: { m: $(this).html() }, dataType: 'script'});
			return;
		}
		
		var cityName = $(this).html().replace(/<br.*>/, ' ');
		var cityCheckboxes = [ ];
		$('#SearchBoxInputArea .AreaSelect input:checkbox').each(function() {
			var html = $(this).next('label:first').html();
			if(html.length >= cityName.length && html.substr(0, cityName.length).toLowerCase() == cityName.toLowerCase())
				cityCheckboxes.push($(this));
		});
		
		if(liElement.hasClass('Selected')) {
			liElement.removeClass('Selected');
			$(cityCheckboxes).each(function() { $(this).attr('checked', false); });
		} else {
			liElement.addClass('Selected');
			$(cityCheckboxes).each(function() { $(this).attr('checked', true); });
		}
		
		var firstCheckbox = cityCheckboxes[0];
		var pos = firstCheckbox.position();
		var parentPos = firstCheckbox.parent().position();
		firstCheckbox.parent().animate({ scrollTop : (pos.top - parentPos.top + firstCheckbox.parent().scrollTop()) }, 'slow');
	});
	
	$('#MetroAreaMap > li > a').live('click', function(e) {
		e.preventDefault();
		
		var liElement = $(this).closest('li');
		var areaCode = liElement.attr('id').replace(/Madison/, '');
		var checkbox = $('#Area' + areaCode);
		if(liElement.hasClass('Selected')) {
			liElement.removeClass('Selected');
			checkbox.attr('checked', false);
		} else {
			liElement.addClass('Selected');
			checkbox.attr('checked', true);
		}
		
		var pos = checkbox.position();
		var parentPos = checkbox.parent().position();
		checkbox.parent().animate({ scrollTop : (pos.top - parentPos.top + checkbox.parent().scrollTop()) }, 'slow');
	});
	
	$('#SortBy').live('change', function(e) {
		$(this).closest('form').trigger('submit');
	});
	$('#ListingSummaries > .Controls > .SortControl > form').live('submit', function(e) {
		e.preventDefault();

		$('#ListingSummaries').html('<div class="Spinner"></div>')
		var map = $('#ListingMap').data('map');
		map.clearOverlays();

		$.ajax({ cache: true, url: $(this).attr('action'), data: $(this).serialize(), dataType: 'script' });
	});
	
	$('#ListingSummaries > ul > li a.ListingLink').live('click', function(e) {
		e.preventDefault();
		
		var windowName = (new Date()).getTime();
		if(window.resultWindows === undefined)
			window.resultWindows = { };
		
		var index = $('#ListingSummaries > ul > li').index($(this).closest('li'));
		window.resultWindows[windowName] = {
			searchKey: $('#ListingSummaries').data('searchKey'),
			offset: $('#ListingSummaries').data('startingOffset') + index
		};
		
		window.open($(this).attr('href'), windowName);
	});

	if(GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("ListingMap"));
		map.setCenter(new GLatLng(43.06788453128748, -89.40055847167969), 8);
		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		$('#ListingMap').data('map', map);
	}

	$(document.body).unload(function() {
		if(GBrowserIsCompatible()) {
			GUnload();
		}
	});
	
	$.ajax({ url: '/update-saved-searches', dataType: 'script' });
});
