function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};

function isLongEnough(fld,len) {
    if(fld.length < len) {
        return false;
    } else {
        return true;
    }
}


var $j = jQuery.noConflict();

$j(document).ready(function() {
    $j(".deletesearch").click(function() {
        if (!confirm("Delete this search?")) return false;
    });

    $j("#aa_createmyaccount").click(function() {
        // verify the other form fields.
        var goodtogo = true;
        errs = "Please fix the following: ";

        if ( $j("#aa_email").val() != $j("#aa_email2").val() ) {
            errs += "\n " + "Email fields do not match";
            goodtogo = false;
        }

        if (!isValidEmailAddress($j("#aa_email").val())) {
            errs += "\n " + "Please enter a valid email address";
            goodtogo = false;
        }

        if ( !isLongEnough($j("#aa_passwd").val(),4)) {
            errs += "\n " + "Password must be at least four characters.";
            goodtogo = false;
        }

        if ( !isLongEnough($j("#firstname").val(),2)) {
            errs += "\n " + "First Name must be at least two characters.";
            goodtogo = false;
        }

        if ( !isLongEnough($j("#lastname").val(),2)) {
            errs += "\n " + "Last Name must be at least two characters.";
            goodtogo = false;
        }
            // alert(errs);

        if (!goodtogo) {
            alert(errs);
            return false;
        }

    });

    $j("#aa_broaden_search").click(function() {
        var port = (window.location.port) ? ':' + window.location.port : '';
        var me = window.location.protocol + '//' + window.location.hostname + port + window.location.pathname;
        me = window.location.pathname;
        // alert(me);
        $j("#aa_search_area").load("mapsource.php",
            {
                'map':this.href
            },

            function(response, status, xhr) {
            if (status == "error") {
                var msg = "Sorry but there was an error: ";
                $j("#aa_search_area").html(msg + xhr.status + " " + xhr.statusText);
            }
        });

        return false;

    });

    // image slide show
    var mainpic = $j("#aa_mainpic").attr("src");
    $j(".aa_thumbnail").mouseover(function() {
        $j("#aa_mainpic").attr("src",$j(this).attr("src"));
    });

    $j(".aa_thumbnail").mouseout(function() {
        $j("#aa_mainpic").attr("src",mainpic);
    });

    $j(".aa_thumbnail").click(function() {
        mainpic=$j(this).attr("src");
        $j("#aa_mainpic").attr("title",$j(this).attr("title"));
    });

    $j("#aa_print_listing").click(function() {
        // alert("Page Title: " + $j("#aa_listingaddress").html());
        $j('#aa_listingdetail').printElement({
            // leaveOpen:true,
            // printMode:'popup',
            pageTitle: $j("#aa_clientname").html()
        });
        return false;
    });

    // $j(".aa_tabs:first").tabs(".aa_panes:first > div");

    $j(".aa_showmorelink").click(function() {
        var toshow = this.rel;
        // alert("show: " + toshow);
        $j(toshow+"_link").click();

        return false;
    });

    $j(".aa_review_link").click(function() {
        // need to hide all tabs.
        // then show the review tab;
        $j(".aa_panes").css("display","none");
        $j("#aa_review").toggle();
        return false;
    });

    $j(".aa_searchnow_link").click(function() {
        $j("#aa_searchform").submit();
    });


    $j("#aa_toolbox ul a[rel]").overlay();


    $j("#aa_toolbox a[rel]").bind("onLoad", function() {
        var toshow = this.rel;
            if (toshow == "#aa_gmap") {
            // this will display the map AFTER displaying the div.
            googlemap(aa_lat,aa_lon,aa_address);
        }
    });

    $j("#aa_calculator_widget").MortgageCalculator({
        mode: "normal",
        animate: "true",
        title: "", footer: "",
        intro: "With this calculator you can put in your values and estimate the amount of your loan and get an estimate on the amount of your monthly payments. Click on the &#39;Calculate&#39; button when you&#39;re ready.",
        logo: {path: "", url: ""},
        fields: {
            principal: {
                enabled: "null",
                type: "input",
                desc: "The total value of the loan (in dollars)"
            } ,
            interest: {
                    enabled: "null",
                    type: "input",
                    desc: "The annual interest rate of the loan"
            } ,
            term: {
                        enabled: "null",
                        type: "select",
                        desc: "The term of the loan (in years)"
            } ,
            down: {
                            enabled: "true",
                            type: "input",
                            desc: "The down payment on the loan (in dollars)"
            } ,
            taxes: {
                                enabled: "true",
                                type: "input",
                                desc: "The annual property taxes (in dollars)"

            } ,
            insurance: {
                                    enabled: "true",
                                    type: "input",
                                    desc: "The annual homeowner&#39;s insurance (in dollars)"
            } ,
            pmi: {
                                        enabled: "true",
                                        type: "input",
                                        desc: "The monthly private mortgage insurance (in dollars)"
            } ,
            extra: {
                                        enabled: "true",
                                        type: "input",
                                        desc: "Extra to pay to the principal per month (in dollars)"
            }
        },
        defaults: {
            taxes: 0,
            insurance: 0.5,
            interest: 6.0,
            term: 30,
            principal: $j("#listprice").html()
        },
        bounds: {
                                    min: {
                                        principal: 0,
                                        interest: 0,
                                        term: 15
                                    },
                                    max: {
                                        principal: 15000000,
                                        interest: 15,
                                        term: 40
                                    },
                                    step: {
                                        term: 5
                                    }
        },
        colors: {
                                    main: {
                                        text: "#000",
                                        back: "#aaa",
                                        border: "#39c"
                                    },
                                    title: {
                                        text: "#000",
                                        back: "#fff"
                                    },
                                    tab: {
                                        text: "#39c",
                                        back: "#fff",
                                        border: "#39c"
                                    },
                                    pane: {
                                        text: "#000",
                                        back: "#fff",
                                        border: "#39c"
                                    },
                                    input: {
                                        text: "#000",
                                        back: "#fff",
                                        border: "#aaa",
                                        error: "#fcc"
                                    },
                                    button: {
                                        text: "#fff",
                                        back: "#46a026",
                                        border: "#1f731a"
                                    },
                                    nav: {
                                        text: "#fff",
                                        back: "#39c",
                                        border: "#39c"
                                    },
                                    table: {
                                        text: "#000",
                                        back: "#fff",
                                        border: "#aaa"
                                    },
                                    footer: {
                                        text: "#999",
                                        back: ""
                                    },
                                    link: {
                                        text: "#39c"
                                    },
                                    values: {
                                        payment: "#6a9f35",
                                        taxes: "#0584af",
                                        insurance: "#ff9300",
                                        total: "#eee",
                                        principal: "#6a9f35",
                                        extra: "#90d948",
                                        interest: "#f00",
                                        balance: "#333"
                                    }
        }
    });


    $j("#aa_clearsearch").click(function() {
        clearForm('#aa_searchform');
    });

    var currentarea = "aa_area_lma";
    $j("#"+currentarea).toggle();

    var currentcounty = "lma";
    $j("#aa_county_"+currentcounty).toggle();

    $j(".aa_show_search_maps").click(function() {
        $j("#aa_search_towns").toggle();
        $j("#aa_lma").toggle();
        return false;
    });

    $j(".aa_area_selector").click(function() {
        // var id = $j(this.id);  // aa_area_XX_selector
        var id = $j(this).attr('id');
        // if we trim off the _selector portion, we have the id of the div to show.
        var divid = id.replace("_selector","")
        // $j("#"+divid).css("display","block");
        // turn off the current area

        $j("#"+currentarea).toggle();
        currentarea = divid;
        //turn on the new one
        $j("#"+currentarea).toggle();

        // if this is lma, then we want to change the town list, as well...
        if (divid=="aa_area_lma") {
            $j("#aa_county_"+currentcounty).toggle();
            //set the current county..
            currentcounty = "lma";
            // turn on the new county..
            $j("#aa_county_"+currentcounty).toggle();
        }

        // adjust the height of the list...
        // $j("#aa_town_list").css("height",$j("#aa_search_area").css("height"));
        return false;
    });


//=====================================================================================
//=====================================================================================
    // running search criteria values
    $j(".aa_towns").change(function() {
        displayselectedtowns();
    });

    $j(".aa_singlefamily_class").change(function() {
        v = "Single Family";
        // now add any sub classes.
        v += " - " + getselectedsfclass();
        $j("#aa_selected_property_type").text(v);
    });

    $j('.aa_propertytype').change(function() {
        var pt = $j("input[name='propertytype']:checked").val();
        var v = "Single Family";
        $j('.aa_singlefamily_class').attr('disabled', true);

        // $j("INPUT[type='checkbox']").attr('checked', $('#checkAllAuto').is(':checked'));

        switch (pt) {
            case "singlefamily":
                v = "Single Family";
                // enable the check boxes
                $j('.aa_singlefamily_class').removeAttr('disabled');
                // now add any sub classes.
                v += " - " + getselectedsfclass();
                break;
            case "multifamily":
                v = "Multi Family";
                break;
            case "land":
                v = "Lots/Land";
                break;
            case "boat":
                v = "Boat Docks";
                break;
            case "rent":
                v = "Rentals";
                break;
            case "commercial":
                v = "Commercial Properties";
                break;
        }


        $j("#aa_selected_property_type").text(v);
    });

    $j('.aa_singlefamily_class').change(function() {
    });

    $j('.aa_minmax_select').change(function() {
       var fld = this.id;
       switch (fld) {
           case "MinPrice":
            $j("#aa_selected_price_min").text($j('#MinPrice :selected').text());
            break;
           case "MaxPrice":
            $j("#aa_selected_price_max").text($j('#MaxPrice :selected').text());
            break;
           case "MinBedrooms":
            $j("#aa_selected_bedrooms_min").text($j('#MinBedrooms :selected').text());
            break;
           case "MaxBedrooms":
            $j("#aa_selected_bedrooms_max").text($j('#MaxBedrooms :selected').text());
            break;
           case "MinBaths":
            $j("#aa_selected_baths_min").text($j('#MinBaths :selected').text());
            break;
           case "MaxBaths":
            $j("#aa_selected_baths_max").text($j('#MaxBaths :selected').text());
            break;
           case "MinLivingArea":
            $j("#aa_selected_livingarea_min").text($j('#MinLivingArea :selected').text());
            break;
           case "MaxLivingArea":
            $j("#aa_selected_livingarea_max").text($j('#MaxLivingArea :selected').text());
            break;
           case "MinLotSize":
            $j("#aa_selected_lotsize_min").text($j('#MinLotSize :selected').text());
            break;
           case "MaxLotSize":
            $j("#aa_selected_lotsize_max").text($j('#MaxLotSize :selected').text());
            break;
           case "MinGarage":
            $j("#aa_selected_garage_min").text($j('#MinGarage :selected').text());
            break;
           case "MaxGarage":
            $j("#aa_selected_garage_max").text($j('#MaxGarage :selected').text());
            break;
       }
    });

    clearForm('#aa_searchform');

    //==============================================================================
            $j("#aa_loading").toggle();
            $j("#aa_searchtabs").toggle();

    //==============================================================================
    // events for the state LIST
    //==============================================================================
    $j(".aa_search_state")
        .mouseover(function() {
            var state = this.id;
            state = state.replace("_search_state","_map");
            $j("#"+state).css('display', 'block');
        })

        .mouseout(function() {
            var state = this.id;
            state = state.replace("_search_state","_map");
            // $j("#"+county).css('display', 'none');

            if (!$j("#"+state).hasClass('selected')) {
                $j("#"+state).css('display', 'none');
            }

        })
        .click(function() {
            // hide the ne map.
            $j("#aa_map_ne_div").css("display","none");

            var state = this.id;
            // aa_search_state_me
            state = state.replace("aa_search_state_","");
            // now just me
            state = "#aa_map_"+state+"_div";

            $j(state).addClass('selected').css('display', 'inline');

        });
    //==============================================================================
    // events for the county LIST
    //==============================================================================
    $j(".aa_search_county")
        .mouseover(function() {
            var county = this.id;
            county = county.replace("_search_county","_map");
            $j("#"+county).css('display', 'block');
        })

        .mouseout(function() {
            var county = this.id;
            county = county.replace("_search_county","_map");
            // $j("#"+county).css('display', 'none');

            if (!$j("#"+county).hasClass('selected')) {
                $j("#"+county).css('display', 'none');
            }

        })
        .click(function() {
            // first, deal with the display of county towns
            var id = this.id;
            var county = id.replace("aa_search_county_","")
            $j("#aa_debug_box").text(county);   //aroostook_me

            // turn off the current county
            $j("#aa_county_towns_"+currentcounty).toggle();
            //set the current county..
            currentcounty = county;
            // turn on the new county..
            $j("#aa_county_towns_"+currentcounty).toggle();

            // now, hilite the county on the map
            var countymap = "#aa_map_"+county;
            $j("#aa_debug_box").text(countymap);
            $j('.aa_search_map img.aa_region').removeClass('selected').css('display', 'none');
            $j(countymap).addClass('selected').css('display', 'inline');

            // now, hilite the county on the list.
            $j('.aa_search_county').removeClass('list_selected');

            var countylistitem = "#aa_search_county_"+county;
            $j(countylistitem).addClass('list_selected');


        })

    ;

    //==============================================================================
    // events for the image maps..
    //==============================================================================
            $j(".aa_search_map_shell area")
            .mouseover(function(){
                var county = this.id;
                county = county.replace("aa_","aa_map_");
                $j("#"+county).css('display', 'block');

                var countylistitem = "#aa_search_county_"+county.replace("aa_map_","");
                $j(countylistitem).css("text-decoration","underline");
            })

            .mouseout(function(){
                var county = this.id;
                county = county.replace("aa_","aa_map_");
                // Check if a click event has occured and only change the Region hover state accodringly
                if (!$j("#"+county).hasClass('selected')) {
                    $j("#"+county).css('display', 'none');

                }
                    var countylistitem = "#aa_search_county_"+county.replace("aa_map_","");
                    $j(countylistitem).css("text-decoration","none");


            })

            .click(function(){
                // unhilite the STATE
                $j('.aa_search_map img.aa_region').removeClass('selected').css('display', 'none');
                $j('.aa_search_county').removeClass('list_selected');

                // if of this div...
                var parent = $j(this).parent().attr('id');
                var grandparent = $j(this).parent().parent().parent().attr('id');

                // alert ("Parent: " + parent + "\n Grandparent: " + grandparent);

                if (parent == "aa_map_ne") {

                    $j("#"+parent+"_div").css("display","none");

                    var county = this.id;
                    county = county.replace("aa_","aa_map_");
                    county = "#" + county + "_div";


                    $j(county).addClass('selected').css('display', 'inline');

                    // SHOW THE COUNTIES...
                    var rlist = county.replace("_div","_list");
                    $j(rlist).css("display","block");


                } else {
                    var county = this.id;
                    county = county.replace("aa_","");
                    $j("#aa_debug_box").text(county);

                    // turn off the current county
                    $j("#aa_county_towns_"+currentcounty).toggle();
                    //set the current county..
                    currentcounty = county;
                    // turn on the new county..
                    $j("#aa_county_towns_"+currentcounty).toggle();


                    var countymap = "#aa_map_"+county;
                    $j(countymap).addClass('selected').css('display', 'inline');

                    var countylistitem = "#aa_search_county_"+county;
                    $j(countylistitem).addClass('list_selected');

                }
            });

            $j(".aa_ne_link").click(function() {
                // hide the current county
                $j("#aa_county_towns_"+currentcounty).toggle();
                currentcounty = "lma";


                var parent = $j(this).parent().attr('id');
                var grandparent = $j(this).parent().parent().attr('id');
                // alert("Parent: " + parent);
                $j("#"+grandparent).css("display","none");
                $j("#aa_map_ne_div").css("display","block");

                return false;
            });

            $j(".aa_show_counties").click(function() {
                var statelist = "#"+$j(this).parent().attr('id') + " .aa_county_list";
                $j(".aa_county_towns").css("display","none");
                $j(statelist).css("display","block");
            });

            $j(".aa_radio_towns_check_all").click(function() {
                // checkall id: aa_check_all_NH-Strafford
                // checkbox class: radio_aa_state_county_NH-Strafford

                // ul id: aa_county_towns_strafford_nh
                // when the check all is clicked, we want all check boxes in the ul to toggle.

                var countycheck = this.id;
                var countyclass = countycheck.replace("aa_check_all_","radio_aa_state_county_");
                $j('.'+countyclass).attr('checked', this.checked);

                displayselectedtowns();



            });
        //--------------  AgentAve Slide Show ---------------------------------------------
            var h = $j('.aa_active').height() + "px";
            $j("#aa_slideshow").css('height',h);
            var aa_activeslideshow = true;
            var aa_playSlideshow =  setInterval( "aa_slideSwitch('next')", 5000 );


            $j("#aa_slidecontrols").hover(function() {
                clearInterval(aa_playSlideshow);
            },
                function() {
                    if (aa_activeslideshow) {
                        aa_playSlideshow =  setInterval( "aa_slideSwitch('next')", 5000 );
                    }
            });

            $j("#aa_ss_prev").click(function() {
                aa_slideSwitch('prev');
                return false;
            })

            $j("#aa_ss_next").click(function() {
                aa_slideSwitch('next');
                return false;
            })

            $j("#aa_ss_stop").click(function() {
                aa_activeslideshow=false;
                return false;
            })

            $j("#aa_ss_play").click(function() {
                aa_activeslideshow=true;
                aa_slideSwitch('next');
                return false;
            })
        //--------------  AgentAve Slide Show ---------------------------------------------});
        var showConsole = function(l,v) {
            if(typeof window.console != 'undefined' && typeof window.console.log != 'undefined') {
                console.log(l, v);
            }
        };

        $j("#aa_show_map").click(function() {
            if ($j(this).text()=="Show Map") {
                $j(this).text("Hide Map");
                var listtop = "+=360px";
                var mapleft = "0";
                setCookie('mapstatus','visible',30);
            } else {
                $j(this).text("Show Map");
                var mapleft = "-9999px";
                var listtop = "-=360px";
                setCookie('mapstatus','hidden',30);
            }
            showConsole("Adjusting aa_results_list to: ", listtop);

            $j('#aa_results_list').animate({"top": listtop}, "fast");
            $j("#aa_results_map_container").animate({
                left: mapleft,
                top: '15px'
            },300);

            return false;
        });
//-----------------------------------------------------------------------------------------//
// google maps jquery...
// we only want to run this code when on the results page...
//-----------------------------------------------------------------------------------------//
    if ($j('#aa_results_map').length) {
        var resultsmap = new google.maps.Map(document.getElementById("aa_results_map"), {
            scrollwheel: false,
            center: new google.maps.LatLng(43.66689497135091,-71.59689354687498),
            zoom: 10,
            maxZoom: 18,
            mapTypeId: 'terrain'
        });

        var bounds = new google.maps.LatLngBounds();

        var infoWindow = new google.maps.InfoWindow;

        var onMarkerClick = function() {
            var marker = this;
            var latLng = marker.getPosition();
            infoWindow.setContent(this.content);

            infoWindow.open(resultsmap, marker);
        }; // onMarkerClick

        var onMarkerMouseOver = function() {
            var marker = this;

            var listid = "#aa_map_results_"+this.id;
            showConsole("List ID: ", listid);

            // $j(listid).css("background-color","#adf");
            $j(listid).addClass("aa_results_map_hover_list");
            showConsole("Added hover to: " , listid);
            // get the parent offset.
            var parentoffset = $j(listid).parent().offset();
            var parenttop = parentoffset.top;

            var thisoffset = $j(listid).offset();
            var thistop = thisoffset.top;

            // showConsole("Parent Offset: ",parenttop);
            // showConsole("LI Offset: ",thistop);

            // this will make the list item visible in the scroll.
            var dest = thistop - parenttop;
            $j("#aa_map_listing_display").scrollTop(dest);

        };  // onMarkerMouseOver

        var onMarkerMouseOut = function() {
            var marker = this;
            var listid = "#aa_map_results_"+this.id;
            // $j(listid).css("background","transparent");
            $j(listid).removeClass("aa_results_map_hover_list");

            showConsole("List ID Out: ", listid);
        }; // onMarkerMouseOut

        google.maps.event.addListener(resultsmap, 'click', function() {
            infoWindow.close();
        });

        var markers = [];

        $j(".aa_geo").each(function(){
            var mlsno = $j(this).attr('id');
            var mlsno = mlsno.replace("geo_","");

            var lat = $j(this).children(".aa_lat").text();
            var lng = $j(this).children(".aa_lon").text();

            var itemno = $j(this).children(".itemno").text();
            var address = $j(this).children(".aa_address").text();
            var llink = $j(this).children(".aa_link").text();
            var pic = $j(this).children(".aa_pic").text();
            var price = $j(this).children(".aa_ListPrice").text();

            var latlng = new google.maps.LatLng(lat,lng);
            bounds.extend(latlng);

            var contentString = '<div class="aa_info_window"><a href="' + llink + '"><img src="' + pic +'" /><br />' + mlsno + ': ' + price + '<br />' + address + '<br />Click to view</a></div>';

            showConsole("MLS: ",mlsno);
            showConsole("Link: ",llink);

            markers[itemno] = new StyledMarker({
                styleIcon:new StyledIcon(StyledIconTypes.BUBBLE,{color:"00ff00",text:itemno}),
                map: resultsmap,
                position: latlng,
                mlsno: mlsno,
                id: itemno,
                content: contentString,
                title:address
                });

            // var styleMaker1 = new StyledMarker({styleIcon:new StyledIcon(StyledIconTypes.MARKER,{color:"00ff00",text:"A"}),position:latlng,map:resultsmap});


            google.maps.event.addListener(markers[itemno], 'click', onMarkerClick);
            google.maps.event.addListener(markers[itemno], 'mouseover', onMarkerMouseOver);
            google.maps.event.addListener(markers[itemno], 'mouseout', onMarkerMouseOut);


            // showConsole("Added Marker: ",lat + "," + lng);

            resultsmap.fitBounds(bounds);
        });

        // run this code aftr the map loads
        zoomLevel = resultsmap.getZoom();
        if(typeof window.console != 'undefined' && typeof window.console.log != 'undefined') {
            console.log("Zoom Level: " + zoomLevel);
        }

        // resultsmap.maxZoom=20;


        // now, add a listener for the list
        $j(".aa_map_results_list").click(function() {
            var lid = $j(this).attr('id');
            showConsole("ID Clicked: ",lid);
        });

        $j(".aa_map_results_list").hover(
            function() {
                var lid = $j(this).attr('id');
                lid = lid.replace("aa_map_results_","");
                $j(this).addClass("aa_results_map_hover_list");

                var marker = markers[lid];
                var latLng = marker.getPosition();
                infoWindow.setContent(marker.content + '<br />Click to view');

                infoWindow.open(resultsmap, marker);
                showConsole("ID Over: ",lid);
            },
            function() {
                var lid = $j(this).attr('id');
                lid = lid.replace("aa_map_results_","");
                // $j(this).css("background","transparent");
                $j(this).removeClass("aa_results_map_hover_list");
                infoWindow.close();
                showConsole("ID Out: ",lid);
            }
        );

        // check the cookie for map status
        var mapstatus=getCookie("mapstatus");
        showConsole("Loading Map Status: ", mapstatus);
        if (mapstatus == "visible") {
            $j("#aa_show_map").click();
        };
        //-----------------------------------------------------------------------------------------//
        // end google maps
        //-----------------------------------------------------------------------------------------//
        $j("#aa_loading_map").css("display","none");
    } // if the google map element exists
});  // end of on load

function setCookie(c_name,value,exdays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
            return unescape(y);
        }
    }
}

// functions below here //
function aa_slideSwitch(direction) {
    var active = $j('#aa_slideshow .aa_active');

    if ( active.length == 0 ) active = $j('#aa_slideshow .aa_slide:last');

    if (direction=='next') {
        var show =  active.next().length ? active.next()
            : $j('#aa_slideshow .aa_slide:first');
    } else {
        var show =  active.prev().length ? active.prev()
            : $j('#aa_slideshow .aa_slide:last');
    }

    active.addClass('last-active');

    show.css({opacity: 0.0})
        .addClass('aa_active')
        .animate({opacity: 1.0}, 200, function() {
            active.removeClass('aa_active last-active');
        });
    var h = $j('.aa_active').height() + "px";
    $j("#aa_slideshow").css('height',h);

}

function clearForm(form) {
  // iterate over all of the inputs for the form
  // element that was passed in
  $j(':input', form).each(function() {
 var type = this.type;
 var tag = this.tagName.toLowerCase(); // normalize case
 // it's ok to reset the value attr of text inputs,
 // password inputs, and textareas
 if (type == 'text' || type == 'password' || tag == 'textarea')
   this.value = "";
 // checkboxes and radios need to have their checked state cleared
 // but should *not* have their 'value' changed
 else if (type == 'checkbox' || type == 'radio')
   this.checked = false;
 // select elements need to have their 'selectedIndex' property set to -1
 // (this works for both single and multiple select elements)
 else if (tag == 'select')
   this.selectedIndex = 0;
  });

  // now, manually set the property class...
  $j("#propertytype_single_family").attr("checked", "checked");
  $j('.aa_singlefamily_class').removeAttr('disabled');
  $j('.aa_singlefamily_class').attr("checked", "checked");
  // now set the defaults on the summary...
        v = "Single Family";
        // now add any sub classes.
        v += " - " + getselectedsfclass();
        $j("#aa_selected_property_type").text(v);


  $j("#aa_selected_price_min").text("No Minimum");
  $j("#aa_selected_bedrooms_min").text("No Minimum");
  $j("#aa_selected_baths_min").text("No Minimum");
  $j("#aa_selected_livingarea_min").text("No Minimum");
  $j("#aa_selected_lotsize_min").text("No Minimum");
  $j("#aa_selected_garage_min").text("No Minimum");

  $j("#aa_selected_price_max").text("No Maximum");
  $j("#aa_selected_bedrooms_max").text("No Maximum");
  $j("#aa_selected_baths_max").text("No Maximum");
  $j("#aa_selected_livingarea_max").text("No Maximum");
  $j("#aa_selected_lotsize_max").text("No Maximum");
  $j("#aa_selected_garage_max").text("No Maximum");

  displayselectedtowns();
};

function displayselectedtowns() {
    var values = $j('input:checkbox:checked.aa_towns').map(function () {
        return this.value;
    }).get(); // ["18", "55", "10"]
    // var seltowns = $j("#aa_selected_towns").text(values.join(", "));
    var towns = values.join(", ");
    towns = towns.replace("_"," ");
    // var towns = values.join(", ")
    if (towns=="") {
        $j("#aa_selected_towns").text("Entire Market Area");
    } else {
        $j("#aa_selected_towns").text(towns);
    }
}

function getselectedsfclass() {
    var values = $j('input:checkbox:checked.aa_singlefamily_class').map(function () {
        return this.value;
    }).get(); // ["18", "55", "10"]

    var subs = values.join(", ");
    return subs;
}

function googlemap(lat,lon,address) {
        // Function to play with google maps...
        // alert("gmap " + address);

        if(typeof window.console != 'undefined' && typeof window.console.log != 'undefined') {
            // code using console.log here
            console.log("function called: ", "googlemap");
        }

    var myLatlng = new google.maps.LatLng(lat,lon);
    var myOptions = {
      zoom: 10,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(document.getElementById("aa_gmap_canvas"), myOptions);

    var contentString = '<div>' + address + '</div>';

    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });


    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title:address
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
    });
}


/// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" />
/*
* Print Element Plugin 1.2
*
* Copyright (c) 2010 Erik Zaadi
*
* Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and
* http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome
*
*  Home Page : http://projects.erikzaadi/jQueryPlugins/jQuery.printElement
*  Issues (bug reporting) : http://github.com/erikzaadi/jQueryPlugins/issues/labels/printElement
*  jQuery plugin page : http://plugins.jquery.com/project/printElement
*
*  Thanks to David B (http://github.com/ungenio) and icgJohn (http://www.blogger.com/profile/11881116857076484100)
*  For their great contributions!
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
*   Note, Iframe Printing is not supported in Opera and Chrome 3.0, a popup window will be shown instead
*/
; (function (window, undefined) {
    var document = window["document"];
    var $ = window["jQuery"];
    $.fn["printElement"] = function (options) {
        var mainOptions = $.extend({}, $.fn["printElement"]["defaults"], options);
        //iframe mode is not supported for opera and chrome 3.0 (it prints the entire page).
        //http://www.google.com/support/forum/p/Webmasters/thread?tid=2cb0f08dce8821c3&hl=en
        if (mainOptions["printMode"] == 'iframe') {
            if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase())))
                mainOptions["printMode"] = 'popup';
        }
        //Remove previously printed iframe if exists
        $("[id^='printElement_']").remove();

        return this.each(function () {
            //Support Metadata Plug-in if available
            var opts = $.meta ? $.extend({}, mainOptions, $(this).data()) : mainOptions;
            _printElement($(this), opts);
        });
    };
    $.fn["printElement"]["defaults"] = {
        "printMode": 'iframe', //Usage : iframe / popup
        "pageTitle": '', //Print Page Title
        "overrideElementCSS": null,
        /* Can be one of the following 3 options:
        * 1 : boolean (pass true for stripping all css linked)
        * 2 : array of $.fn.printElement.cssElement (s)
        * 3 : array of strings with paths to alternate css files (optimized for print)
        */
        "printBodyOptions": {
            "styleToAdd": 'padding:10px;margin:10px;', //style attributes to add to the body of print document
            "classNameToAdd": '' //css class to add to the body of print document
        },
        "leaveOpen": false, // in case of popup, leave the print page open or not
        "iframeElementOptions": {
            "styleToAdd": 'border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element
            "classNameToAdd": '' //css class to add to the iframe element
        }
    };
    $.fn["printElement"]["cssElement"] = {
        "href": '',
        "media": ''
    };
    function _printElement(element, opts) {
        //Create markup to be printed
        var html = _getMarkup(element, opts);

        var popupOrIframe = null;
        var documentToWriteTo = null;
        if (opts["printMode"].toLowerCase() == 'popup') {
            popupOrIframe = window.open('about:blank', 'printElementWindow', 'width=650,height=440,scrollbars=yes');
            documentToWriteTo = popupOrIframe.document;
        }
        else {
            //The random ID is to overcome a safari bug http://www.cjboco.com.sharedcopy.com/post.cfm/442dc92cd1c0ca10a5c35210b8166882.html
            var printElementID = "printElement_" + (Math.round(Math.random() * 99999)).toString();
            //Native creation of the element is faster..
            var iframe = document.createElement('IFRAME');
            $(iframe).attr({
                style: opts["iframeElementOptions"]["styleToAdd"],
                id: printElementID,
                className: opts["iframeElementOptions"]["classNameToAdd"],
                frameBorder: 0,
                scrolling: 'no',
                src: 'about:blank'
            });
            document.body.appendChild(iframe);
            documentToWriteTo = (iframe.contentWindow || iframe.contentDocument);
            if (documentToWriteTo.document)
                documentToWriteTo = documentToWriteTo.document;
            iframe = document.frames ? document.frames[printElementID] : document.getElementById(printElementID);
            popupOrIframe = iframe.contentWindow || iframe;
        }
        focus();
        documentToWriteTo.open();
        documentToWriteTo.write(html);
        documentToWriteTo.close();
        _callPrint(popupOrIframe);
    };

    function _callPrint(element) {
        if (element && element["printPage"])
            element["printPage"]();
        else
            setTimeout(function () {
                _callPrint(element);
            }, 50);
    }

    function _getElementHTMLIncludingFormElements(element) {
        var $element = $(element);
        //Radiobuttons and checkboxes
        $(":checked", $element).each(function () {
            this.setAttribute('checked', 'checked');
        });
        //simple text inputs
        $("input[type='text']", $element).each(function () {
            this.setAttribute('value', $(this).val());
        });
        $("select", $element).each(function () {
            var $select = $(this);
            $("option", $select).each(function () {
                if ($select.val() == $(this).val())
                    this.setAttribute('selected', 'selected');
            });
        });
        $("textarea", $element).each(function () {
            //Thanks http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/
            var value = $(this).attr('value');
            //fix for issue 7 (http://plugins.jquery.com/node/13503 and http://github.com/erikzaadi/jQueryPlugins/issues#issue/7)
            if ($.browser.mozilla && this.firstChild)
                this.firstChild.textContent = value;
            else
                this.innerHTML = value;
        });
        //http://dbj.org/dbj/?p=91
        var elementHtml = $('<div></div>').append($element.clone()).html();
        return elementHtml;
    }

    function _getBaseHref() {
        var port = (window.location.port) ? ':' + window.location.port : '';
        return window.location.protocol + '//' + window.location.hostname + port + window.location.pathname;
    }

    function _getMarkup(element, opts) {
        var $element = $(element);
        var elementHtml = _getElementHTMLIncludingFormElements(element);

        var html = new Array();
        html.push('<html><head><title>' + opts["pageTitle"] + '</title>');
        if (opts["overrideElementCSS"]) {
            if (opts["overrideElementCSS"].length > 0) {
                for (var x = 0; x < opts["overrideElementCSS"].length; x++) {
                    var current = opts["overrideElementCSS"][x];
                    if (typeof (current) == 'string')
                        html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >');
                    else
                        html.push('<link type="text/css" rel="stylesheet" href="' + current["href"] + '" media="' + current["media"] + '" >');
                }
            }
        }
        else {
            $("link", document).filter(function () {
                return $(this).attr("rel").toLowerCase() == "stylesheet";
            }).each(function () {
                html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >');
            });
        }
        //Ensure that relative links work
        html.push('<base href="' + _getBaseHref() + '" />');
        html.push('</head><body style="' + opts["printBodyOptions"]["styleToAdd"] + '" class="' + opts["printBodyOptions"]["classNameToAdd"] + '">');
        html.push('<div class="' + $element.attr('class') + '">' + elementHtml + '</div>');
        html.push('<script type="text/javascript">function printPage(){focus();print();' + ((!$.browser.opera && !opts["leaveOpen"] && opts["printMode"].toLowerCase() == 'popup') ? 'close();' : '') + '}</script>');
        html.push('</body></html>');

        return html.join('');
    };
})(window);

