$(document).ready(function(){ // document ready
	
	geo = new GClientGeocoder();
	
	reasons[G_GEO_SUCCESS]            = "Success";
	reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address";
	reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address.";
	reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address";
	reasons[G_GEO_BAD_KEY]            = "Bad API Key";
	reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries";
	reasons[G_GEO_SERVER_ERROR]       = "Server error";

/* PROPERTY VIEW */

  $(document).trigger('live-property-view');

	$(".thumbs li")
		.live("click",function(){
			$(this).siblings().removeClass("active");
			$(this).addClass("active");
			
			var src = $(this).find("img").attr("src");
			var gallery = $(this).parents("div.gallery");
			var widthHeight = gallery.hasClass("main-gallery") ? '?width=360&height=240' : '?width=240&height=160';
			var mainSrc = src.slice(0, src.indexOf("?")) + widthHeight;
			var imageHolder = gallery.find(".main-image");
			var currentImage = imageHolder.find("img");
			
			$("<img />").attr('src', mainSrc).hide().appendTo(imageHolder).fadeIn();
			currentImage.fadeOut(function(){
				$(this).remove();
			});
		});

/* PROPERTY RESULTS */
	
	$("#search-filters-list input:text").floatLabel();
	
	$("#property-list > ul li")
		.live('mouseover', function(){ $(this).addClass('hover'); })
		.live('mouseout', function(){ $(this).removeClass('hover'); }) 
	;
		
	$("#property-list > ul li a, #property-list > ul li").live('click', function(){
		var url = $(this).is('a') ? $(this).attr('href') : $(this).find('a').attr('href');
		$.get(url, function(response){
			if ($("#property-view").length > 0) {
				$("#property-view").replaceWith(response);
				$("#overlay").fadeIn(function(){
					$(this).css('opacity', 0.2);
				});
			} else {
				$("<div />").attr('id','overlay').prependTo(document.body);
				$(document.body).prepend(response);
			}
			$("#property-view").css('top', $(window).scrollTop());
		}, 'html');
		return false;
	});
	
/* PROPERTY SEARCH */
	
	var count = $("#search-filters-list li").length;
	$("#search-filters-list li").each(function(i){
		var linksDiv = $('<div class="quick-links"></div>');
		
		if (i>0) {
			$('<a href="#">Prev</a>')
				.click(function(){
					var activeItem = $(this).parents('li:first')[0];
					var index = $("#search-filters-list > li").index(activeItem);
					$("#search-filters-list").accordion('activate', index-1);
					return false;
				})
				.appendTo(linksDiv);
			$(linksDiv).append(' | ');
		}
		
		if (i<(count-1)) {
			$('<a href="#">Next</a>')
				.click(function(){
					var activeItem = $(this).parents('li:first')[0];
					var index = $("#search-filters-list > li").index(activeItem);
					$("#search-filters-list").accordion('activate', index+1);
					return false;
				})
				.appendTo(linksDiv);
		}
		
		$("div.content", this).append(linksDiv).append('<span class="break"></span>');
	});
	
	// link switcher for search by filter or name
	$('#search-switch-link').toggle(function(){
		$('#search-filters, #search-filters-nav').hide();
		$('#search-name').fadeIn();
		$(this).html('Search by Filters');
		return false;
	}, function(){
		$('#search-name').hide();
		$('#search-filters, #search-filters-nav').fadeIn();
		$(this).html('Search by Name');
		return false;
	});
	
	// clear all input filters
	$("#filter-clear a").click(function(){
		$("#search-filters, #search-name").clearForm();
		clearSliders();
		return false;
	});
	
	$("#filter-active a").click(function(){
		$("#search-filters-list").accordion('activate', 4);
		return false;
	});
	
	// toggle filter list
	$("#search-filters-list").accordion({
		header: '.tab',
		autoHeight: false
	});
	
/* SEARCH FILTER SLIDERS */

	var filtersWidth;
	$("#filter-results").css({ cursor: "pointer" })
		.toggle(
			function(){ 
				$("#property-list ul").css({ marginRight:50 });
				$("#search-filters").width(0);
				$("#search-filters-wrap").css({ marginRight:0 });
				$("#search-filters-list").hide();
			},
			function(){ 
				$("#property-list ul").css({ marginRight:230 });
				$("#search-filters").width(180);
				$("#search-filters-wrap").css({ marginRight:12 });
				$("#search-filters-list").show();
			}
		);

	$(window).bind("scroll", function(){
		if ( $(window).scrollTop() > 288 ) {
			var windowTop = $(window).scrollTop() - 275;
			$("#search-filters-wrap").css({ position:"absolute", top:windowTop, right:0 });
		} else {
			$("#search-filters-wrap").css({ top:0 });
		}
	});
	
	// remove null options	
	$("#search-filters-list select").not("#PropertyState").each(function(){
		var option = $(this).find("option:first");
		if (option.text() === "") option.remove();
	});
	
	$.ui.slider.defaults['stop'] = function() {
		loadResults();
	}
	
	$.ui.slider.defaults['orientation'] = "horizontal";
	
	// Initialize Sliders
	if ($("#PropertyRadius").val() == 1)
		$("#PropertyRadius").val(10);
	$("#PropertyRadius").hide()
		.selectToUISlider({ labels: 6 });
		
	if ($("#UnitTypeDepositMax").val() == 0)
		$("#UnitTypeDepositMax").find('option:last').attr('selected','selected');
	$("#UnitTypeDepositMax").hide()
		.selectToUISlider({ labels: 6 });
		
	$("#OptionLeaseTerm").hide()
		.selectToUISlider({ labels: 3, labelSrc:'value' });
	
	rangeSlider({ labelText:"Rent Range", tics:5, labelSrc:"value",
		minField:"#UnitTypeRentMin", maxField:"#UnitTypeRentMax" });
	rangeSlider({ labelText:"Bedrooms Range", tics:3, labelSrc:"text",
		minField:"#UnitTypeBedroomsMin", maxField:"#UnitTypeBedroomsMax" });
	rangeSlider({ labelText:"Bathrooms Range", tics:5, labelSrc:"value",
		minField:"#UnitTypeBathroomsMin", maxField:"#UnitTypeBathroomsMax" });
	rangeSlider({ labelText:"Square Footage Range", tics:5, labelSrc:"value",
		minField:"#UnitTypeSquareFootageMin", maxField:"#UnitTypeSquareFootageMax" });

	function rangeSlider(options) {
		$(options.minField)
			.parent().hide();
		if ($(options.maxField).val() == $(options.maxField).find('option:first').val())
			$(options.maxField).find('option:last').attr('selected','selected')
		$(options.maxField)
			.prev().html(options.labelText);
		$(options.minField+", "+options.maxField).hide()
			.selectToUISlider({ labels:options.tics, "labelSrc":options.labelSrc });
	}
	
/* AJAX EVENTS */
	
	$("#search-filters input").change(function(){
		loadResults();
	});
	
	$("#search-filters").submit(function(){
		geocode();
		loadResults();
		return false;
	});
	
	if ( $("#PropertyAddress").val() != "" ) {
		address = $("#PropertyAddress").val();
		geo.getLocations(address, function (result){
			if (result.Status.code == G_GEO_SUCCESS) {
				geocode = result.Placemark[0].Point.coordinates;
				$("#PropertyLatitude").val(geocode[1]);
				$("#PropertyLongitude").val(geocode[0]);
			}
		});
	}
	
	$("#PropertyIndexForm").submit(function(){
		if (address != $("#PropertyAddress").val()) {
			// we have a new address
			address = $("#PropertyAddress").val();
			geo.getLocations(address, function (result){
				if (result.Status.code == G_GEO_SUCCESS) {
					geocode = result.Placemark[0].Point.coordinates;
					$("#PropertyLatitude").val(geocode[1]);
					$("#PropertyLongitude").val(geocode[0]);
					loadResults();
				} else {
					var reason="Code "+result.Status.code;
					if (reasons[result.Status.code]) {
						reason = reasons[result.Status.code]
					} 
					alert(reason);
					geocode = false;
				}
			});
		} else {
			loadResults();
		}
		return false;
	});
	
}); // end document ready

/* PUBLIC FUNCTIONS */

var address = "";
var geo;
var reasons = [];

	function loadResults() {
		var form = $("#search-filters");
		$.post(form.attr('action'), form.serializeArray(), function(response){
			$("#property-list").replaceWith(response);
			if ( $(window).scrollTop() > 288 ) {
				$(window).scrollTop(284);
			}
		});
	}

	function clearSliders() {
		$("select[id$='Min']").each(function(){
		 	$(this)	
			.find('option:first').attr('selected','selected').end()
			.trigger('change');
		});
	
		$("select[id$='Max']").each(function(){
		 	$(this)	
			.find('option:last').attr('selected','selected').end()
			.trigger('change');
		});
	}
