var formSubmitTO;
var formCollection = new Object();
var backcheck = false;
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(){
	
	// 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();
	});

	$(':text',$('#filters-form')).each(function(){
		var dataName = $(this).get(0).name;		
		formCollection[dataName] = (($(this).val() == 'check-in' || $(this).val() == 'check-out') ? "" : $(this).val());
	});
	var action = $('#filters-form').get(0).action;
	
	// DE26773 IE7 returns '#' as action and with jquery min upgrade to 1.7, ajax was not working.
	// so updated the action when it equals to '#'
	if(action == '#') {
		action = window.location.href;
	}
	if (action.indexOf('#') > 0) {
		action = action.substring(0, action.indexOf('#'));
		
	};
	
	// This param is added to make ajax request url different than page url
	// to fix IE8 issue DE26173
	action  = action + "&test=test";
		
	if (formCollection['filterCheckin'] && formCollection['filterCheckout'] && Date.parse(formCollection['filterCheckin']) >= Date.parse(formCollection['filterCheckout'])){		
		alert("Checkin Date must be before Checkout Date");
		return false;		
	}
	
	setSendOmnitureDate();
	
	// Populate the Loading bar
	$('#properties').html($('#propertiesLoading').html());
	
		
	$.ajax({
		url: action,
		type: 'POST',
		data: formCollection,
		// Timout at 60 seconds
		timeout: 60000,
		success: handleData,
		error: handleError,
		dataType: 'html'
	});
	
	checkincookie = $.cookie("filterCheckin");
	checkoutcookie = $.cookie("filterCheckout");
	$.cookie("dateUpdated", "", { path: '/' });
	 
	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();
	if(backcheck && $.cookie("LISTING_SCROLLTOP") != null && $.cookie("LISTING_SCROLLTOP") != ''){
		//alert('final if scroll position '+$.cookie("LISTING_SCROLLTOP") + '  '+backcheck);
		window.scroll(0, $.cookie("LISTING_SCROLLTOP"));
		
	}
	else{
		clearScrollCookie();
	}
	backcheck = false;
}

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');
	}
	clearScrollCookie();
	backcheck = false;
}

function clearScrollCookie(){
	
	if($.cookie("LISTING_SCROLLTOP") != null && $.cookie("LISTING_SCROLLTOP") != ''){
    	$.cookie("LISTING_SCROLLTOP", '', {
			path : '/vacation-rentals/'
		});
	}
}


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

function createSlideFunc($sliderval, rangeMin, rangeMax) {
	return function( event, ui ) {
		var val1 = ui.values[0];
		var val2 = ui.values[1];
		if (val2 <= val1) {
			var temp = val1;
			val1 = val2;
			val2 = val1;
		}
		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('always_up')) ? 'up' :($(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).hasClass('always_up')) ? $('#'+orderByName).removeClass('blue-txt').addClass('orange-txt') : $('#'+orderByName).removeClass('blue-txt').addClass('orange-txt').addClass('sorted_'+sortDirection);
		
	}
}

function makeResultsClickable() {
	$('.powh').click(function(){
		sendContainerClickedOmniture('SR', 'R1', 'C1');
		document.location.href = $('a.title', $(this)).attr('href');
	});
	$('.property').click(function(){
		document.location.href = $('a.title', $(this)).attr('href');
		// Attaching car-rentals popunder
		if(typeof(handleCarRentalsPopunder) != "undefined") {			
			handleCarRentalsPopunder($('a.title', $(this)));			
		}
	});
	$('.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)) {
		//As we are loading third party libraries after dom load
		//It might be case when before Omniture gets loaded, this event get fired
		//causing javascript error, just exiting silently in that case
		var s;
		try{
			s=s_gi(s_account);
		} catch(err){
			return;
		}
	    s.linkTrackVars='events';
	    s.linkTrackEvents='event27';
	    s.events='event27';
		s.tl(this, 'o', 'Compare Listings');
	    return true;
	}
}

function processFilterSearchSubmit() {
	
	$('#filter-search-form-checkin').val($('#filterCheckin').val());
	$('#filter-search-form-checkout').val($('#filterCheckout').val());
	$('#filter-search-form-params').val($('#filters-form').serialize());
	
	// This cookie is used to tell that this is a fresh search. 
    // Changes done to resolve issue: search austin and then again search for austin.
    // For this case search params are going for first search but for second search
    // page is loaded from cache causing search params not being sent.
    $.cookie("VR_OMNITURE_MULTISEARCH", "NewSearch", {
		path : '/vacation-rentals/'
	});
	
	return true;
}

$(document).ready(function(){
	
	// --- input tip --- //
	
	dateFields('#filterCheckin', '#filterCheckout', { callFormSubmit : true });

	// --- sliders --- //
	$('.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);	

	$('#filters-form').submit(formProc);
	
	
	$('#compareButton').click(findCompareListings);
	
	$('#properties').click(function() {
		var st = $(window).scrollTop();
		//alert('writing var cookie '+st);
		$.cookie("LISTING_SCROLLTOP", st, {
			path : '/vacation-rentals/'
		});
	});
	
	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');
		});
		$('.powh').mouseover(function(){
			$(this).addClass('over');
		}).mouseout(function(){
			$(this).removeClass('over');
		});
	}
	
	// Show delayed thumbnails
	showThumbnails();
	
	$('#periodFilterHelp').tooltip({
        showURL: false
    });
	
	initFilterSearchBox();
	

});

function initFilterSearchBox() {
	// If you change this string, also change the constant
	// SearchController.DEFAULT_SEARCH_TEXT	 
	var defaultSearch = "destination or listing ID";
	
	var searchBox = $("#filterSearchbox");
		
	searchBox.focus(
			function (e) {
				if (searchBox.val() === defaultSearch) {
					searchBox.val("");
					searchBox.removeClass("gray-txt").addClass("black-txt");
				}
			}
		);
	searchBox.blur( 
			function (e) {
				if (searchBox.val() === "") {
					searchBox.val(defaultSearch);
					searchBox.removeClass("black-txt").addClass("gray-txt");
				}
			}
		);
	
	searchBox.autocomplete("/search/autocomplete.htm", {
		delay: 100,
		minChars: 3, 
		max: 9,
		highlight: false,
		cacheLength: 10,
		matchSubset: false,
		width: 172,
		extraParams: { displayCount: 'true'}
	});
		
	$('#filter-search-form').submit(processFilterSearchSubmit);
	
	if ($('#orderBy').val() != '') {
  	  updateSortBarDisplay($('#orderBy').val(), $('#direction').val());
  	}
	
}

