var formSubmitTO;
var formCollection = new Object();
var compareTooManyMsg = 'You have selected too many properties to compare. Please reduce your selection to a maximum of 5 properties to compare.';
var compareTooFewMsg = 'You have selected too few properties to compare. Please increase your selection to a maximum of 5 properties to compare.';
	
function sendXHR(){
	clearTimeout(formSubmitTO);
	formSubmitTO = setTimeout(formProc, 800);
}

function formProc(){
	
	// Populate the Loading bar
	$('#properties').html($('#propertiesLoading').html());
	
	// Indicate this is an AJAX post
	formCollection.ajaxPostSortResults = true;
	$('#ajaxCalled').val('true');

	$(':hidden',$('#filters-form')).each(function(){
		var dataName = $(this).get(0).name;
		if(dataName) {
			formCollection[dataName] = $(this).val();
		}
	});
	$(':checkbox',$('#filters-form')).each(function(){
		if($(this).get(0).checked == true){
			var dataName = $(this).get(0).name;
			formCollection[dataName] = $(this).val();
		} else {
			var dataName = $(this).get(0).name;
			formCollection[dataName] = "";
		}
	});
	$('select',$('#filters-form')).each(function(){
		var dataName = $(this).get(0).name;
		formCollection[dataName] = $(this).val();
	});
	
	var action = $('#filters-form').get(0).action;
	if (action.indexOf('#') > 0) {
		action = action.substring(0, action.indexOf('#'));
	};

	var requestType;
	// DE8635: Safari 4 on Windows displays the listing sort page
	// incorrectly and throws a Maximum stack size exceeded.
	if ($.browser.safari) {
		requestType = 'POST';
	} else {
		requestType = 'GET'
	}
	
	$.ajax({
		url: action,
		type: requestType,
		data: formCollection,
		// Timout at 10 seconds
		timeout: 10000,
		success: handleData,
		error: handleError,
		dataType: 'html'
	});
	
	return false;
}

var handleData = function(data) {
	$('#properties').html(data);
	makeResultsClickable();
	// Ugly Tab hack to handle changing result size
	// Ugly IE hack to handle changing result size
	var belowDiv = $('#belowResults');
	if (belowDiv) {
		belowDiv.removeClass('zoom1');
		belowDiv.addClass('zoom1');
	}
	// Show delayed thumbnails
	showThumbnails();
}

function showThumbnails() {
	// Show delayed thumbnails
	$('img.delayedImg').each(function() {
	    $(this).attr('src', $(this).attr('longdesc'));
	    $(this).removeClass('delayedImg');
	});
}

var handleError = function() {
	$('#properties').html($('#propertiesError').html());
	// Ugly IE hack to handle changing result size
	var belowDiv = $('#belowResults');
	if (belowDiv) {
		belowDiv.removeClass('zoom1');
		belowDiv.addClass('zoom1');
	}
}

function backToFilteredResults() {
    // If Back was used post-AJAX, run the AJAX
    if ($('#ajaxCalled').val() == 'true') {
    	if ($('#orderBy').val() != '') {
    	  updateSortBarDisplay($('#orderBy').val(), $('#direction').val());
    	}
    	formProc();
    }
}

function updateRateRangeSlider(keepValues) {
	var period = $('#filterByPeriod').val();
	var range = $('#raterange');
	if (period == '1') {
		range.slider('enable');
		resizeRatesSlider(0, 500, 50, keepValues);
	} else if (period == '7' || period == '28') {
		range.slider('enable');
		resizeRatesSlider(0, 4000, 250, keepValues);
	} else {
		range.slider('disable');
		resizeRatesSlider(0, 4000, 250, keepValues);
	}
}

function resizeRatesSlider(min, max, step, keepValues) {
	var range = $('#raterange');
	var rangeVal = $('#raterange-val');
	
	range.slider('option', 'min', min);
	range.slider('option', 'max', max);
	range.slider('option', 'step', step);
	range.slider('option', 'slide', createSlideFunc(rangeVal, min, max));

	range.children('.min-label').text('$' + min);
	range.children('.mid-label').text('$' + ((max - min) / 2));
	range.children('.max-label').text('$' + max + '+');

	var minVal = min;
	var maxVal = max;
	if (keepValues == true) {
		minVal = rangeVal.children('.min-in').val(); 
		maxVal = rangeVal.children('.max-in').val();
	} else {
		range.slider('values', 0, min);
		range.slider('values', 1, max);
		rangeVal.children('.min-range').val(min); 
		rangeVal.children('.max-range').val(max);
	}
	
	updateSliderValues($('#raterange-val'), minVal, maxVal, min, max);
}

function createSlideFunc($sliderval, rangeMin, rangeMax) {
	return function() {
		var values = $(this).slider('option', 'values');
		var val1, val2;
		if (values[0] <= values[1]) {
			val1 = values[0];
			val2 = values[1];
		} else {
			val1 = values[1];
			val2 = values[0];
		}
		val1 = Math.round(val1 * 10) / 10;
		val2 = Math.round(val2 * 10) / 10;
		
		updateSliderValues($sliderval, val1, val2, rangeMin, rangeMax);
	};
}

function updateSliderValues($sliderval, min, max, rangeMin, rangeMax) {
	
	var minText = min;
	var maxText = max;
	if (max == rangeMax) {
		maxText = '' + max + '+';
	}
	
	$sliderval.children('.min').text(minText);
	$sliderval.children('.min-in').val(min); 
	$sliderval.children('.max').text(maxText);
	$sliderval.children('.max-in').val(max);
}

function orderByClick() {
	var orderByName = $(this).get(0).name;
	
	// Default to 'up' or ascending order
	var sortDirection = ($(this).hasClass('sorted_down')) ? 'up' : ($(this).hasClass('sorted_up')) ? 'down' : ($(this).hasClass('default_down')) ? 'down' : 'up';
	var orderByDirection = (sortDirection == 'up') ? 'ASC' : 'DESC';
	
	// Set the inputs
	$('#orderBy').val(orderByName);
	$('#direction').val(orderByDirection);
	
	updateSortBarDisplay(orderByName, orderByDirection);
}

function updateSortBarDisplay(orderByName, orderByDirection) {
	// Clear current selection
	$(':submit', $('#sortbar')).removeClass('sorted_down').removeClass('sorted_up').removeClass('orange-txt').addClass('blue-txt');
	
	// Find correct button and flag it
	if ($('#'+orderByName)) {
		var sortDirection = (orderByDirection == 'ASC') ? 'up' : 'down';
		$('#'+orderByName).removeClass('blue-txt').addClass('orange-txt').addClass('sorted_'+sortDirection);
	}
}

function makeResultsClickable() {
	$('.property').click(function(){
		document.location.href = $(this).children('a').attr('href');
	});
	$('.compareSelect').click(function(event) {
		event.stopPropagation();
	});
}

function findCompareListings() {
	var listingIds = '';
	var checkedListings = 0;
	$('input:checkbox:checked[name=\'compareListings\']').each(function() {
	  checkedListings++;
	  listingIds = listingIds + '&listingIds=' + $(this).val();
	});
	if (checkedListings < 2) {
		alert(compareTooFewMsg);
	} else if (checkedListings > 5) {
		alert(compareTooManyMsg);
	} else {
		sendCompareOmniture();
		document.location.href = '/compare.htm?' + listingIds.substring(1);
	}
	return false;
}

function sendCompareOmniture() {
	if (!(window.s === undefined)) {
		var s=s_gi(s_account);
	    s.linkTrackVars='events';
	    s.linkTrackEvents='event27';
	    s.events='event27';
		s.tl(this, 'o', 'Compare Listings');
	    return true;
	}
}

$(document).ready(function(){
	$('.sliders').each(function(){
		var $sliderval = $(this).get(0).id + '-val';
			$sliderval = $('#'+$sliderval);
		var _step = $('#'+ $(this).get(0).id + '-step');
			_step = (_step.length > 0) ? parseFloat(_step.val()) : 1;
			
		var minValIn = $sliderval.children('.min-in').val();
		var minVal;
		var rangeMin = parseFloat($sliderval.children('.min-range').val());
		if (minValIn == '') {
			minVal = rangeMin;
		} else {
			minVal = parseFloat(minValIn);
		}
		
		var maxValIn = $sliderval.children('.max-in').val();
		var maxVal;
		var rangeMax = parseFloat($sliderval.children('.max-range').val());
		if (maxValIn == '') {
			maxVal = rangeMax;
		} else {
			maxVal = parseFloat(maxValIn);
		}
		
		$(this).slider({
			stop:sendXHR, 
			slide:createSlideFunc($sliderval, rangeMin, rangeMax), 
			min:rangeMin, 
			max:rangeMax, 
			step: _step,
			values:[minVal, maxVal],
			range:true
		});

		var values = $(this).slider('option', 'values');
		var val1, val2;
		if (values[0] <= values[1]) {
			val1 = values[0];
			val2 = values[1];
		} else {
			val1 = values[1];
			val2 = values[0];
		}
		val1 = Math.round(val1 * 10) / 10;
		val2 = Math.round(val2 * 10) / 10;

		updateSliderValues($sliderval, val1, val2, rangeMin, rangeMax);
	});
	
	$(':checkbox',$('#filters-form')).each(function(){
		$(this).bind('click', sendXHR);
	});
	$('select',$('#filters-form')).each(function(){
		$(this).bind('change', sendXHR);
	});

	$(':submit', $('#sortbar')).click(orderByClick);
	
	$('#filterByPeriod').change(updateRateRangeSlider);
	updateRateRangeSlider(true);

	$('#filters-form').submit(formProc);
	
	$('#compareButton').click(findCompareListings);
	
	makeResultsClickable();
	
	// Check if this is from the 'back' button, if so, re-filter.
	backToFilteredResults();
	
	if(jQuery.browser.msie) {
		$('.property').mouseover(function(){
			if ($(this).hasClass('deal')) {
				$(this).addClass('over-deal');
			}
			$(this).addClass('over');
		}).mouseout(function(){
			$(this).removeClass('over-deal');
			$(this).removeClass('over');
		});
	}
	
	// Show delayed thumbnails
	showThumbnails();
	
	$('#periodFilterHelp').tooltip({
        showURL: false
    });
});