﻿var _ld = null;
var MAXSEARCHLATDELTA = 0.15;
var MAXSEARCHLNGDELTA = 0.3;
function mapLoaded(map){
    _ld = new ListingDetail(_appPath+'/handlers/listing.ashx');
    _map = map;
    _map.addMapMoveCallback('search',function(){updateSearchLocation();});
    var aMan = new AmenityManager(_appPath + '/handlers/amenities.ashx', map, null, 500);
    var amenityContainer = document.getElementById('amenityToolbarSection');
    var amenityLinks = amenityContainer.getElementsByTagName('a');
    for(var i=0;i<amenityLinks.length;i++){
        var val = amenityLinks[i].id.replace('amenityCategoryLink_','');
        setAmenityLink(aMan,amenityLinks[i],val);
    }
    
    setupMarkerAnchors(map);
    
    //if the hash contains a propid we will try and pop it
    var l = window.location;
    if (l.hash&&/^#?[0-9]+$/.test(l.hash)){
        var id = parseInt(l.hash.replace('#',''));
        var marker = map.getMarker(id,HOUSE_MARKER_TYPE);
        if(marker){
            listingMarkerClick(map,marker);
        } else {
            marker = map.getMarker(id,MINIHOUSE_MARKER_TYPE)
            if(marker){
                smallListingMarkerClick(map,marker);
            }
        }
    }
}

function setupMarkerAnchors(map){
    //setup listing info window links
    var listingMarkers = map.markers[HOUSE_MARKER_TYPE];
    for(var i in listingMarkers){
        attachMarkerWindowAnchor(listingMarkers[i]);
    }
}
function attachMarkerWindowAnchor(marker){
    if(marker.info){
        var link = document.getElementById("view" + marker.info.id);
        if(link){
            link.onclick = function(){listingMarkerClick(_map,marker);};
        }
    }
}
function setAmenityLink(aMan,link,val){
    link.onclick=function(){
            aMan.clearTypes();
            if(val>0){
                aMan.addType(val);
                aMan.getAmenities(null,function(result){alert(result.error.message);aMan.clearTypes();});
            }else{
                aMan.clearAmenities();
            }
            return false;
        };
}

function showFindMapLocation(){
    document.getElementById('findMapLocation').style.visibility = 'visible';
    document.getElementById('locationText').focus();
    document.getElementById('locationText').select();
    gatrack('/search/showFindMapLocation');
}

function hideFindMapLocation(){
    document.getElementById('findMapLocation').style.visibility = 'hidden';
}

function showMapSearchHelp(){
    document.getElementById('mapSearchHelpPopup').style.display = '';
    gatrack('/search/showMapSearchHelp');
}

function hideMapSearchHelp(){
    document.getElementById('mapSearchHelpPopup').style.display = 'none';
}

function updateSearchLocation(){
    if(!document.getElementById('useMapForLocation').checked){
        gatrack('/search/mapMove/false');
        var value = getCookie('showMapTip');
        if( value==null || value == '1' ){
            showMapMessage();
        }
        return;
    }
    
    var bounds = _map.getBounds(MAXSEARCHLATDELTA,MAXSEARCHLNGDELTA);
    var zoom = _map.getZoom();
    if(_search.bounds!==bounds||_search.zoom!==zoom){
        _map.showWait();
        document.getElementById('mapInfo').value=_map.getMapInfo(MAXSEARCHLATDELTA,MAXSEARCHLNGDELTA);
        if(_search.bounds===null||_search.bounds===''){
            _search.cityIds=null;
            _search.zips=null;
            _search.countyIds=null;
        }
        _search.page=null;
        _search.bounds=bounds;
        _search.zoom=zoom;
        _search.execute(displayResults, displayError);
        gatrack('/search/mapMove/true');
    }
}

function displayResults(search,result){
    document.getElementById('listings').innerHTML=getResultsDisplay(result.listings,result.q);
    document.getElementById('listings').scrollTop = 0;
    var query = [];
    //if(search.view!=''){query[query.length]='view='+search.view;}
    if(result.paging.page>1){query[query.length]='pg='+result.paging.page;}
    
    var startIndex = ((result.paging.page-1) * result.paging.itemsPerPage) + 1;
    var endIndex = startIndex + result.paging.itemsPerPage - 1;
    if(endIndex>result.paging.totalItems){
        endIndex = result.paging.totalItems;
    }
    var listingDisplayCount = '';
    if(result.paging.totalItems>0){
        listingDisplayCount = String.format("Now displaying listings {0} to {1}", startIndex, endIndex)
        if(search.view=='map'){
            listingDisplayCount += ' on the map';
        }
    }
    document.getElementById('listingDisplayCount').innerHTML = listingDisplayCount;
    setDistrictDisplay(result.districts);
    setFeaturesDisplay(result.features);
    
    var qs='';
    if(query.length>0){
        qs=(result.seoPath.indexOf("?")>-1?'&':'?') + query.join('&');    
    }

    window.location.hash='#'+result.seoPath + qs;
    _map.clearMarkers(HOUSE_MARKER_TYPE);
    _map.clearMarkers(MINIHOUSE_MARKER_TYPE);
    _map.clearMarkers(CITY_MARKER_TYPE);
    _map.addMarkers(getMarkerInfo(result.listings,result.otherListings,result.citycounts),false);
    setupMarkerAnchors(_map);
    var pageTurn=getPageTurnHtml(result.seoPath,result.paging);
    var pageJump=getPageJumpHtml(result.seoPath,result.paging);
    document.getElementById('pageTurnTop').innerHTML=pageTurn;
    document.getElementById('pageJumpTop').innerHTML=pageJump;
    document.getElementById('pageTurnBottom').innerHTML=pageTurn;
    document.getElementById('pageJumpBottom').innerHTML=pageJump;
    document.getElementById('TotalListingCount').innerHTML=addCommas(result.count);
    document.getElementById('sortBy').innerHTML = getSortByHtml(search.dir);
    setSortClick('sortBy',displayResults, displayError);
    var mlsDataHtml=getMlsDataHtml(result.MlsSummary);
    if(mlsDataHtml!=document.getElementById('mlsDataSelection').innerHTML){
        document.getElementById('mlsDataSelection').innerHTML=mlsDataHtml;
    }
    hookUpPagingEvents();
    if(result.isMapSearchOnly){
        document.getElementById('searchCriteriaLocation').innerHTML='<div class="searchCriteriaMapText">Results are currently based on the map viewing area.  To search based on a location name, add a location below.</div>';
    }
    updateSearchViewDisplay('searchViewsTop',result.searchViews);
    document.getElementById('disclaimerFooter').innerHTML=result.footer;
    try{
        document.getElementById('saveSearchTop').href=result.saveUrl;
        document.getElementById('saveSearchTop').onclick=function(){_account.showSaveSearch(result.saveUrl); return false;}
        document.getElementById('emailMeListingsTop').href=result.saveUrl;
        document.getElementById('emailMeListingsTop').onclick=function(){_account.showSaveSearch(result.saveUrl); return false;}
    } catch(err) {}
    
    var headers = '';
    if(result.titles.h1){headers+='<h1>'+result.titles.h1+'</h1>';}
    if(result.titles.h2){headers+='<h2>'+result.titles.h2+'</h2>';}
    document.getElementById('searchTitleArea').innerHTML=headers;
    if(result.titles.title){document.title=result.titles.title;}
    _map.hideWait();
}

function hookUpPagingEvents(){
    setPagingClicks('pageTurnTop',displayResults, displayError);
    setPagingClicks('pageJumpTop',displayResults, displayError);
    setPagingClicks('pageTurnBottom',displayResults, displayError);
    setPagingClicks('pageJumpBottom',displayResults, displayError);
}

function setPagingClicks(containerId,responseCallback, errorCallback){
    var container = document.getElementById(containerId);
    if(container){
        var links = container.getElementsByTagName('a');
        var pageNum;
        for(var i=0;i<links.length;i++){
            pageNum = getQueryValue(links[i].href, 'pg');
            if(pageNum!=''){
                setPagingClicksElement(links[i],pageNum,responseCallback,errorCallback);
            }else{
                links[i].onclick=null;
            }
        }
    }
}

function setPagingClicksElement(elem, pageNum,responseCallback, errorCallback){
    elem.onclick=function(){
                    _search.page=pageNum;
                    _map.showWait();
                    _search.execute(responseCallback, errorCallback);
                    gatrack('/search/paging');
                    return false;
                };
}
function getPage(pagenum,responseCallback, errorCallback){
   _search.page=pagenum;
    _map.showWait();
    _search.execute(responseCallback, errorCallback);
    gatrack('/search/mappaging');
    return false;
}

function setSortClick(containerId,responseCallback, errorCallback){
    var container = document.getElementById(containerId);
    if(container){
        var link = container.getElementsByTagName('a');
        if(link&&link.length>0){
            link[0].onclick=function(){
                _map.showWait();
                if(_search.dir!="ASC"){
                    _search.dir="ASC"
                } else {
                    _search.dir=null;
                }
                _search.page=1;
                _search.execute(responseCallback, errorCallback);
                gatrack('/search/sorting');
                return false;
            };
        }
    }
}

function displayError(search,result){
    if(result.error.type==='boundstoolarge'){
        var html = '<div style="text-align:center;">' +
        '<p style="font-size:14px;"><em>The current map based search is too large.</em></p>' +
        '<p><strong>Please zoom in to update results</strong></p></div>';
        document.getElementById('listings').innerHTML=html;
    }
    else{
        alert(result.error.message);
    }
    _map.hideWait();
}

function toggleMapSize( link ){
    var container = document.getElementById('MapResultsView');
    var link = document.getElementById('mapSizeLink');
    var icon =document.getElementById('mapSizeToggleIcon')
    if(container.className == 'fullMap'){
        icon.src=icon.src.replace('house.gif','globe.gif');
        link.innerHTML = 'Full map view';
        container.className = '';
        setCookie('searchMap','small',null,'/');
        gatrack('/search/toggleMapSize/small');
    }else{
        icon.src=icon.src.replace('globe.gif','house.gif');
        link.innerHTML = 'Side by Side View';
        container.className = 'fullMap';
        setCookie('searchMap','full',null,'/');
        gatrack('/search/toggleMapSize/full');
    }
    if(_map!==null){_map.checkResize();}
}

function initStyleCB(cbId) {
	if(!document.getElementById)return;
	
	var cb = document.getElementById(cbId);
	if(!cb)return;
	var events = new Array("onfocus", "onblur", "onselect", "onchange", "onclick", "ondblclick", "onmousedown", "onmouseup", "onmouseover", "onmousemove", "onmouseout", "onkeypress", "onkeydown", "onkeyup");
	// loop over the length of the forms in the document

	if(cb.getAttribute("type") == "checkbox") {
		cb.style.visibility = "hidden";
		cb.style.display = "none";
		var img = document.createElement("img");
		img.setAttribute("class","chk");
		cb.parentNode.insertBefore(img,cb)
		cb.imgRef = img;
		updateStyleCB(cb);
		// assign the checkbox objects event handlers to its replacement image
		for(e=0;e<events.length;e++) if(eval('cb.' +events[e])) eval('img.' + events[e] + '= cb.' + events[e]);
		addEvent(cb,"click",function(){updateStyleCB(cb);})
    	img.onclick = function() { cb.click(); return false;}
	}
}

function updateStyleCB(cb) {
	// finally, update the image to reflect the current state of the checkbox.
	if(cb.checked) {
		cb.imgRef.setAttribute("src",_appPath+"/images/search/chk_on.gif");
	} else {
		cb.imgRef.setAttribute("src",_appPath+"/images/search/chk_off.gif");
	}
}

function findLocation(){
    var locationText = document.getElementById('locationText').value;
    _map.setLocationFromText(locationText); 
    hideFindMapLocation();
    gatrack('/search/findLocation/' + escape(locationText));
}

function resetLocation(){
    _map.reset(); 
    hideFindMapLocation();
    gatrack('/search/resetLocation');
}

function useMapForLocationClicked(checked){
    setCookie('UseMapForLocation',checked,null,'/');
    if(checked){
        updateSearchLocation();
        gatrack('/search/useMapForLocationClicked/true');
    } else {
        gatrack('/search/useMapForLocationClicked/false');
    }
}

function gatrack(url){
    //google analytics tracking
    if(typeof( pageTracker ) != 'undefined'){
        pageTracker._trackPageview(url);
    }
}

function createMapMessage(){
    var container = document.getElementById("mapCol");
    var msgDiv = document.createElement("div");
    msgDiv.id="mapMessage";
    var html = "<p>Did you know that you can update your results based on the location of the map?</p>";
    html += "<p>Please check the box above the map to change your results as the map moves.</p>";
    html += "<input id='showMapTip' type='checkbox' /><label for='showMapTip'>Do not show again</label>";
    html += "<div style='text-align:right;'><input type='submit' onclick='hideMapMessage(); return false;' value='Close' /></div>";
    
    msgDiv.innerHTML = html;
    container.appendChild(msgDiv);
    msgDiv.style.left = ((container.offsetWidth - msgDiv.offsetWidth)/2).toString() + 'px';
    msgDiv.style.top = ((container.offsetHeight - msgDiv.offsetHeight)/2).toString() + 'px';
    return msgDiv;
}
function showMapMessage(){
    var el = document.getElementById("mapMessage");
    if(!el){
        el=createMapMessage();
    }
    el.style.visibility='visible';
}
function hideMapMessage(){
    var el = document.getElementById("mapMessage");
    if(el){
        el.style.visibility='hidden';
    }
    
    var chk = document.getElementById("showMapTip");
    if(chk){
        if(chk.checked){
            var date = new Date();
		    date.setDate(date.getDate()+365);
            setCookie('showMapTip', '0', date,'/');
        } else {
            setCookie('showMapTip', '0',null,'/');
        }
    } else {
        setCookie('showMapTip', '0',null,'/');
    }
}

function createAddressLink(id,searchText){
    var elem = document.getElementById(id);
    if(elem==null){return};
    var placemarkDiv = document.createElement('div');
    placemarkDiv.id = 'placemarkDiv';
    placemarkDiv.style.display='none';
    placemarkDiv.style.border='solid 1px black';
    placemarkDiv.style.backgroundColor='white';
    placemarkDiv.style.position='absolute';
    placemarkDiv.style.padding='5px 5px 5px 5px';
    placemarkDiv.innerHTML = '<div><img src="'+ _appPath + '/images/loading.gif" />Loading</div>';
    elem.appendChild(placemarkDiv);
    var a =  document.getElementById(id+'Link');
    var loaded = false;
    a.onclick=function(){document.getElementById('placemarkDiv').style.display='';if(loaded!=true){lookup(searchText, placemarkDiv);loaded=true;}};
}

function lookup(searchText, placemarkDiv){
    lookupLocation(searchText, function(places){
       var html = '';
       if(places==null){
            html = '<div>An error has occured, please try again later</div>';
        }else if(places.length==0){
            html = '<div>No matching locations found.</div>'
        }else{
            html = '<div>Possible locations (click one):</div><ul>';
            var place;
            for(var i=0;i<places.length;i++){
                place = places[i];
                if(place.c=="High"||place.c=="Medium"){
                    html += '<li><a href="' + getNearbyGeocodeSearchUrl(place.p.latitude,place.p.longitude,0.5,place.display) + '">' + place.display + '</a></li>';
                }
            }
            html+='</ul>';
        }
        html += '<div style="text-align:center;"><a href="javascript:void(0);" onclick="document.getElementById(\'placemarkDiv\').style.display=\'none\';">Close</a></div>';
        placemarkDiv.innerHTML = html;
     });
}
function lookupLocation(searchText,callback){
    var geocoder = new WDCGeocoder(); 
    geocoder.getLocations(searchText, callback);
}

function getNearbyGeocodeSearchUrl(lat, lng, miles,display){
    //build bounds based on lat lng and 'radius' miles
    //69.172 is number of miles in 1 degree lat
    var MILESPERDEGREE = 69.172;
    var latRange = miles / MILESPERDEGREE;
    var longRange = (miles / MILESPERDEGREE) / Math.cos(lat * Math.PI / 180);

    var minLatitude = lat - latRange;
    var maxLatitude = lat + latRange;
    var minLongitude = lng - longRange;
    var maxLongitude = lng + longRange;

    //create a bounds search url
    var bounds = String.format("{0},{1},{2},{3}", minLatitude.toString(), minLongitude.toString(), maxLatitude.toString(), maxLongitude.toString());
    var zoom = '15';
    var view = 'map';
    return String.format('{0}/search/realestate/searchresults.aspx?bounds={1}&zm={2}&view={3}&sortby=distance&orig={4},{5}{6}',_appPath, bounds, zoom, view,lat.toString(),lng.toString(),(display!=null&&display!='')?'|'+encodeURIComponent(display):'');
}

function getResultsDisplay(listings,query){
    if(listings==null||listings.length==0){
        var res = '<div style="text-align:center;">' +
                  '<p style="font-size:14px;"><em>Unfortunately, <strong>0</strong> properties matched your search criteria.</em></p>' +
                  '<p><strong>Can you broaden your search?</strong>' +
                  '<br />&nbsp;&nbsp;- Expand to include more areas' +
                  '<br />&nbsp;&nbsp;- Specify fewer features' +
                  '<br />&nbsp;&nbsp;- Widen your price range</p></div>';
        return res;
    }
    
    var html = '';
    var dividerHtml = '<div style="padding:3px 0; text-align:center;clear:both;"><img src="' + _appPath + '/images/searchResultsDivider.jpg" alt="" width="300" height="1" /></div>';
    var mappedCount=0;
    for( var i = 0; i < listings.length; i++){
        if(i%2==0){
            html += '<div class="listingModule">'
        } else {
            html += '<div class="listingModule alt">'
        }
        var listing = listings[i];
        
        var mapAnchorId = 'view' + listing.p;

        if( listing.lat !== null && listing.lng !== null ) {
            mappedCount++;
            html += '<div class="listingMapAnchor"><a id="view' + listing.p + '" title="View on Map" href="javascript:void(0);"><img src="'+_appPath+'/images/search/map_house'+(mappedCount)+'.gif"/></a></div>';
        }  
        
        html += getListingDisplay(listing);
        
        html += '<div class="narrowListings">';
        if(listing.mlsData!==null){
            html += listing.mlsData;
        }
        html += '</div>';
        html += dividerHtml;
        html += '</div>';
    }
    return html;
}

function getListingDisplay(listing){
    var html = '';
    var pUrl = listing.url;
    html += '<div id="prow' + listing.p + '" class="narrowListings">';
    html += '<div class="listing">'
    if(listing.addr !== null){
        html += '   <span class="address"><a href="'+ pUrl + '">' + listing.addr + '</a>';
        if(listing.addr2 !== null){
            html += '<br />' + listing.addr2;
        }
        html += '</span>';
    } else {
        html += '   <span class="address">Address not provided</span>';
    }
    html += '   <span class="cityState">' + listing.loc + '</span>';
    html += '   <div class="propertyImage">';
    var imgAlt = "";
    if(listing.addr !== null && listing.addr != "Listing not provided" ){
        imgAlt = listing.addr;
    } else {
        imgAlt = "MLS #/Web ID: " + listing.mls;
    }
    if(listing.img!==null){
        html += '       <a href="' + pUrl + '"><img src="' +listing.img + '" alt="' + imgAlt + '" style="height:75px;width:100px;border-width:0px;" /></a>';
    }
    html += '   </div>';
    html += '   <div class="propertyInfo"><div>';
    if(listing.price){
        html += '       <span class="price">$' + addCommas(listing.price) + '</span>';
    }
    if(listing.newtomarket == true){
        html += '       <img id="JustListedIcon" src="' + _appPath + '/images/search/i_justlisted.gif" alt="Just Listed" />';
    }
    if(listing.pricereduced == true){
        html += '       <img id="PriceReducedIcon" src="' + _appPath + '/images/search/i_pricereduced.gif" alt="Price Adjusted" />';
    }
    if(listing.openhouse == true){
        html += '       <img id="OpenHouseIcon" src="' + _appPath + '/images/search/i_openhouse.gif" alt="Open House" />';
    }
    if(listing.newconstruction == true){
        html += '       <img id="NewConstructionIcon" src="' + _appPath + '/images/search/i_newconstruction.gif" alt="New Construction" />';
    }
    if(listing.adultcommunity == true){
        html += '       <img id="AdultCommunityIcon" src="' + _appPath + '/images/search/i_adultcommunity.gif" alt="Adult Community" />';
    }
    if(listing.weichertexclusive == true){
        html += '       <img id="WeichertExclusiveIcon" src="' + _appPath + '/images/search/i_weichertexclusive.gif" alt="Weichert Exclusive" />';
    }
    if(listing.foreclosure == true){
        html += '       <img id="ForeclosureIcon" src="' + _appPath + '/images/search/i_foreclosure.gif" alt="Foreclosure" />';
    }
    html += '   </div>';
    if(listing.bedBath!=null && listing.bedBath!=""){
        html += '       <span class="bedBath" style="display:block;">' + listing.bedBath + '</span>';
    }
    if(listing.units && listing.units != ""){
        html += '       <div>Units: '+ listing.units +'</div>';
    }
    if(listing.type !== null){
        html += '       <div><a href="' + pUrl + '">' + listing.type + '</a></div>';
    }
    if(listing.currentuse && listing.currentuse != ""){
        html += '       <div>Current Use: '+ listing.currentuse +'</div>';
    }
    if(listing.zoning && listing.zoning != ""){
        html += '       <div>Zoning: '+ listing.zoning +'</div>';
    }
    html += '       <div>MLS #/Web ID: ' + listing.mls + '</div>';
    if(listing.status && listing.status != ""){
        html += '       <div>Status: '+ listing.status +'</div>';
    }
    html += '       <div>'
    html += '           <span class="detailsLink"><a href="' + pUrl + '">View Details</a></span>'
    if(listing.vtour !== null){
        html += '       <span class="virtualTourLink"><a href="javascript:openWin(\'' + listing.vtour + '\',\'VirtualTour\',\'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=700,height=540\')"><strong>Virtual Tour</strong></a></span>';
    }
    if(listing.openhouse == true){
        if(listing.ohtour == true ){
            html += '       <div class="openHouseTourLink"><a id="lnkAddToTour_' + listing.mls + '" rel="nofollow"><strong>Added to tour</strong></a></span></div>';
        }else {
            html += '       <div class="openHouseTourLink"><a id="lnkAddToTour_' + listing.mls + '" onclick="addToTour(' + listing.p + ',\'lnkAddToTour_' + listing.mls + '\');return false;" href="' + _appPath + '/openhouse/openhousetour.aspx?oh=' + listing.p + '" rel="nofollow"><img src="' + _appPath + '/images/search/addtoopentour.gif" alt="Add to Open House Tour" /></a></span></div>';
        }
    }
    if(listing.dist != null){
        html += '<div class="distanceSection"><img src="' + _appPath + '/images/myweichert/mappoint.gif" alt="" style="border-width: 0px;" />Mileage: ' + listing.dist + ' mi';
        if(listing.lat != null && listing.lng != null){
            html += '<span> [<a href="javascript:void(0);" onclick="_distancePopup.show(arguments[0],' + listing.lat + ',' + listing.lng + ');">more</a>]</span>';
        }
        html += '</div>';
    }
    html += '       </div>';
    html += '   </div>';
    html += '</div>';
    html += '</div>';
    return html;
}

function setDistrictDisplay(districts){
    var container = document.getElementById('schoolDistrictListContainer');
    var list = document.getElementById('schoolDistrictList');
    if(container&&list){
        list.innerHTML = '';
        if(districts!=null&&districts.length>0){
            var itemClick = function(){document.getElementById('AllSchoolDistricts').checked=false;};
            for(var i=0;i<districts.length;i++){
                var chk = createChkListItem(districts[i].name, 'schoolDistrictList_'+districts[i].id, '', itemClick, districts[i].on);
                list.appendChild(chk);
            }
            container.style.display='';
        } else {
            container.style.display='none';
        }
    }
}

function setFeaturesDisplay(features){
    var container = document.getElementById('advancedFeaturesContainer');
    var list = document.getElementById('advancedFeaturesList');
    if(container&&list){
        list.innerHTML = '';
        if(features!=null&&features.length>0){
            for(var i=0;i<features.length;i++){
                var chk = createChkListItem(features[i].name, 'advancedFeaturesList_'+features[i].id, '', null, features[i].on);
                list.appendChild(chk);
            }
            container.style.display='';
        } else {
            container.style.display='none';
        }
    }
}

function getMarkerInfo(listings,otherListings,citycounts){
    var mapData = [];
    var listingCount = 0;
    for( var j = 0; j < listings.length; j++ ){
        var listing = listings[j];
        if( listing.lat !== null && listing.lng !== null ) {
            listingCount++;
            mapData.push(getListingMapData(listing,listingCount));
        }
    }
    if(otherListings){
        for(var k=0;k<otherListings.length;k++){
            var tooltip = '$' + addCommas(otherListings[k].price);
            mapData.push(getMapData(otherListings[k].id,MINIHOUSE_MARKER_TYPE,otherListings[k].lat,otherListings[k].lng,smallListingMarkerClick,MINIHOUSE_ICON,tooltip,null,null,null,5200));
        }
    }
    
    if(citycounts){
        for(var i = 0; i < citycounts.length; i++){
            var city = citycounts[i];
            mapData.push(getCityMapData(city));
        }
    }
    return mapData;
}

function getListingMapData(listing, index){
    var icon = HOUSE_ICON;
    if(index<=20){
        icon = HOUSE_ICONS[index];
    }
    var tooltip = '$' + addCommas(listing.price);
    return getMapData(listing.p,HOUSE_MARKER_TYPE,listing.lat,listing.lng,listingMarkerClick,icon,tooltip,null,null,null,5500);
}

function getCityMapData(city){
    //var html = '<strong>'+city.CityName+'</strong><br/>Mapped: '+city.Mapped.toString()+'<br/>Not Mapped: '+city.Unmapped.toString();
    return getMapData(city.id,CITY_MARKER_TYPE,city.lat,city.lng,cityMarkerClick,CITY_ICON,city.name,null,city.desc);
}

//id,group,lat,lng,onclick,icon,title,desc,url,z
function getMapData(id,group,lat,lng,onclick,icon,tooltip,title, desc, url, z){
    return { "id" : id, "group" : group, "lat" : lat, "lng" : lng, "onclick" : onclick, "icon" : icon, "tooltip" : tooltip, "title" : title, "desc" : desc, "url" : url, "z" : z};
}

function getPageTurnHtml(path,paging){
    var prevHref='';
    var nextHref='';
    var html = '';
    if(paging!==null){    
        if(paging.totalPages<=1){
            return '';
        }
        if(paging.page > 1){
            prevHref = 'href="' + path + "?pg=" + (paging.page-1).toString() + '"';
        }
        if(paging.page < paging.totalPages){
            nextHref = 'href="' + path + "?pg=" + (paging.page+1).toString() + '"';
        }
        html = '<div class="tablePageTurnNavigation">';
        html += '<span class="spanPageTurnLinks">';
        html += '<span class="spanPageTurnLink"><a ' + prevHref + '>Previous</a></span>';
        html += '<span class="spanPageTurnLinkDivider">&nbsp;|&nbsp;</span>';
        html += '<span class="spanPageTurnLink"><a ' + nextHref + '>Next</a></span>';
        html += '</div>';
    }

    return html;
}

function getPageJumpHtml(path,paging){
    var html = '';
        if(paging!==null){
        html = '<div class="tablePageJumpNavigation">';
        for(var i=1; i<=paging.totalPages; i++){
            var link = path + '?pg=' + i.toString();
            if(i==paging.page){
                html += i.toString();
            }else{
                html +='<a href="'+link+'">'+i.toString()+'</a>';
            }
            
            if(i!=paging.totalPages){
                html+='<span class="spanLinkDivider">&nbsp;|&nbsp;</span>';
            }
        }
        html+='</div>';
    }
    return html;
}

function getMlsDataHtml(mlsSummary){
    var html = '';
    if(mlsSummary.length>1){
        html+= '<div>';
        html+='<table class="sideSelectMLS">';
        
        for(var i=0;i<mlsSummary.length;i++){
            var mls = mlsSummary[i];
            html+='<tr><td style="text-align:left;padding:2px 0 2px 6px;">';
            if(mls.sel==true){
                html+='<span style="font-size:11px;font-weight:bold;">Current View:  </span>';
                html+='<a>' + mls.total.toString() + '&nbsp;listings</a>' + mls.desc;
            } else {
                html+='<a href="'+ mls.url + '">' + mls.total.toString() + '&nbsp;listings</a>' + mls.desc;
            }
            html+='</td></tr>';
        }
        html+='</table></div>'
    }
    return html;
}

function getSortByHtml(dir){
    var html = 'Sort by <a href="javascript:void(0);" rel="nofollow">Price</a> ';
    if(dir=="ASC"){
        html += '<img src="' + _appPath + '/images/arrow-up.gif" alt="" style="border-width: 0px;" />';
    } else {
        html += '<img src="' + _appPath + '/images/arrow-down.gif" alt="" style="border-width: 0px;" />';
    }
    return html;    
}

function updateSearchViewDisplay(containerId,searchViews){
    var container = document.getElementById(containerId);
    var links = container.getElementsByTagName('a');
    var views = searchViews;
    if(links.length==views.length){
        for(var i=0;i<views.length;i++){
            links[i].href=views[i].url;
            links[i].className = views[i].className;
        }
    }
}

function listingMarkerClick(context, marker){
    if(marker.info.desc==null){
        var descElement = document.getElementById("prow"+marker.info.id);
        if(descElement){
            var newElem = descElement.cloneNode(true);
            newElem.id = newElem.id + '_map';
            var temp = document.createElement("div");
            temp.appendChild(newElem);
            marker.info.desc = temp.innerHTML;
        }
    }
    if(marker.info.desc!=null){
        context.showMarkerPopup(context, marker);
    }
}
function smallListingMarkerClick(context, marker){
    if(marker.info.desc!=null){
        context.showMarkerPopup(context, marker);
    } else {
        _ld.getResultListing(marker.info.id,_search.toString(),function(ldcontext,result){
            marker.info.desc = getListingDisplay(result.listing);
            context.showMarkerPopup(context, marker);
        });
    }
}

function cityMarkerClick(context,marker){
    if(marker.info.desc!=null){
        context.showMarkerPopup(context, marker);
    }
}

Number.prototype.toRad = function() { 
  return this * Math.PI / 180; 
}
//distance calculations for user addresses
function calcDistance(lat1, lon1, lat2, lon2){
    var result = Math.acos(Math.sin(lat1.toRad())*Math.sin(lat2.toRad()) + Math.cos(lat1.toRad())*Math.cos(lat2.toRad())*Math.cos((lon2-lon1).toRad())) * 3959;
   	return Math.round(result*10)/10;
}
// end user address javascript

function WDCDistancePopup(searchLocation, accountLocations){
    this.searchLocation = searchLocation;
    this.accountLocations = accountLocations;

    this.container = null;
    this.content = null;
    this.init();
}

WDCDistancePopup.prototype.init = function(){
    var context = this;
    var container = document.createElement('div');
    container.className = 'distancePopUp';
    container.style.display = 'none';
    container.style.position = 'absolute';
    var close = document.createElement('a');
    close.onclick = function(){ context.hide(); };
    close.innerHTML = '[close]';
    close.className = 'distanceCloseLink';
    container.appendChild(close);
    
    var content = document.createElement('div');
    container.appendChild(content);
    
    this.content = content;
    this.container = container;
    document.body.appendChild(this.container);
};
WDCDistancePopup.prototype.show = function(e, lat, lng){
    if(this.searchLocation==null&&(this.accountLocations==null||this.accountLocations.length==0)){
        return;
    }
    var html = '<table class="distanceTable">';
    if(this.searchLocation!=null){
        html += '<tr><td class="distanceTableHeader" colspan="2">Distance from Searched Location</td></tr>';
        html += '<tr><td class="distanceTableCellLeft">' + this.searchLocation.name + '</td><td class="distanceTableCellRight">' + calcDistance(lat,lng,this.searchLocation.lat,this.searchLocation.lng) + ' mi</td></tr>';
    }
    if(this.accountLocations!=null&&this.accountLocations.length>0){
        html += '<tr><td class="distanceTableHeader" colspan="2">Distance from Saved Map Points</td></tr>';
        for(var i=0;i<this.accountLocations.length;i++){
            var loc = this.accountLocations[i];
            html += '<tr><td class="distanceTableCellLeft">' + loc.name + '</td><td class="distanceTableCellRight">' + calcDistance(lat,lng,loc.lat,loc.lng) + ' mi</td></tr>';
        }
    }
    html += '</table>';
    this.content.innerHTML = html;

    e = (e) ? e : event;
    this.container.style.top = mouseY(e) + 'px';
    this.container.style.left = mouseX(e) + 'px';
    this.container.style.display = '';
};

WDCDistancePopup.prototype.hide = function(){
    this.container.style.display = 'none';
}; 

//search criteria functions
function InitSections(){
    var sectionIds = new Array('Location','Price','PropertyTypes','Features','ListingType','Schools','AdvancedFeatures');
    var value;
    var section;
    for (section in sectionIds){
        value = getCookie(sectionIds[section]);
        if( value!==null && value == 0 ){
            var header = document.getElementById(sectionIds[section] + 'Header');
            var content = document.getElementById(sectionIds[section]);
            if(content!=null){
                content.style.display = "none";
            }
            if(header!=null){
                header.className = header.className.replace("Expanded", "");
                header.className = header.className.replace("Collapsed", "");
                header.className += " Collapsed";
            }
        }
    }
}

function toggleSection( e, sectionId ){
    var section = document.getElementById(sectionId);
    if(section){
        if(section.style.display == "none"){ 
            setCookie(sectionId, '1',null,'/');
            section.style.display = "";
            e.className = e.className.replace("Expanded", "");
            e.className = e.className.replace("Collapsed", "");
            e.className += " Expanded";
        } else {
            setCookie(sectionId, '0',null,'/');
            section.style.display = "none";
            e.className = e.className.replace("Expanded", "");
            e.className = e.className.replace("Collapsed", "");
            e.className += " Collapsed";
        }
    }
}

var _states = {};
var _regions = {};
var _lochttp = null;
function getLocHttp(){
    if(_lochttp==null){
        _lochttp = new WDCHttp(_appPath+'/handlers/locations.ashx');
    }
    return _lochttp;
}
function selectState(stateId){
    var dd = document.getElementById('StateList');
    if(dd&&dd.value!=stateId){
        dd.value=stateId;
    }
    if(stateId!=''){
        if(_states[stateId]){
            setState(_states[stateId]);
        } else {
            var params = "mode=state&stateid=" + encodeURIComponent(stateId);
            _show('waitImageSection');
            getLocHttp().get(this,params,function(context,result){
                _states[result.state.id.toString()] = result.state;
                setState(result.state);
            });
        }
    } else {
        clearRegion();
    }
    return (dd.value != stateId);
}
function selectRegion(regionId){
    var dd = document.getElementById('RegionList');
    if(dd&&dd.value!=regionId){
        dd.value=regionId;
    }
    if(regionId!=''){
        if(_regions[regionId]){
            setRegion(_regions[regionId]);
        } else {
            var params = "mode=region&regionid=" + encodeURIComponent(regionId);
            _show('waitImageSection');
            getLocHttp().get(this,params,function(context,result){
                _regions[result.region.id.toString()] = result.region;
                setRegion(result.region);
            });
        }
    } else {
        clearRegion();
    }
    return (dd.value != regionId);
}
function clearRegion(){
    var e;
    if(e = document.getElementById('findSchoolDistrictDiv')){e.innerHTML = '<div class="checkBoxListHeader">Select a County/Region</div>';}
}
function setState(state){
    _hide('waitImageSection');
    
    clearRegion();
    var regiondd = document.getElementById('RegionList');
    regiondd.options.length=1;
    if(state!=null&&state.regions!=null){
        for(var i=0;i<state.regions.length;i++){
            regiondd.options[regiondd.options.length] = new Option(state.regions[i].name, state.regions[i].id);
        }
    } 
}
function setRegion(region){
    _hide('waitImageSection');
    if(region!=null){
        setCheckboxList('findSchoolDistrictDiv', 'Districts', region.districts, 'name', 'id');
    } else {
        clearRegion();
    }
}
function setCheckboxList(containerId, display, items, nameAttribute, valueAttribute){
    var container = document.getElementById(containerId);
    if(container){
        container.innerHTML = '';
        if(items!=null&&items.length>0){
            var headerClick = function(){toggleAll(containerId, this.checked);};
            container.appendChild(createChkListItem('- All '+display+' -', containerId+'_all','checkBoxListHeader',headerClick));

            var itemClick = function(){document.getElementById(containerId+'_all').checked=false;};
            for(var i=0;i<items.length;i++){
                var item = items[i];
                var className = (i%2==0 ? 'checkboxListItem':'checkboxListAltItem');        
                container.appendChild(createChkListItem(item[nameAttribute],containerId+'_'+item[valueAttribute],className,itemClick));
            }
        } else {
            container.innerHTML = 'Not available';
        }
    }
}

function createMyWeichertCallout(){
    var c = createTag('div',{'id':'myWeichertCallout'});
    c.appendChild(createTag('span', {'class':'myWeichertCallout'}));
    c.appendChild(createTag('img', {'src':_appPath+'/images/impressions.gif?impid=mwSRcallout&rnd='+(new Date()).getTime(),'useMap':'#calloutMap'}));
    var m = createTag('map',{'id':'calloutMap','name':'calloutMap'});
    var area = createTag('area', {'shape':'POLY','href':'javascript:void(0);','coords':'140,8, 175,8, 175,26, 140,26','title':'Close'});
    area.onclick = function(){return hideCallout(c);};
    m.appendChild(area);
    area = createTag('area', {'shape':'POLY','href':_appPath+'/myweichert/AddAccount.aspx?trksrc=mwSRcallout','coords':'34, 112, 90,112, 90,136, 34,136','title':'Ask us'})
    m.appendChild(area);
    c.appendChild(m);
    setupFadeIn(c,750,1000);
    var main;
    if(main = document.getElementById('main')){main.appendChild(c);}
}
function hideCallout(elem){
    elem.style.display='none';
    setCookie('myWeichertCalloutShown','1',null,'/');
    return false;
}

function addToTour (propertyId,clientId){
    var t = new WDCOpenHouseTour(_appPath+'/handlers/openhousetour.ashx');
    t.addTourProperty(propertyId,clientId, function (success,message){
        if(message!=''){
            alert(message);
        }
    });
}

