$(function() {
    //init search tabs
    $('#search-shell').tabs({fx: {opacity: 'toggle', duration: 'fast'}});
    geocoder = new google.maps.Geocoder();
    //init result tabs for both views and map tabs for the map view
    $('.results-shell').tabs({
    	show: function(event, ui) {
    		var selected = $(".results-shell").tabs("option","selected");
    	}
    });
    $('.map-view-map').tabs();

    //set first location as current
    $('.loc-types li:first-child').children('a').addClass('current-loc');

    //on click, change current location
    $('.loc-types').children('li').click(function(){
        var liY = $(this).position().top;
        $(this).siblings().children('a').removeClass('current-loc');
        $(this).children('a').addClass('current-loc');
        $(this).parent().stop().animate({backgroundPosition: '0 ' + liY + 'px'}, 200);
        return false;
    });

    //show and hide functionality for search shell
    $("#show-search-link").toggle(
        function(){
            $('#search-content').slideUp('fast');
            $(this).html('show criteria');
            return false;
        },
        function(){
            $('#search-content').slideDown('fast');
            $(this).html('hide criteria');
            return false;
        }
    );

    //allow clicking tab to expand content if it's hidden
    $('#search-shell').children('.ui-tabs-nav').find('a').click(function() {
        if ($('#show-search-link').html() == 'show criteria') {
            window.setTimeout("$('#show-search-link').trigger('click');", 200);
        }
        //move the property type checkboxes into the active tab
        $($(this).attr('href')).append($('#property-types').detach());
        return false;
    });

    //show and hide functionality for options shell
    $('#show-options-link').toggle(
       function(){
            $('#bottom-options').slideDown('fast');
            $(this).html('hide criteria').css('background', 'url(http://www.z57.com/creative/idx2/images/control-090-small.png) no-repeat right center');
            return false;
       },
       function(){
            $('#bottom-options').slideUp('fast');
            $(this).html('more criteria').css('background', 'url(http://www.z57.com/creative/idx2/images/control-270-small.png) no-repeat right center');
            return false;
       }
    );

    //init view toggling buttons, setting list view as default (disables clicking)
    $('#toggle-view').buttonset().children('#map-view').button({disabled: true}).next().button({disabled: false});

	$('#map-view').click(function(){
		$('.list-view-results, .list-view-map').hide();
		$('.map-view-results, .map-view-map').show(0, function(){ 
			setTimeout("setupBigMap()", 500);
			$("#small_map_details_canvas").toggle();
			if($("#tab-details-2 div.details-info").length > 0){
				$("#map-view-details-map").append($("#small_map_details_canvas").detach());
				initializeDetailsMap();
			}
			return false;
		});
		$('#list-view').button({disabled: false});
		$('#map-view').button({disabled: true});
		currentView = 'map';
		$('.ajax-loader').hide(0);
	});
    $('#list-view').click(function(){
		$('.map-view-results, .map-view-map').hide();
		$('.list-view-results, .list-view-map').show(0, function(){ 
			setTimeout("checkSmallMap(false)", 500);
			if($("#tab-details-1 div.details-info").length > 0){
				$(".map").append($("#small_map_details_canvas").detach());
				initializeDetailsMap();
			}
			return false; 
		});
		$('#map-view').button({disabled: false});
		$('#list-view').button({disabled: true});
		currentView = 'list';
		$('.ajax-loader').hide(0);
    });

    //Bind 'live' events to links that open 'details' part of listing
    $('.listing-address a, .listing-thumbnail a, a.view-details-link', '.list-view-results').live('click', function(){
        $('.list-view-results').tabs('select', 1);
        return false;
    });
    $('.listing-address a, .listing-thumbnail a, a.view-details-link', '.map-view-results').live('click', function(){
        $('.map-view-map').tabs('select', 1);
        return false;
    });
    
    $(".tb-submit").live("click", function(){
    	$("#loginForm").submit();
    });
    
    $("#loginForm").live("submit", function(){
    	checkEmailLogin($('#tb-login-email').val());
		return false;
    });
    
    //feature table styling
    $('.details-panel').find('tr').children('td:even').css({'font-weight': 'bold', 'text-align': 'right'});

    //init sliders
    $( "#price-slider" ).slider({
            range: true,
            min: 0,
            max: 500000000,
            step: 500,
            values: [ 200000, 1000000 ],
			slide: function( event, ui ) {
				$( "#price-input-low" ).val( ui.values[0].toLocaleString().split(".")[0] );
				$( "#price-input-high" ).val( ui.values[1].toLocaleString().split(".")[0] );
				if(ui.value < 5000)
					$( "#price-slider" ).slider( "option", "step", 100 );
				else if(ui.value < 15000)
					$( "#price-slider" ).slider( "option", "step", 1000 );
				else if(ui.value < 100000)
					$( "#price-slider" ).slider( "option", "step", 10000 );
				else if(ui.value < 1000000)
					$( "#price-slider" ).slider( "option", "step", 25000 );
				else if(ui.value >= 1000000)
					$( "#price-slider" ).slider( "option", "step", 100000 );
            }
    });
    
    $("#price-input-low, #price-input-high").change(function (){
    	if(parseInt($('#price-input-high').val().replace(/(\.00$|[^0-9])/g,'')) < parseInt($('#price-input-low').val().replace(/(\.00$|[^0-9])/g,''))){
			$('#price-input-high').val("800,000");
			$('#price-input-low').val("200,000");
			displayStatusMsg("The Min Price needs to be lower than the Max Price.");
		}
		$("#price-slider").slider("values", 0, $('#price-input-low').val().replace(/(\.00$|[^0-9])/g,''));
		$("#price-slider").slider("values", 1, $('#price-input-high').val().replace(/(\.00$|[^0-9])/g,''));
	});
    
    $( "#sqft-slider" ).slider({
            range: true,
            min: 0,
            max: 15000,
            values: [ 0, 15000 ],
            slide: function( event, ui ) {
				$("#sqft-input-low").val(ui.values[0]);
				$("#sqft-input-high").val(ui.values[1]);
				if(ui.value < 1000)
					$( "#sqft-slider" ).slider( "option", "step", 100 );
				else if(ui.value < 5000)
					$( "#sqft-slider" ).slider( "option", "step", 500 );
				else if(ui.value <= 15000)
					$( "#sqft-slider" ).slider( "option", "step", 1000 );
            }
    });
    
    $("#sqft-input-low, #sqft-input-high").change(function (){
		if(parseInt($('#sqft-input-high').val()) < parseInt($('#sqft-input-low').val())){
			$('#sqft-input-high').val(0);
			$('#sqft-input-low').val(15000);
			displayStatusMsg("The Min Size needs to be lower than the Max Size.");
		}
		$("#sqft-slider").slider("values", 0, $('#sqft-input-low').val());
		$("#sqft-slider").slider("values", 1, $('#sqft-input-high').val());
	});
    
    $( "#lot-size-slider" ).slider({
            range: true,
            min: 0,
            max: 200000,
            values: [ 0, 200000 ],
            slide: function( event, ui ) {
				$( "#lot-size-input-low" ).val( ui.values[ 0 ] );
				$( "#lot-size-input-high" ).val( ui.values[ 1 ] );
				if(ui.value < 5000)
					$( "#lot-size-slider" ).slider( "option", "step", 100 );
				else if(ui.value < 50000)
					$( "#lot-size-slider" ).slider( "option", "step", 1000 );
				else if(ui.value <= 200000)
					$( "#lot-size-slider" ).slider( "option", "step", 5000 );
            }
    });
    
    $("#lot-size-input-low, #lot-size-input-high").change(function (){
		if(parseInt($('#lot-size-input-high').val()) < parseInt($('#lot-size-input-low').val())){
			$('#lot-size-input-high').val(0);
			$('#lot-size-input-low').val(15000);
			displayStatusMsg("The Min Size needs to be lower than the Max Size.");
		}
		$("#lot-size-slider").slider("values", 0, $('#lot-size-input-low').val());
		$("#lot-size-slider").slider("values", 1, $('#lot-size-input-high').val());
	});
    
    $("#lot-size-sqrft, #lot-size-acre").click(function(){
    	if(this.value == 'acre' && this.checked && lotSizeUnit != 'acre'){
    		lotSizeUnit = 'acre';
    		var lowVal = Math.max(0,parseFloat($("#lot-size-input-low").val()/43560).toFixed(1));
    		var highVal = Math.min(10,parseFloat($("#lot-size-input-high").val()/43560).toFixed(1));
    		$("#lot-size-slider").slider({
	            min: 0,
	            max: 10,
	            step: 0.1,
	            values: [ lowVal, highVal ],
	            slide: function( event, ui ) {
					$("#lot-size-input-low").val(ui.values[0]);
					$("#lot-size-input-high").val(ui.values[1]);
	            }
			});
			$("#lot-size-input-low").val(lowVal);
			$("#lot-size-input-high").val(highVal);
    	} else if(this.value == 'sqrft' && this.checked && lotSizeUnit != 'sqrft'){
    		lotSizeUnit = 'sqrft';
    		var lowVal = Math.max(0,parseInt($("#lot-size-input-low").val()*43560));
    		var highVal = Math.min(200000,parseInt($("#lot-size-input-high").val()*43560));
	    	$( "#lot-size-slider" ).slider({
	            min: 0,
	            max: 200000,
	            step: 500,
	            values: [ lowVal, highVal ],
	            slide: function( event, ui ) {
					$( "#lot-size-input-low" ).val( ui.values[ 0 ] );
					$( "#lot-size-input-high" ).val( ui.values[ 1 ] );
					if(ui.value < 5000)
						$( "#lot-size-slider" ).slider( "option", "step", 100 );
					else if(ui.value < 50000)
						$( "#lot-size-slider" ).slider( "option", "step", 1000 );
					else if(ui.value <= 200000)
						$( "#lot-size-slider" ).slider( "option", "step", 5000 );
	            }
			});
			$("#lot-size-input-low").val(lowVal);
			$("#lot-size-input-high").val(highVal);
    	}
    });
    
    $(".text-input").change(function(){
	    this.value = this.value.replace(/(\.00$|[^0-9])/g,'');
		if(this.id == 'price-input-high' || this.id == 'price-input-low')
			this.value = parseInt(this.value).toLocaleString().split(".")[0];
    });

    //I believe this will need to be fired every time the content in this are is reloaded (for each search)
    $("#result-message a").click(function() {
        if ($("#show-search-link").html() == "show") {
            $("#show-search-link").trigger('click');
        }
    });
    
    //this toggles text/list search
    $(".search-list-toggle").click(function(){
    	var geoLoc = $(this).closest('.geo-loc');
		$(geoLoc).children("p.typeLink").toggle();
		$(geoLoc).children("p.selectLink").toggle();
		$(geoLoc).children("div").children().toggle();
		$(geoLoc).children("select.searchList").toggle();
		return false;
    });
    
    $("p.listing-address a, a.view-details-link, .listing-thumbnail a").live("click", function(){
    	if(GetCookie('id')==null){
    		callDetails($(this).attr("obid"),$(this).attr("feed"),$(this).attr("source"));
    	}else{
    		getDetails($(this).attr("obid"),$(this).attr("feed"),$(this).attr("source"));
    	}
    });
    
    //this shows/hides the geography tab and loads the selects via ajax if needed
    $(".loc-type-switch").click(function(){
    	var current = $('.current-loc').attr("href");
    	var active = $(this).attr("href");
		$(current).hide();
    	$(active).show();
		loadList($(active).children("select.searchList"),$(active).attr("dataType"),$(active).attr("areaID"));
    });
    
    $(".addr-type-switch").click(function(){
    	var current = $('#tab-address').find('.current-addr');
    	var active = $(this).attr("href");
    	$(current).removeClass('current-addr');
    	$(':input.activeInput',$(current).attr('href')).each(function(){ 
    		$(this).removeClass('activeInput'); 
    	});
    	$(this).addClass('current-addr');
    	$(':input',$(this).attr('href')).each(function(){ 
    		$(this).addClass('activeInput');
    	});
		$($(current).attr("href")).hide();
    	$(active).show();
    	
    });
	
	$("#propertyTypeAllBox").click(function(){
		if(this.checked){
			$(".propertyTypeBox").each(function(){
				$(this).attr("checked",false);
			});
		}
	});
	
    $(".propertyTypeBox").click(function(){
	if(this.checked){
		$("#propertyTypeAllBox").attr("checked",false);
	    var min = parseInt($(this).attr("min"));
		var max = parseInt($(this).attr("max"));
		if(min < parseInt($("#price-input-low").val()))
			$("#price-input-low").val(min);
		if(max > parseInt($("#price-input-high").val()))
			$("#price-input-high").val(max);
	}
    });
    
    $(".centerMap").live('click', function(){
    	bigMap.panTo(bigMapMarkersRef[$(this).attr('obid')].getPosition());
    	bigMap.setZoom(15);
    	return false;
    });
    
    $(".map-re-search").live('click', function(){
    	mapSearch(false);
    	return false;
    });
    
    $("#searchResultsLink").live('click', function(){
    	$('#search-content').slideDown('fast');
    	$("#show-search-link").html('hide');
    });
    
    $(".view-listing-link").live('click', function(){
    	scrollTo($('#results-section').offset().left,$('#results-section').offset().top);
    	getDetails($(this).attr('obid'),$(this).attr('feedid'),'');
    	return false;
    });
    
    $(".save-listing-link").live('click', function(){
    	saveProperty($(this).attr('feed'),$(this).attr('mlsid'),$(this).attr('obid'),$(this).attr('streetaddress'));
    	return false;
    });
    
    $(".delete-listing-link").live('click', function(){
    	confirmDeleteProperty($(this).attr('obid'));
    	return false;
    });
    
    $(".delete-listing-link-confirm").live('click', function(){
    	deleteSavedProperty($(this).attr('obid'));
    	return false;
    });
    
    $(".delete-link-cancel").live('click', function(){
    	$('#confirmDeleteMsg').fadeOut(250);
    	return false;
    });
    
    $(".view-search-link").live('click', function(){
    	callSearch('index.cfm?event=idx.ajaxSearch&'+$(this).attr('params'),'');
    	$("#show-search-link").html('show criteria');
        $('#search-content').slideUp('fast');
    	scrollTo($('#search-shell').offset().left,$('#search-shell').offset().top);
    	return false;
    });
    
    $(".delete-search-link").live('click', function(){
    	confirmDeleteSearch($(this).attr('searchid'));
    	return false;
    });
    
    $(".delete-search-link-confirm").live('click', function(){
    	deleteSearch($(this).attr('searchid'));
    	return false;
    });
    
    $(".email-alerts-link").live('click', function(){
    	toggleAlerts($(this).attr('searchid'),$(this).attr('enable'));
    	return false;
    });
    
    $(".photo-tour-link").live('click', function(){
    	loadSlideshow($(this).attr('imgList'),$(this).attr('feed'));
    	return false;
    });
		
	$(".slide-prev, .slide-next").click(function(){
    	browseSlideshow($(this).hasClass("slide-prev"));
    	return false;
    });
    
    $(".slide-startstop").click(function(){
    	startStopSlideshow();
    	return false;
    });
    
    $(".close-slideshow").click(function(){
    	clearTimeout(slideTicker);
    	slideTicker = null;
    	$("#slideshow").hide(100);
    	return false;
    });
    
    $(".call-action-link, .email-listing-link, .mortgage-center-link").live("click", function(){
    	callFormTB($(this).attr("msg"),$(this).attr("boxHeight"),$(this).attr("boxWidth"),$(this).attr("form"),$(this).attr("params"));
    	return false;
    });
    
    $(".save-search-button").click(function(){
    	saveSearch();
    	return false;
    });
    
    $('#STREETADDRESS').change(function(){
    	mapIt();
    });
    
    $('.map-msg-remove').click(function(){
    	showAlertBox = false;
    	$('#mapMsg').hide();
    	return false;
    });
    
    /*  The following use custom functions that you can find in functions.js  */
    
    //autocomplete, this one adds the selected element under the select box
    $('select.searchList').change(function(){
    	if($(this).children("option:selected").val() != '')
			addItem($(this).siblings("ul"), $(this).children("option:selected").val(), $(this).children("option:selected").attr("text"));
		this.selectedIndex = 0;
	});
	
	$('.removeItem').live("click", function(){
		$(this).parent().remove();
		return false;
	});
	
	$("#close-slideshow").click(function(){
		$("#slideshow").fadeOut(100);
		clearTimeout(slideTicker);
		slideTicker = null;
		return false;
	});
	
	$("#slide-start-stop").click(function(){
		startSlideshow();
		return false;
	});
	
	//This is the creation of the autocomplete, we apply it on every input
    $("input.searchInput").autocomplete({
    	delay: 250,
    	minLength: 3,
    	source: "index.cfm?event=ext.getListOptions",
    	select: function(e, ui) {
    		var itemValue = ui.item.value;
            if(itemValue.split('||').length > 1)
                itemValue = itemValue.split('||')[1];
            var itemText = ui.item.value.split('||')[0].replace(";",",");
    		if($(this).closest(".geo-loc").attr("dataType") != 'areaSearch')
    			itemValue = itemValue.replace(",","|");
			if(ui.item.value != '')
				addItem($(this).closest(".geo-loc").children("ul"), itemValue, itemText);
			ui.item.value = "";
		},
        open: function(e, ui){
            $('.ui-menu-item a').each(function(){
                var newText = $(this).html().split('||')[0].replace(";",",");
                $(this).attr("cid", $(this).html().split('||')[1]);
                $(this).html(newText);
            });
        }
	});
    
    $("input.searchInput").keypress(function(event){
        if(event.which == '13'){
            $("#submit-search").click();
        }
    });
	
	//when you click an input, we set the autocomplete options based on what you want to search for
	$("input.searchInput").focus(function(){
		var dataType = $(this).closest(".geo-loc").attr("dataType");
		var areaID = $(this).closest(".geo-loc").attr("areaID");
		params = "&dataType=" + dataType;
		if(areaID != null)
			params += "&areaID=" + areaID;
		$("input.searchInput").autocomplete( "option", "source",autocompleteURL + "&format=json"+params);
	});
	
	$("#statusMsg, #confirmDeleteMsg, #slideshow").offset({ top: topOffset, left: leftOffset });
	
	infoBox = new InfoBox({
		disableAutoPan: false
		,closeBoxMargin: "0"
		,closeBoxURL: ""
		,maxWidth: 0
		,pixelOffset: new google.maps.Size(-25, 5)
		,zIndex: null
		,infoBoxClearance: new google.maps.Size(1, 1)
		,isHidden: false
		,pane: "floatPane"
		,enableEventPropagation: false
	});
});


