var map = null;
var _localMap = null;
var doc = document;
var browser = navigator.appName;
var isIE = (browser == "Microsoft Internet Explorer");
var $get;
if(isIE)
    $get = document.getElementById;
else
    $get = function(id){return document.getElementById(id);}
var mapHeight = 593;
var slDrawing = new VEShapeLayer();
var slPinPoints = new VEShapeLayer();
var _bulkPinPoints = null;
var customPolygon = null;
var _myPoints = new Array();
var tempShape = null;
var tempPoints = null;
var divPaging = null;
var mapDataGrid = null;
var mapDataGridBody = null;
var _pageSize = 6;
var _currentPage = 1;
var _totalPages = 0;
var _listings = null;
var _request = null;
var _sortAddressAsc = -1;
var _sortCityAsc = -1;
var _sortPriceAsc = -1;
var _sortBedsAsc = -1;
var _sortBathsAsc = -1;
var _sortStatusAsc = -1;
var _sortSqrFeetAsc = -1;
var _paddingXOffset = 0;//18;
var _paddingYOffset = 0;//-2;
var _selectState = null;
var _selectCity = null;
var _selectZoomState = null;
var _selectZoomCity = null;
var _mapjsinitialized = false;
var _initialBounds = null;
var ItemDetails = new Array();
var _hide = false;
var _mapLoaded = false;
var _boundsLoaded = false;
var _lastSelectedState = null;
var _lastSelectedCity = null;
var _lastSelectedZip = null;
var _limitedCitiesList = null;
var _directionsList = "";
var _getDirectionsGrid = "";
var _goToAddress = "";
var _isPrint = false;
//items to prepoulate map via session or querystring
var lm_x = 38.75, lm_y = -99.71;
var lm_city = "", lm_state = "", lm_zip = "", lm_minPrice = "", lm_maxPrice = "", lm_beds = "", lm_baths = "", lm_sqrft = "", lm_sortby = "", lm_sortdir = "";
var lm_sources = null;
var lm_zoom = 4;
var lm_mode = 'r';
var lm_search = false;
//add lat/long/zoom querystring params to setmapview
var lm_customView = false;
var lm_useMapFind = false;
var lm_customSort = false;
//add source rules to JS
var showOffice = true; 
//add guestbook popup
var showGuestbook = false;

//Joe 06/25/2008
//Map Directions New Code
var _printWindow = null;
var _DirectionObj = { 
    "StreetAddress":"",
    "Directions" : "",
    "StreetLatLong" : null,
    "Changed" : true,
    "Valid" : false,
    "LastHousePos" : null
    };

function GetDistance(lat1, lon1, lat2, lon2)
{
    //6371; // km
    var R = 3959;//miles
    var dLat = (lat2-lat1) * (Math.PI/180);
    var dLon = (lon2-lon1) * (Math.PI/180); 
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(lat1 * (Math.PI/180)) * Math.cos(lat2 * (Math.PI/180)) * 
            Math.sin(dLon/2) * Math.sin(dLon/2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    return R * c;
}
function ExpandMap(){
    var divMap = $get('divMap');
    var mapResultsGrid = $get('mapResultsGrid');
    if(divMap && mapResultsGrid){
        divMap.style.width = '697px';
        mapResultsGrid.style.display = 'none';
    }
}
function RetractMap(){
    var divMap = $get('divMap');
    var mapResultsGrid = $get('mapResultsGrid');
    if(divMap && mapResultsGrid){
        divMap.style.width = '461px';
        mapResultsGrid.style.display = 'block';
    }
}
function setShowOffice(bool)
{
    if(bool)
        showOffice = bool;
}
function setShowGuestBook(bool)
{
    if(bool)
        showGuestbook = bool;
}
function GetDirections()
{
    var newAddress = $get('startAddress').value;
    _DirectionObj.Changed = _DirectionObj.StreetAddress != newAddress;
    map.DeleteRoute();
    if(_DirectionObj.Changed)
    {
        _DirectionObj.StreetAddress = newAddress;
        _DirectionObj.Changed = false;
        _DirectionObj.Valid = false;
        map.Find(null, _DirectionObj.StreetAddress + ", United States" , null, null, null, 1, false, false, false, false, GotClientPos)
    }
    if(!_DirectionObj.Valid) return;
    var locations = new Array();
    var splitResult = _directionsList.split(",");
    if(splitResult.length > 0){  
       for (var iLoopCnt = 0; iLoopCnt < (splitResult.length - 1); iLoopCnt++){ 
            locations.push(new VELatLong(_listings.listings[splitResult[iLoopCnt]].Geo.Latitude,_listings.listings[splitResult[iLoopCnt]].Geo.Longitude));
        }
    }
    
    if(locations.length < 1) return;
    if(locations.length > 1)
    {
        var templocations = new Array();
        _DirectionObj.LastHousePos = _DirectionObj.StreetLatLong;
        while(locations.length > 0)
        {
            locations.sort(DistanceSort);
            templocations.push(locations.pop());
            _DirectionObj.LastHousePos = templocations[templocations.length - 1];
        }
        locations = templocations;
    }
    //Array.push(locations, 0, _DirectionObj.StreetLatLong);
    //locations.push(0, _DirectionObj.StreetLatLong);
    locations.splice(0,0,_DirectionObj.StreetLatLong);
    var options = new VERouteOptions();
    options.DrawRoute = true;
    options.SetBestMapView = true;
    options.RouteCallback = DirectionsComplete;
    options.ShowDisambiguation = false;
    map.GetDirections(locations, options);
}
function PrintWindowLoaded()
{
    _printWindow.$get('text').innerHTML = _DirectionObj.Directions;
    _printWindow = null;
}
function GotClientPos(layer, results, places, hasMore, error)
{
    if(error != null){
        SetDirections(error);
        return;
    }
    SetDirections('');
    _DirectionObj.StreetLatLong = places[0].LatLong;
    _DirectionObj.Valid = true;
    GetDirections();
}//Sorts Furthest to Closest for Array Popping
function DistanceSort(a, b)
{
    return GetDistance(_DirectionObj.LastHousePos.Latitude, _DirectionObj.LastHousePos.Longitude, a.Latitude, a.Longitude) > 
        GetDistance(_DirectionObj.LastHousePos.Latitude, _DirectionObj.LastHousePos.Longitude, b.Latitude, b.Longitude);
}
function DirectionsComplete(route)
{
    
    var splitResult = _directionsList.split(",");             
	var turns = "<h3>Turn-by-Turn Directions</h3>\r\n"+((_DirectionObj.StreetAddress != null && _DirectionObj.StreetAddress.length >0)?"<p><b>Starting Address:</b> " + _DirectionObj.StreetAddress + "<br/>\r\n":"") + "<p><b>Total Distance:</b> " + route.Distance.toFixed(1) + " miles<br/>\r\n<b>Estimated Time (Total):</b> " + GetTime(route.Time) + "</p>";
	// Unroll route and populate DIV
	var legs          = route.RouteLegs;
	var leg           = null;
	var turnNum       = 0;  // The turn #
	var styles = new Array();
	styles[0] = 'background-color:#F7F5F6;';
	styles[1] = 'background-color:#EAEAEA;';
	// Get intermediate legs
	var address = "";
	for(var iLoopCnt = 0; iLoopCnt < legs.length; iLoopCnt++)
	{
		// Get this leg so we don't have to reference multiple times
		leg = legs[iLoopCnt];  // Leg is a VERouteLeg object
		var legNum = iLoopCnt + 1;
		if(legNum > 1)
		    turns += "<br /><b>From Address:</b> " + address;
		address = "";
        if(_listings.listings[splitResult[iLoopCnt]].Address.Address.length > 0){
		    address += _listings.listings[splitResult[iLoopCnt]].Address.Address + (_listings.listings[splitResult[iLoopCnt]].Address.City.length > 0? ", " : "" );
		}
		if(_listings.listings[splitResult[iLoopCnt]].Address.City.length > 0)
		        address += _listings.listings[splitResult[iLoopCnt]].Address.City;
		if(_listings.listings[splitResult[iLoopCnt]].Address.State.length > 0){
		    var state = stateToAbb(_listings.listings[splitResult[iLoopCnt]].Address.State.toLowerCase());
		    address += " " + state;
		}
		turns += "<br/><b>Destination Address " + legNum + ":</b> " + address + "<br/><b>Distance:</b> " + leg.Distance.toFixed(1) + " miles<br/>\r\n<b>Estimated Time:</b> " + GetTime(leg.Time) + "<br/><br/>\r\n";
		// Unroll each intermediate leg
		var turn        = null;  // The itinerary leg
		var legDistance = null;  // The distance for this leg
		turns += "<table width='460' style='font-size:11px;border:1px solid #b5b5b5;'>";
		for(var j = 0; j < leg.Itinerary.Items.length; j ++)
		{
			turnNum++;
			// turn is a VERouteItineraryItem object
			turn = leg.Itinerary.Items[j];
			turns += "<tr><td style='" + styles[j % 2] + ((j != (leg.Itinerary.Items.length-1))? "border-bottom:1px solid #b5b5b5;":"") + "'>" + turn.Text;
			legDistance = turn.Distance;
			// So we don't show 0.0 for the arrival
			if(legDistance > 0)
			{
			    // Round distances to 1/10ths then // Append time if found
			    turns += " (" + legDistance.toFixed(1) + " miles" + (turn.Time != null? "; " + GetTime(turn.Time):"") + ")<br/>\r\n";
		    }
		    turns += "</td></tr>\r\n";
	    }
    	turns += "</table>\r\n";
    }
    _DirectionObj.Directions = turns;
    //new Code to popup print directions only after Directions are loaded.
    if(_isPrint)
        SendToPrintPage(_DirectionObj.Directions);
    _isPrint = false;
    // Populate DIV with directions
    //SetDirections(turns);
}
// time is an integer representing seconds
// returns a formatted string
function GetTime(time)
{
    if(time == null) return("");
    if(time > 60)
    {                                 // if time == 100
       var seconds = time % 60;       // seconds == 40
       var minutes = time - seconds;  // minutes == 60
       minutes     = minutes / 60;    // minutes == 1
       if(minutes > 60)
       {                                     // if minutes == 100
          var minLeft = minutes % 60;        // minLeft    == 40
          var hours   = minutes - minLeft;   // hours      == 60
          hours       = hours / 60;          // hours      == 1
          return(hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
       }
       else
          return(minutes + " minutes, " + seconds + " seconds");
    }
    else return(time + " seconds");
}
function SetDirections(s)
{
    $get("divRections").innerHTML = s;
}
function ClearRoute()
{
    SetDirections('');
    map.DeleteRoute();
    _DirectionObj.Directions = null;
    
}
//End New Code

function InitMapVars(selectState, selectCity, selectZoomState, selectZoomCity)
{
    _selectState = selectState;
    _selectCity = selectCity;
    _selectZoomState = selectZoomState;
    _selectZoomCity = selectZoomCity;
    _mapjsinitialized = true;
}
function FindLocation()
{
    var what = null;
    var where = null;
    var findType = null;
    var results = null;
    var city = $get(_selectZoomCity).options[$get(_selectZoomCity).selectedIndex].value;
    _lastSelectedZip = city;
    var state = $get(_selectZoomState).options[$get(_selectZoomState).selectedIndex].value;
    _lastSelectedState = state;
    var zip = $get('Zip').value;
    _lastSelectedZip = zip;
    if(zip && zip != '' && zip != "Zip")
        where = zip;
    else
        where = city != 'Select City' ? city : ''+ (where.length > 0 ? ', ' : '') + (state != 'Select State' ? state : '') + (where.length > 0 ? ', United States' :'');
    if(where && where.length > 0)
        map.Find(what, where, findType, null, 0, 1, false,false,true,true, MoreResults);
}
function MoreResults(a,b,c,d,e)
{
}
function Draw()
{
    ClearMap();
    ToggleLeftColDiv('Drawing');
    map.AttachEvent("onclick", DrawPolyMouseClick);
	map.AttachEvent("onmousemove", DrawPolyMouseMove);
    $get('polySearch').src = 'http://images.dhmiservices.com/dhmcore/IDX/MapView/stop_btn.gif';
    $get('polySearch').onclick = ClearMap;
    $get('polyimage').onclick = ClearMap;

    $get("divMap").style.cursor='crosshair';
}
function DrawPolyMouseClick(e)
{
    var x = e.mapX + _paddingXOffset;
    var y = e.mapY + _paddingYOffset;
    pixel = new VEPixel(x, y);
    var LL = PixelToLatLong(pixel);
    
    //Add the first point
    _myPoints.push(LL);
    //Check if search ended
    if (e.rightMouseButton)
    {
        try
        {
            map.DetachEvent("onmousemove", DrawPolyMouseMove);
            map.DetachEvent("onclick", DrawPolyMouseClick);
            slDrawing.DeleteShape(tempShape);
        }catch (err){}
        
        if(SearchPoly())
            SaveCookie();
        $get("divMap").style.cursor = 'http://maps.live.com/cursors/grab.cur';
    }
    else $get("divMap").style.cursor='crosshair';
}
function DrawPolyMouseMove(e)
{
    var x = e.mapX + _paddingXOffset;
    var y = e.mapY + _paddingYOffset;
    pixel = new VEPixel(x, y);
    var LL = PixelToLatLong(pixel);
    
    tempPoints = _myPoints.slice(0, _myPoints.length);
    tempPoints.push(LL);
    
    try{slDrawing.DeleteShape(tempShape);}catch (err){}
    
    if (tempPoints.length == 2)//Draw line
    {
        tempShape = new VEShape(VEShapeType.Polyline, tempPoints);
        tempShape.HideIcon();
        slDrawing.AddShape(tempShape);
    }
    if (tempPoints.length > 2)//Draw Polygon
    {
        tempShape = new VEShape(VEShapeType.Polygon, tempPoints);
        tempShape.HideIcon();
        slDrawing.AddShape(tempShape);
    }
    if($get("divMap").style.cursor != 'crosshair')
        $get("divMap").style.cursor = 'crosshair';
}
function PixelToLatLong(pixel)
{
    return map.GetMapStyle() == VEMapStyle.Birdseye ? map.GetBirdseyeScene().PixelToLatLong(pixel) : map.PixelToLatLong(pixel);
}
function ToggleLeftColDiv(section)
{
    //added to remove double image section loading from page load and search
    if(section == "searching" && $get('searchingImgDiv'))
        return;
        
    if(!mapDataGrid)
    {
	    mapDataGrid = doc.createElement('table');
	    mapDataGrid.setAttribute('cellPadding', '2');
	    mapDataGrid.setAttribute('cellSpacing', '3');
	    mapDataGrid.style.width = '220px'; 
	    mapDataGrid.style.height = 'auto';
	    mapDataGrid.style.margin = '10px auto 0 auto';
	    $get('mapResultsGrid').appendChild(mapDataGrid);
		mapDataGridBody = doc.createElement('TBODY');
		mapDataGrid.appendChild(mapDataGridBody);
    }
    if (section == "updating") {
        $get('mapStatusText').innerText = 'Updating...';
        return;
    }
    RemoveLeftColData();
    if(section == "searching")
    {
        var div = doc.createElement('div');
        window.document
        div.setAttribute('id','searchingImgDiv');
        div.style.textAlign = 'center';
        div.style.marginTop = '30px';
        var img = doc.createElement('img');
        var img2 = doc.createElement('img');
        var img3 = doc.createElement('img');
        img.src = "http://images.dhmiservices.com/dhmcore/IDX/MapView/wait_text.gif";
        img2.src = "http://images.dhmiservices.com/dhmcore/IDX/MapView/searching_animation.gif";
        img3.src = "http://images.dhmiservices.com/dhmcore/IDX/MapView/wait_house.gif";
        div.appendChild(img);
        div.appendChild(img2);
        div.appendChild(img3);
        $get('mapResultsGrid').insertBefore(div,mapDataGrid);
        $get('mapStatusText').innerText = 'Searching....';
    }
    else if(section == "noResults")
    {
        var img = doc.createElement('img');
        img.setAttribute('id','noResultsImg');
        img.src = 'http://images.dhmiservices.com/dhmcore/IDX/MapView/door.jpg';
        img.setAttribute('alt','No Results Available');
        $get('mapResultsGrid').insertBefore(img,mapDataGrid);
        $get('mapStatusText').innerText = 'No Results Found.';
    }
    else if(section == "Drawing")
    {
        var img = doc.createElement('img');
        img.style.marginTop = '30px';
        img.setAttribute('id','IdleImg');
        img.src = 'http://images.dhmiservices.com/dhmcore/IDX/MapView/idx-map-instruction.gif';
        img.setAttribute('alt','Neighborhood Boundary Search Instructions.');
        $get('mapResultsGrid').insertBefore(img,mapDataGrid);
        $get('mapStatusText').innerText = 'Drawing';
    }
    else
    {
        var img = doc.createElement('img');
        img.style.marginTop = '30px';
        img.setAttribute('id','IdleImg');
        img.src = 'http://images.dhmiservices.com/dhmcore/IDX/MapView/idx-map-instruction.gif';
        img.setAttribute('alt','Do you want to run a search?');
        $get('mapResultsGrid').insertBefore(img, mapDataGrid);
        $get('mapStatusText').innerText = section;
    }
}
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	//x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return '$'+x1;// + x2;
}
function RemoveLeftColData()
{
    if($get('noResultsImg'))
    {
        var img = $get('noResultsImg');
        $get('mapResultsGrid').removeChild(img);
    }
    else if($get('IdleImg'))
    {
        var img = $get('IdleImg');
        $get('mapResultsGrid').removeChild(img);
    }
    else if($get('searchingImgDiv'))
    {
        var div = $get('searchingImgDiv');
        $get('mapResultsGrid').removeChild(div);
    }
}
function GetMLSBounds()
{
    $.ajax(
            {
                type: "POST",
                url: "../webservices/clientservices.asmx/GetMlsBounds",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(_request){ 
                    BoundsSuccess(_request);
                },
                error: function(msg){Refresh();}                
            });
            //ClientServices._staticInstance.GetMlsBounds(BoundsSuccess, BoundsFailed);
}
function SearchPoly()
{
    if(_myPoints.length < 3)//Not enough points to make a polygon
    {
        slDrawing.DeleteAllShapes();
        _myPoints = new Array();
        $get('polySearch').src = 'http://images.dhmiservices.com/dhmcore/IDX/MapView/start_btn.gif';
        $get('polySearch').onclick = Draw;
        $get('polyimage').onclick = Draw;
        return false; 
    }    
    customPolygon = new VEShape(VEShapeType.Polygon, _myPoints);
    slDrawing.AddShape(customPolygon);
    customPolygon.HideIcon();
    //Get close to polygon
    map.SetMapView(_myPoints);
    //Abort previous transaction
    AbortRequest();
    var zip = "";
    if($get('Zip').value != "Zip")
        zip = $get('Zip').value;
    //Search Polypoints
    var hasZip = zip.length > 0 && zip.toLowerCase() != "zip";
    var price = GetMinMaxPrice();
    var _strMyPoints = ''; 
    for(var i=0; i<_myPoints.length; i++)
        _strMyPoints += (_strMyPoints.length > 0?'|':'') + _myPoints[i].Latitude+':'+_myPoints[i].Longitude;
    $.ajax(
            {
                type: "POST",
                url: "../webservices/clientservices.asmx/GetPolyListingsPOST",
                data: "{polyPoints:'"+_strMyPoints+"',minPrice:"+price.MinPrice+",maxPrice:"+price.MaxPrice+",beds:"+parseInt($get('Beds').options[$get('Beds').selectedIndex].value)+",baths:"+parseFloat($get('Baths').options[$get('Baths').selectedIndex].value)+",sqrFeet:"+parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value)+",active:"+true+",city:"+(_mapjsinitialized && !hasZip ? "'"+ $get(_selectCity).options[$get(_selectCity).selectedIndex].value+"'" : null)+",state:"+(_mapjsinitialized && !hasZip ? "'"+$get(_selectState).options[$get(_selectState).selectedIndex].value+"'" : null)+",zip:'"+zip+"',srcs:'"+lm_sources+"'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(_request){ 
                    SearchComplete(_request);
                },
                error: function(msg){}                
            });
    /*
    _request = ClientServices._staticInstance.GetPolyListings(_myPoints, price.MinPrice, price.MaxPrice,
        parseInt($get('Beds').options[$get('Beds').selectedIndex].value),
        parseFloat($get('Baths').options[$get('Baths').selectedIndex].value),
        parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value), true,//$get('Active').checked,
        (_mapjsinitialized && !hasZip ? $get(_selectCity).options[$get(_selectCity).selectedIndex].value : null), 
        (_mapjsinitialized && !hasZip ? $get(_selectState).options[$get(_selectState).selectedIndex].value : null), 
        zip, SearchComplete, SearchFailed);
        */
    GetLocalInfo();
    ToggleLeftColDiv('searching');
    
    return true;
}
function GetLocalInfo()
{
    if(_localMap.get_DisplayPublic())
        _localMap.GetPublicSchools();
    if(_localMap.get_DisplayPrivate())
        _localMap.GetPrivateSchools();
    if(_localMap.get_DisplayWorship())
        _localMap.GetWorship();
}
function Refresh() 
{
    ToggleLeftColDiv('searching');
    slPinPoints.DeleteAllShapes();
    ClearGrid();
    //Added to Remove Poly Points if City/State/Zip Change made and Search Ran
    var RemovePoly = false;
    if((!_lastSelectedCity && $get(_selectCity).selectedIndex != 0) || (_lastSelectedCity && $get(_selectCity).options[$get(_selectCity).selectedIndex].value != _lastSelectedCity))
        RemovePoly = true;
    if((!_lastSelectedState && $get(_selectState).selectedIndex != 0) || (_lastSelectedState && $get(_selectState).options[$get(_selectState).selectedIndex].value != _lastSelectedState))
        RemovePoly = true;
    if($get('Zip').value != "Zip" && ((!_lastSelectedZip && $get('Zip').value.length > 0) || (_lastSelectedZip && $get('Zip').value != _lastSelectedZip)))
        RemovePoly = true;
    if(RemovePoly && _myPoints.length > 0)
        ClearMap();
    if(_myPoints.length > 0)
        SearchPoly();
    else
    {
        if($get('Zip').value.length > 0 && $get('Zip').value != "Zip")
        {
            _lastSelectedZip = $get('Zip').value;
            _lastSelectedCity = null;
            _lastSelectedState = null;
            var price = GetMinMaxPrice();
            $.ajax(
            {
                type: "POST",
                url: "../webservices/clientservices.asmx/GetListingsPOST",
                data: "{TLLat:" + 0.0 + ",TLLong:" + 0.0 + ",BRLat:" + 0.0 + ",BRLong:" + 0.0 + ",minPrice:" + price.MinPrice + ",maxPrice:" + price.MaxPrice + ",beds:" + parseInt($get('Beds').options[$get('Beds').selectedIndex].value) + ",baths:" + parseFloat($get('Baths').options[$get('Baths').selectedIndex].value) + ",sqrFeet:" + parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value) + ",active:" + true + ",city:" + null + ",state:" + null + ",zip:'" + $get('Zip').value + "',srcs:" + (lm_sources != null ? "'" + lm_sources + "'" : null) + "}",
                //data: {TLLat:0.0,TLLong:0.0,BRLat:0.0,BRLong:0.0,minPrice:price.MinPrice,maxPrice:price.MaxPrice,beds:parseInt($get('Beds').options[$get('Beds').selectedIndex].value),baths:parseFloat($get('Baths').options[$get('Baths').selectedIndex].value),sqrFeet:parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value),active:true,city:'',state:'',zip:$get('Zip').value,srcs:lm_sources},
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(_request) {
                    SearchComplete(_request);
                },
                error: function(msg) {
                    alert(msg);
                }
            });
            /*_request = ClientServices._staticInstance.GetListings(new VELatLong(0,0),new VELatLong(0,0), price.MinPrice, price.MaxPrice,
            parseInt($get('Beds').options[$get('Beds').selectedIndex].value),
            parseFloat($get('Baths').options[$get('Baths').selectedIndex].value),
            parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value), true,//$get('Active').checked,
            null, null, $get('Zip').value,lm_sources, SearchComplete, SearchFailed);*/
        }
        else if($get(_selectState).selectedIndex != 0 && $get(_selectCity).selectedIndex != 0)
        {
            var city = $get(_selectCity).options[$get(_selectCity).selectedIndex].value;
            var state = $get(_selectState).options[$get(_selectState).selectedIndex].value;
            _lastSelectedCity = city;
            _lastSelectedState = state;
            _lastSelectedZip = null;
            var price = GetMinMaxPrice();
            $.ajax(
            {
                type: "POST",
                url: "../webservices/clientservices.asmx/GetListingsPOST",
                data: "{TLLat:"+0.0+",TLLong:"+0.0+",BRLat:"+0.0+",BRLong:"+0.0+",minPrice:"+price.MinPrice+",maxPrice:"+price.MaxPrice+",beds:"+parseInt($get('Beds').options[$get('Beds').selectedIndex].value)+",baths:"+parseFloat($get('Baths').options[$get('Baths').selectedIndex].value)+",sqrFeet:"+parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value)+",active:"+true+",city:'"+city+"',state:'"+state+"',zip:"+null+",srcs:"+(lm_sources != null?"'"+lm_sources+"'":null)+"}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(_request){ 
                    SearchComplete(_request);
                },
                error: function(msg){
                    alert(msg);
                }                
            });
            /*_request = ClientServices._staticInstance.GetListings(new VELatLong(0,0),new VELatLong(0,0), price.MinPrice, price.MaxPrice,
                parseInt($get('Beds').options[$get('Beds').selectedIndex].value),
                parseFloat($get('Baths').options[$get('Baths').selectedIndex].value),
                parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value), true,//$get('Active').checked,
                city, state, null,lm_sources, SearchComplete, SearchFailed);
                */
        }
        else if($get(_selectState).selectedIndex != 0)
        {
            
            var state = $get(_selectState).options[$get(_selectState).selectedIndex].value;
             _lastSelectedState = state;
             _lastSelectedCity = null;
             _lastSelectedZip = null;
             var price = GetMinMaxPrice();
             var city = "";
             if (lm_city.length > 0) {
                 city = lm_city.replace(/,/g, '|');
                 var corrected_cities = "";

                 var cities = city.split('|');
                 if (cities.length > 1) {
                     for (i = 0; i < cities.length; i++) {
                         corrected_cities += cities[i].substring(0, cities[i].indexOf("(")).replace(/\s+$/, "") + "|";
                     }
                     city = corrected_cities;
                 }
             }
             $.ajax(
            {
                type: "POST",
                url: "../webservices/clientservices.asmx/GetListingsPOST",
                data: "{TLLat:"+0.0+",TLLong:"+0.0+",BRLat:"+0.0+",BRLong:"+0.0+",minPrice:"+price.MinPrice+",maxPrice:"+price.MaxPrice+",beds:"+parseInt($get('Beds').options[$get('Beds').selectedIndex].value)+",baths:"+parseFloat($get('Baths').options[$get('Baths').selectedIndex].value)+",sqrFeet:"+parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value)+",active:"+true+",city:'"+city+"',state:'"+state+"',zip:"+null+",srcs:"+(lm_sources != null?"'"+lm_sources+"'":null)+"}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(_request){ 
                    SearchComplete(_request);
                },
                error: function(msg){
                    alert(msg);
                }                
            });
             /*
            _request = ClientServices._staticInstance.GetListings(new VELatLong(0,0),new VELatLong(0,0), price.MinPrice, price.MaxPrice,
                parseInt($get('Beds').options[$get('Beds').selectedIndex].value),
                parseFloat($get('Baths').options[$get('Baths').selectedIndex].value),
                parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value), true,//$get('Active').checked,
                null, state, null,lm_sources, SearchComplete, SearchFailed);
                */
        }
        else if($get('hiddenSelectedStateMap').value.length > 0)
        { //if only one state is available
            var state = $get('hiddenSelectedStateMap').value;
             _lastSelectedState = state;
             _lastSelectedZip = null;
             var price = GetMinMaxPrice();
             
            if($get(_selectCity).selectedIndex != 0){
                var city = $get(_selectCity).options[$get(_selectCity).selectedIndex].value;
                _lastSelectedCity = city;
                $.ajax(
                {
                    type: "POST",
                    url: "../webservices/clientservices.asmx/GetListingsPOST",
                    data: "{TLLat:"+0.0+",TLLong:"+0.0+",BRLat:"+0.0+",BRLong:"+0.0+",minPrice:"+price.MinPrice+",maxPrice:"+price.MaxPrice+",beds:"+parseInt($get('Beds').options[$get('Beds').selectedIndex].value)+",baths:"+parseFloat($get('Baths').options[$get('Baths').selectedIndex].value)+",sqrFeet:"+parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value)+",active:"+true+",city:"+(city != null?"'"+city+"'":null)+",state:'"+state+"',zip:"+null+",srcs:"+(lm_sources != null?"'"+lm_sources+"'":null)+"}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(_request){ 
                        SearchComplete(_request);
                    },
                    error: function(msg){
                        alert(msg);
                    }                
                });
                /*
                _request = ClientServices._staticInstance.GetListings(new VELatLong(0,0),new VELatLong(0,0), price.MinPrice, price.MaxPrice,
                parseInt($get('Beds').options[$get('Beds').selectedIndex].value),
                parseFloat($get('Baths').options[$get('Baths').selectedIndex].value),
                parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value), true,//$get('Active').checked,
                city, state, null,lm_sources, SearchComplete, SearchFailed);
                */

            } else {
                if (_limitedCitiesList) {
                    _lastSelectedCity = null;
                    $.ajax(
                    {
                        type: "POST",
                        url: "../webservices/clientservices.asmx/GetListingsPOST",
                        data: "{TLLat:" + 0.0 + ",TLLong:" + 0.0 + ",BRLat:" + 0.0 + ",BRLong:" + 0.0 + ",minPrice:" + price.MinPrice + ",maxPrice:" + price.MaxPrice + ",beds:" + parseInt($get('Beds').options[$get('Beds').selectedIndex].value) + ",baths:" + parseFloat($get('Baths').options[$get('Baths').selectedIndex].value) + ",sqrFeet:" + parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value) + ",active:" + true + ",city:'" + _limitedCitiesList + "',state:'" + state + "',zip:" + null + ",srcs:" + (lm_sources != null ? "'" + lm_sources + "'" : null) + "}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(_request) {
                            SearchComplete(_request);
                        },
                        error: function(msg) {
                            alert(msg);
                        }
                    });
                

                } else {
                    _lastSelectedCity = null;
                    $.ajax(
                    {
                        type: "POST",
                        url: "../webservices/clientservices.asmx/GetListingsPOST",
                        data: "{TLLat:" + 0.0 + ",TLLong:" + 0.0 + ",BRLat:" + 0.0 + ",BRLong:" + 0.0 + ",minPrice:" + price.MinPrice + ",maxPrice:" + price.MaxPrice + ",beds:" + parseInt($get('Beds').options[$get('Beds').selectedIndex].value) + ",baths:" + parseFloat($get('Baths').options[$get('Baths').selectedIndex].value) + ",sqrFeet:" + parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value) + ",active:" + true + ",city:'" + lm_city + "',state:'" + state + "',zip:" + null + ",srcs:" + (lm_sources != null ? "'" + lm_sources + "'" : null) + "}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(_request) {
                            SearchComplete(_request);
                        },
                        error: function(msg) {
                            alert(msg);
                        }
                    });
                    /*
                    _request = ClientServices._staticInstance.GetListings(new VELatLong(0,0),new VELatLong(0,0), price.MinPrice, price.MaxPrice,
                    parseInt($get('Beds').options[$get('Beds').selectedIndex].value),
                    parseFloat($get('Baths').options[$get('Baths').selectedIndex].value),
                    parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value), true,//$get('Active').checked,
                    null, state, null,lm_sources, SearchComplete, SearchFailed);
                    */
                }
            }       
        }
        else
        {
            // Edited on 10/09/08 by Jon to search view of map with parameters specified.  Only if city state or zip is not popuplated.
            _lastSelectedState = null;
            _lastSelectedCity = null;
            _lastSelectedZip = null;
            var price = GetMinMaxPrice();
            if(map != null){
                var view = map.GetMapStyle() == VEMapStyle.Birdseye ? map.GetBirdseyeScene().GetBoundingRectangle() : map.GetMapView();
                $.ajax(
                {
                    type: "POST",
                    url: "../webservices/clientservices.asmx/GetListingsPOST",
                    data: "{TLLat:"+view.TopLeftLatLong.Latitude+",TLLong:"+view.TopLeftLatLong.Longitude+",BRLat:"+view.BottomRightLatLong.Latitude+",BRLong:"+view.BottomRightLatLong.Longitude+",minPrice:"+price.MinPrice+",maxPrice:"+price.MaxPrice+",beds:"+parseInt($get('Beds').options[$get('Beds').selectedIndex].value)+",baths:"+parseFloat($get('Baths').options[$get('Baths').selectedIndex].value)+",sqrFeet:"+parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value)+",active:"+true+",city:"+null+",state:"+null+",zip:"+null+",srcs:"+(lm_sources != null?"'"+lm_sources+"'":null)+"}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(_request){ 
                        SearchComplete(_request);
                    },
                    error: function(msg){
                        alert(msg);
                    }                
                });
            }
            /*
            _request = ClientServices._staticInstance.GetListings(view.TopLeftLatLong,view.BottomRightLatLong,price.MinPrice, price.MaxPrice,
                parseInt($get('Beds').options[$get('Beds').selectedIndex].value),
                parseFloat($get('Baths').options[$get('Baths').selectedIndex].value),
                parseInt($get('SqrFeet').options[$get('SqrFeet').selectedIndex].value), true,//$get('Active').checked,
                null, null, null,lm_sources, SearchComplete, SearchFailed);
                */
        }
    }
}
function GetMinMaxPrice()
{
    var price = {"MinPrice" : -1, "MaxPrice" : -1};
    price.MinPrice = parseFloat($get('MinPrice').value.replace(",",""));
    price.MaxPrice = parseFloat($get('MaxPrice').value.replace(",",""));
    if(isFinite(price.MinPrice) && isFinite(price.MaxPrice))
    {
        if(price.MinPrice == 0 && price.MaxPrice == 0)
        {
            price.MinPrice = -1;
            price.MaxPrice = -1;
            $get('MinPrice').value = "MinPrice";
            $get('MaxPrice').value = "MaxPrice";
        }
        else if(price.MinPrice > price.MaxPrice && price.MaxPrice > 0)
        {
            price.MinPrice = price.MaxPrice;
            price.MaxPrice = parseFloat($get('MinPrice').value.replace(",",""));
            $get('MinPrice').value = price.MinPrice
            $get('MaxPrice').value = price.MaxPrice;
        }
        else if(price.MinPrice > price.MaxPrice && price.MaxPrice <= 0)
        {
            price.MaxPrice = -1;
            $get('MaxPrice').value = "MaxPrice";
        }
    }
    else if(!isFinite(price.MinPrice) && isFinite(price.MaxPrice))
    {
        price.MinPrice = -1;
        $get('MinPrice').value = "MinPrice";
        
    }
    else if(isFinite(price.MinPrice) && !isFinite(price.MaxPrice))
    {
        price.MaxPrice = -1;
        $get('MaxPrice').value = "MaxPrice";
    }
    else
    {
        price.MinPrice = -1; price.MaxPrice = -1;
        $get('MinPrice').value = "MinPrice";
        $get('MaxPrice').value = "MaxPrice";
    }
    return price;
}
function DisplayResults()
{
	var mapTableHead = null;
	var mapTableHeaders = null;
	var mapTableHeadRow = null;	
	//This prevents an infinite search loop
	doc.getElementsByTagName('body')[0].onresize = null;
	_totalPages = Math.ceil(_listings.listings.length / _pageSize);
	doc.getElementsByTagName('body')[0].onresize = function(){};
	//Load Datagrid for the first time
    if(!mapDataGrid)
    {
	    mapDataGrid = doc.createElement('table');
	    mapDataGrid.setAttribute('cellPadding', '2');
	    mapDataGrid.setAttribute('cellSpacing', '3');
	    mapDataGrid.style.width = '220px'; 
	    mapDataGrid.style.height = 'auto';
	    mapDataGrid.style.margin = '10px auto 0 auto';
	    $get('mapResultsGrid').appendChild(mapDataGrid);
		mapDataGridBody = doc.createElement('TBODY');
		mapDataGrid.appendChild(mapDataGridBody);	
	}
	Page(1,true);
    ResizeMap();
}
function AddHomePin(index)
{
    slPinPoints.DeleteAllShapes();
    _bulkPinPoints = new Array();
    for(var iLoopCnt = index; iLoopCnt < index + 10 && iLoopCnt < _listings.listings.length; iLoopCnt++)
    {
        var logo = '';
        if(_listings.sources != null){
		    for(var i = 0; i < _listings.sources.length;i++)
		    {
		        if(_listings.sources[i] == _listings.listings[iLoopCnt].Source)
		        {
		            logo = _listings.logos[i];
		            break;
		        }
		    }
		}
        var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(_listings.listings[iLoopCnt].Geo.Latitude, _listings.listings[iLoopCnt].Geo.Longitude));
        pin.SetCustomIcon('<div class="mapPin" id="cilisting_' + _listings.listings[iLoopCnt].Source + '_' + _listings.listings[iLoopCnt].MLSID + '" onclick="javascript:' + (showGuestbook == true ? 'if(AttachGuestBookData){AttachGuestBookData(\'/ListingDetails.aspx?homeID=' + _listings.listings[iLoopCnt].Source + '_' + _listings.listings[iLoopCnt].MLSID + '&rownum=' + (iLoopCnt + 1) + '\');}if(CheckForCookie(\'SoftDetailGB\',0, this.id)){' : '') + 'window.location=\'/ListingDetails.aspx?homeID=' + _listings.listings[iLoopCnt].Source + '_' + _listings.listings[iLoopCnt].MLSID + '&rownum=' + (iLoopCnt + 1) + '\';' + (showGuestbook ? '}' : '') + '">' + (iLoopCnt + 1) + '</div>');
        pin.SetTitle('<span style="float:left; font-weight: bold; color: #A31818;font-size:13px;">' + addCommas(_listings.listings[iLoopCnt].Core.PriceList) + '</span><span style="float:right;color:black;">' + _listings.listings[iLoopCnt].Address.Address + '</span><br clear="left">');
        pin.SetDescription('<a id="cipinlisting_' + _listings.listings[iLoopCnt].Source + '_' + _listings.listings[iLoopCnt].MLSID + '" ' + (showGuestbook == true ? 'onclick="if(AttachGuestBookData){AttachGuestBookData(\'/ListingDetails.aspx?homeID=' + _listings.listings[iLoopCnt].Source + '_' + _listings.listings[iLoopCnt].MLSID + '&rownum=' + (iLoopCnt + 1) + '\');} return CheckForCookie(\'SoftDetailGB\',0, this.id);" ' : '') + 'href="/ListingDetails.aspx?homeID=' + _listings.listings[iLoopCnt].Source +
         '_' + _listings.listings[iLoopCnt].MLSID + '&rownum=' + (iLoopCnt + 1) + '"><img src="' +
         (_listings.listings[iLoopCnt].Core.PrimaryPhoto && _listings.listings[iLoopCnt].Core.PrimaryPhoto.length > 0 ?
        _listings.listings[iLoopCnt].Core.PrimaryPhoto : 'http://images.dhmiservices.com/dhmcore/IDX/Default.gif') + '" width="85px" align="left"></a>' + '<div style="position:relative;left:8px;"><span style="text-align:left; color: black;">' +
        _listings.listings[iLoopCnt].Address.City + ' ' +
        _listings.listings[iLoopCnt].Address.State + ', ' + _listings.listings[iLoopCnt].Address.Zip + 
        '<br />MLSID# ' + _listings.listings[iLoopCnt].MLSID + '<br />' + 
        'Status: ' + _listings.listings[iLoopCnt].Core.ListingActiveStatus + 
        (_listings.listings[iLoopCnt].Core.Beds != null && _listings.listings[iLoopCnt].Core.Beds > 0 ? '<br />Beds: ' +  _listings.listings[iLoopCnt].Core.Beds : '') + 
        (_listings.listings[iLoopCnt].Core.Baths != null && _listings.listings[iLoopCnt].Core.Baths > 0 ? '<br />Baths: ' +  _listings.listings[iLoopCnt].Core.Baths : '') +
        (_listings.listings[iLoopCnt].Core.SquareFeet != null && _listings.listings[iLoopCnt].Core.SquareFeet > 0 ? '<br />SqFt: ' + _listings.listings[iLoopCnt].Core.SquareFeet : '') +
        (_listings.listings[iLoopCnt].Extended.DetailDisclosure != null && _listings.listings[iLoopCnt].Extended.DetailDisclosure.length > 0 ? '<br />' + _listings.listings[iLoopCnt].Extended.DetailDisclosure : '') + 
        '<br />' + '</span></div><div style="position:relative;left:8px;top:5px;">' + logo + '</div>' );
        _listings.listings[iLoopCnt].School = pin;
        _bulkPinPoints.push(_listings.listings[iLoopCnt].School);
    }
    
    $get('mapStatusText').innerHTML = 'Results '+((index*1)+1) +' - ' + iLoopCnt + ' of '+ _listings.listings.length;
    slPinPoints.AddShape(_bulkPinPoints);
    map.SetMapView(_bulkPinPoints);
}
function Page(page,initialDisplay) {

    //Joe 6/30/08
    ClearRoute();
    
    if(!_listings.listings) return false;
    if(_listings.listings.length < 1 || !_listings.listings[0])
    { 
        ToggleLeftColDiv('noResults');
        return false;
    }
    else
        RemoveLeftColData();
        
    //Keep page in bounds
    _currentPage = page < 1 ? 1 : page > _totalPages ? _totalPages : page;
    var count = 0;
    var styles = new Array();
	styles[0] = 'mapRow1';
	styles[1] = 'mapRow2';
	
    if(divPaging)
    {
        $get('mapResultsGrid').removeChild(divPaging);
	    divPaging.innerText = '';
	    $get('mapResultsGrid').insertBefore(divPaging, mapDataGrid);
	}
	else
	{
	    divPaging = doc.createElement('div');
	    divPaging.id = 'divPagingLocal';
	    divPaging.style.textAlign = 'center';
	    divPaging.style.fontSize = "11px";
	    divPaging.className = 'paging';
	    $get('mapResultsGrid').insertBefore(divPaging, mapDataGrid);
	}
	var divPagingLocal = divPaging;
    
	//added to put 10 listings at a time on Map
    AddHomePin((page-1)*_pageSize);
    
	//Start Paging
	if(_totalPages > 1)
	{
        var prevLink = doc.createElement('a');
        if(_currentPage == 1)
            prevLink.onclick = function() { return false; };
        else
            prevLink.href = 'javascript:Page(_currentPage - 1);';
        prevLink.innerHTML = '<img src="http://images.dhmiservices.com/dhmcore/arrow_left.gif"/>';
        divPagingLocal.appendChild(prevLink);
    	var index=1;
    	if(_totalPages == 1)
            prevLink.disabled = true;
        
        if(_currentPage > 6 || (_totalPages - _currentPage < 5 && _totalPages > 6))
        {
            index = _currentPage;
            if(index+5 > _totalPages)
	            index = _totalPages - 5;
	        else if((index + 5) % 6 > 0)
	        {
	            index = index - ((index + 5) % 6);
	        }
	        if(index < 0)index = 1;
	        var firstLink = doc.createElement('a');
	        firstLink.href = 'javascript:Page(1);';
	        firstLink.innerText = 1;
	        var prevJumpLink = doc.createElement('a');
	        prevJumpLink.href = 'javascript:Page('+(index - 1)+');';
	        prevJumpLink.innerText = "...";
		    divPagingLocal.innerHTML += '&nbsp;&nbsp;';
	        divPagingLocal.appendChild(firstLink);
		    divPagingLocal.innerHTML += '&nbsp;&nbsp;';
	        divPagingLocal.appendChild(prevJumpLink);
	        
        }
	    for(var iLoopCnt = index; iLoopCnt <= index + 5 && iLoopCnt <= _totalPages; iLoopCnt++)
	    {
	        divPagingLocal.innerHTML += '&nbsp;';
    	    
		    var navLink = doc.createElement('a');
	        navLink.href = 'javascript:Page(' + iLoopCnt + ');';
	        if(iLoopCnt == _currentPage)
	            navLink.className = "currentPage";
		    navLink.innerText = iLoopCnt;
	        divPagingLocal.appendChild(navLink);
	    }
    	
	    divPagingLocal.innerHTML += '&nbsp;&nbsp;';

        var nextLink = doc.createElement('a');
        if(_currentPage == _totalPages)
            nextLink.onclick = function() { return false; };
        else
            nextLink.href = 'javascript:Page(_currentPage + 1);';
        nextLink.innerHTML = '<img src="http://images.dhmiservices.com/dhmcore/arrow_right.gif"/>';
	    if(iLoopCnt == _totalPages)
            nextLink.disabled = true;
        //set up prevLink   
        
        if(_currentPage+5 < _totalPages || (_currentPage+5 == _totalPages && iLoopCnt < _totalPages))
        {
            var nextJumpLink = doc.createElement('a');
	        nextJumpLink.href = 'javascript:Page('+(index + 6)+');';
	        nextJumpLink.innerText = "...";
	        divPagingLocal.appendChild(nextJumpLink);
	        divPagingLocal.innerHTML += '&nbsp;&nbsp;';
	        var lastlink = doc.createElement('a');
	        lastlink.href='javascript:Page('+_totalPages+');';
	        lastlink.innerText = _totalPages;
	        divPagingLocal.appendChild(lastlink);
	        divPagingLocal.innerHTML += '&nbsp;&nbsp;';
        }
        divPagingLocal.appendChild(nextLink);
	    divPagingLocal.innerHTML += '<br />';
	}
	else
	{
	   divPagingLocal.innerHTML += '<br style="line-height: 20px;"/>'; 
	}
	//End Paging  
	clearChildren(mapDataGridBody);
	mapDataGridBody.appendChild(doc.createTextNode(""));
    //Fill Datagrid
    var sources = new Array();
    var mlsnums = new Array();
		
	var funcCrPopUp = CreatePopUp;	
	for(var iLoopCnt = ((_currentPage - 1) * _pageSize); iLoopCnt < _pageSize + ((_currentPage - 1) * _pageSize)
	    && iLoopCnt < _listings.listings.length; iLoopCnt++)
    {	
        ItemDetails[iLoopCnt]= new Array();
        ItemDetails[iLoopCnt][0] = _listings.listings[iLoopCnt].Address.Address;
        ItemDetails[iLoopCnt][1] = _listings.listings[iLoopCnt].Core.PriceList;
        ItemDetails[iLoopCnt][2] = _listings.listings[iLoopCnt].Core.PrimaryPhoto;
        ItemDetails[iLoopCnt][3] = _listings.listings[iLoopCnt].Address.City;
        ItemDetails[iLoopCnt][4] = _listings.listings[iLoopCnt].Address.State;
        ItemDetails[iLoopCnt][5] = _listings.listings[iLoopCnt].Address.Zip;
        ItemDetails[iLoopCnt][6] = _listings.listings[iLoopCnt].Source;
        ItemDetails[iLoopCnt][7] = _listings.listings[iLoopCnt].MLSID;
        
		var mapRow = doc.createElement('tr');
		if(!isIE){
		    mapRow.style.position = 'relative';
		    mapRow.style.zIndex = '10';
		}
		mapRow.id = "houseRow_"+iLoopCnt;
		sources.push(_listings.listings[iLoopCnt].Source);
		mlsnums.push(_listings.listings[iLoopCnt].MLSID);
		//mapRow.className = styles[iLoopCnt % 2];
		mapRow.className = 'listing';
		mapRow.style.marginTop = "3px";
		
		
		funcCrPopUp(mapRow, _listings.listings[iLoopCnt].School, styles[iLoopCnt % 2]);
			
	    mapCell1 = doc.createElement('td');
	    mapCell1.style.border = '1px solid #b5b5b5';
	    //mapCell1.className = 'listing';
	    mapCell1.style.cursor = 'pointer';
	    if(navigator.appName=="Netscape"){//fix for map links not working in firefox
	        if(showGuestbook)
            {
	            mapCell1.setAttribute("onclick","if(AttachGuestBookData){AttachGuestBookData(\'/ListingDetails.aspx?homeID='+_listings.listings["+iLoopCnt+"].Source+'_'+_listings.listings["+iLoopCnt+"].MLSID+'&rownum='+("+iLoopCnt+"+1)+'\');} if(CheckForCookie('SoftDetailGB',0, this.id)){window.location='/ListingDetails.aspx?homeID='+_listings.listings["+iLoopCnt+"].Source+'_'+_listings.listings["+iLoopCnt+"].MLSID+'&rownum="+(iLoopCnt + 1)+"';}");  
	        }else{
	            mapCell1.setAttribute("onclick","window.location='/ListingDetails.aspx?homeID='+_listings.listings["+iLoopCnt+"].Source+'_'+_listings.listings["+iLoopCnt+"].MLSID+'&rownum="+(iLoopCnt + 1)+"'");  
	        }
	    }
	    if(isIE)
	        mapCell1.style.height = "40px";
	    else
	        mapCell1.style.height = "45px";
	    var link = doc.createElement('a')
	    if(showGuestbook)
        {
            if ((navigator.appName=="Microsoft Internet Explorer" && parseInt(navigator.appVersion)<=7)){
                //link.onclick = "if(AttachGuestBookData){AttachGuestBookData(\'/ListingDetails.aspx?homeID='+_listings.listings["+iLoopCnt+"].Source+'_'+_listings.listings["+iLoopCnt+"].MLSID+'&rownum='+("+iLoopCnt+"+1)+'\');} return ShowUserPopUp(\'guestbook\', this.id);";
                link.onclick = "if(AttachGuestBookData){AttachGuestBookData(\'/ListingDetails.aspx?homeID='+_listings.listings["+iLoopCnt+"].Source+'_'+_listings.listings["+iLoopCnt+"].MLSID+'&rownum='+("+iLoopCnt+"+1)+'\');} return CheckForCookie('SoftDetailGB',0, this.id);";
            }else{
                //link.setAttribute("onclick","if(AttachGuestBookData){AttachGuestBookData(\'/ListingDetails.aspx?homeID='+_listings.listings["+iLoopCnt+"].Source+'_'+_listings.listings["+iLoopCnt+"].MLSID+'&rownum='+("+iLoopCnt+"+1)+'\');} return ShowUserPopUp(\'guestbook\', this.id);");  
                link.setAttribute("onclick","if(AttachGuestBookData){AttachGuestBookData(\'/ListingDetails.aspx?homeID='+_listings.listings["+iLoopCnt+"].Source+'_'+_listings.listings["+iLoopCnt+"].MLSID+'&rownum='+("+iLoopCnt+"+1)+'\');} return CheckForCookie('SoftDetailGB',0, this.id);");  
            }
        }
        link.id = 'linklisting_' + _listings.listings[iLoopCnt].Source + '_' + _listings.listings[iLoopCnt].MLSID;
	    link.href = '/ListingDetails.aspx?homeID='+_listings.listings[iLoopCnt].Source+'_'+_listings.listings[iLoopCnt].MLSID+'&rownum='+(iLoopCnt + 1);
	    link.title = "Click to View Listing";
	    link.style.textDecoration = 'none';
	    link.style.display = 'block';
	    var logo = '';
	    if(_listings.sources != null){
		    for(var i = 0; i < _listings.sources.length;i++)
		    {
		        if(_listings.sources[i] == _listings.listings[iLoopCnt].Source)
		        {
		            logo = _listings.logos[i];
		            break;
		        }
		    }
		}
		if (_listings.listings[iLoopCnt].Source != 328) {
		    if (_listings.listings[iLoopCnt].Core.PrimaryPhoto.length > 0)
		        link.innerHTML += '<div style="float:left;width:55px;height:auto;"><img src="' + _listings.listings[iLoopCnt].Core.PrimaryPhoto + '" width="50" style="margin-right: 5px;"><div style="margin-top:5px;">' + logo + '</div></div>';
		    else
		        link.innerHTML += '<div style="float:left;width:55px;height:auto;"><img src="http://images.dhmiservices.com/dhmcore/IDX/no_pic_95x63.gif" width="50" style="margin-right: 5px;"><div style="margin-top:5px;">' + logo + '</div></div>';
		} else {
		if (_listings.listings[iLoopCnt].Core.PrimaryPhoto.length > 0)
		    link.innerHTML += '<div style="float:left;width:55px;height:auto;"><img src="' + _listings.listings[iLoopCnt].Core.PrimaryPhoto + '" width="50" style="margin-right: 5px;"></div>';
		else
		    link.innerHTML += '<div style="float:left;width:55px;height:auto;"><img src="http://images.dhmiservices.com/dhmcore/IDX/no_pic_95x63.gif" width="50" style="margin-right: 5px;"></div>';

		}
		mapCell1.style.fontSize ="9px";
		mapCell1.style.fontFamily= "Tahoma,sans-serif";
		mapCell1.style.position = "relative";
		mapCell1.style.textAlign = "left";
		mapCell1.style.verticalAlign = "top";
		var add_btn_pos = 'margin-top:-23px;';
		//mapCell1.innerHTML += '<div style="width:55px;float:right;" style="'+add_btn_pos+'"><img src="http://images.dhmiservices.com/dhmcore/IDX/MapView/map_add_directions_btn.gif" id="directionsGroup_' + iLoopCnt +'" name="directionsGroup" onClick="AddToDirections(this);" alt="Click to add to your directions!" /></div>';    
		var citystate = "";
		var state = "";
		if(_listings.listings[iLoopCnt].Address.State.length > 0)
		    state = stateToAbb(_listings.listings[iLoopCnt].Address.State.toLowerCase());
		else
		    state = _listings.listings[iLoopCnt].Address.State;
		if(_listings.listings[iLoopCnt].Address.City.length>0 && _listings.listings[iLoopCnt].Address.State.length > 0)
		    citystate = _listings.listings[iLoopCnt].Address.City+', '+state;
		else if(_listings.listings[iLoopCnt].Address.City.length > 0 && _listings.listings[iLoopCnt].Address.State.length == 0)
		    citystate = _listings.listings[iLoopCnt].Address.City;
		else if(_listings.listings[iLoopCnt].Address.City.length == 0 && _listings.listings[iLoopCnt].Address.State.length > 0)
		    citystate = state; 
		link.innerHTML +='<div><span style="color: #a54b4d; font-weight: bold;">'+addCommas(_listings.listings[iLoopCnt].Core.PriceList)+'</span></div>';
		if(_listings.listings[iLoopCnt].Core.ListingActiveStatus.length > 0)
		    link.innerHTML +='<div><span class="smBoldDescTxt detailText">Status: ' + _listings.listings[iLoopCnt].Core.ListingActiveStatus + '</span></div>';
		link.innerHTML +='<div><span class="smBoldDescTxt detailText">MLSID# ' + _listings.listings[iLoopCnt].MLSID + '</span></div>';
		
		link.innerHTML +='<div><span class="smBoldDescTxt detailText">'+citystate+'</span></div><div>' + (_listings.listings[iLoopCnt].Core.SquareFeet.length > 0?'<span class="smBoldDescTxt detailText">SqFt: '+_listings.listings[iLoopCnt].Core.SquareFeet+'</span></div>':'');
		
		if(_listings.listings[iLoopCnt].Core.Beds>0 && _listings.listings[iLoopCnt].Core.Baths>0){
		    link.innerHTML += '<div><span class="smBoldDescTxt detailText">'+_listings.listings[iLoopCnt].Core.Beds + ' Beds</span><span class="smBoldDescTxt detailText">/ '+_listings.listings[iLoopCnt].Core.Baths+ ' Baths</span></div>';
		}
		//set up to stop based on toggle for show office, but not used currently
		//if(showOffice)
		link.innerHTML += '<div><span class="smBoldDescTxt detailText">'+_listings.listings[iLoopCnt].Extended.DetailDisclosure+'</span></div>';
		//link.innerHTML += '</div>';
		mapCell1.appendChild(link);
		if (_listings.listings[iLoopCnt].Source == 328) {
		    link.innerHTML += '<div style="float:left;">' + logo + '</div>';
		}
		mapCell1.innerHTML += '<div style="width:55px;float:right;" style="'+add_btn_pos+'"><img src="http://images.dhmiservices.com/dhmcore/IDX/MapView/map_add_directions_btn.gif" id="directionsGroup_' + iLoopCnt +'" name="directionsGroup" onClick="AddToDirections(this);" alt="Click to add to your directions!" /></div>'; 
		//mapCell1.innerHTML += '<div><span class="smBoldDescTxt detailText">'+_listings.listings[iLoopCnt].Extended.DetailDisclosure.substring(0,24)+'...</span></div>';
		mapRow.appendChild(mapCell1);
		mapDataGridBody.appendChild(mapRow);
		count++;
    }
    mapDataGrid.appendChild(mapDataGridBody);
    var clientsrcs = '';
    var clientmls = '';
    for(var i = 0; i < sources.length; i++)
        clientsrcs += (clientsrcs.length > 0?"|":"")+sources[i];
    for(var i = 0; i < mlsnums.length; i++)
        clientmls += (clientmls.length > 0?"|":"")+mlsnums[i];
    //Reporting
    $.ajax(
            {
                type: "POST",
                url: "../webservices/clientservices.asmx/ReportImpressionPOST",
                data: "{sources:'"+clientsrcs+"',mlsnums:'"+clientmls+"'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });   
     //ClientServices.ReportImpression(sources, mlsnums);
}

function CreatePopUp(row, pin, className)
{
	var popup = doc.createElement('div');
	popup.innerHTML = pin._IconContent;
	popup = popup.childNodes[0];
	var pinId = pin._IconContent.substring(pin._IconContent.indexOf("msftve")).substring(0,pin._IconContent.substring(pin._IconContent.indexOf("msftve")).indexOf('"'));
	var PinLink;
	if($get(pinId))
		PinLink = $get(pinId);
	row.dhm_popup = popup;
	row.dhm_class = className;
	row.dhm_pinLink = PinLink;
	row.onmouseover = PopupMouseover;
	row.onmouseout = PopupMouseout;
}
function PopupMouseover()
{
    if(!this.dhm_popup)return;
	var popup = this.dhm_popup;
	if(this.onmouseout) 
		if(popup.onmouseover)
			popup.onmouseover();
	this.className = 'mapRowHighlight';
	var indx = this.id.substring(9);
	_listings.listings[indx].School.SetCustomIcon('<div class="mapPinRed" id="rpinlisting_' + _listings.listings[indx].Source + '_' + _listings.listings[indx].MLSID+'" onclick="javascript:'+(showGuestbook==true?'if(AttachGuestBookData){AttachGuestBookData(\'/ListingDetails.aspx?homeID='+_listings.listings[indx].Source+'_'+_listings.listings[indx].MLSID+'&rownum='+((indx*1)+1)+'\');}if(ShowUserPopUp(\'guestbook\', this.id)){':'')+'window.location=\'/ListingDetails.aspx?homeID='+_listings.listings[indx].Source+'_'+_listings.listings[indx].MLSID+'&rownum='+ ((indx*1) + 1) +'\';'+(showGuestbook?'}':'')+'">' + ((indx*1) + 1) + '</div>');
	///this.dhm_pinLink.style.zIndex=(indx*1) + 1011;
}
function PopupMouseout(){ 
	if(!this.dhm_popup)return;
	var popup = this.dhm_popup;
	if(this.onmouseout) 
		if(popup.onmouseover){
			popup.onmouseout();
		} 
	//this.className = this.dhm_class; 
	this.className = 'listing'; 
	var indx = this.id.substring(9);
	_listings.listings[indx].School.SetCustomIcon('<div class="mapPin" id="bpinlisting_' + _listings.listings[indx].Source + '_' + _listings.listings[indx].MLSID+'" onclick="javascript:'+(showGuestbook==true?'if(AttachGuestBookData){AttachGuestBookData(\'/ListingDetails.aspx?homeID='+_listings.listings[indx].Source+'_'+_listings.listings[indx].MLSID+'&rownum='+((indx*1)+1)+'\');}if(ShowUserPopUp(\'guestbook\', this.id)){':'')+'window.location=\'/ListingDetails.aspx?homeID='+_listings.listings[indx].Source+'_'+_listings.listings[indx].MLSID+'&rownum='+ ((indx*1) + 1) +'\';'+(showGuestbook?'}':'')+'">' + ((indx*1) + 1) + '</div>');
	//this.dhm_pinLink.style.zIndex=(indx*1)+1000;
}
function ToggleModifySearch()
{
    var button = $get('btnModifySearch');
    if (button)
    {
        if(button.src.substring(button.src.indexOf("MapView/")) == "MapView/close_tab.gif")
        {
            $get('pnlFlash').style.display = 'none';
            button.src = "http://images.dhmiservices.com/dhmcore/IDX/MapView/filter.gif";
            button.style.cursor = 'auto';
            button.detachEvent("onclick",ToggleModifySearch);
            $get('pnlModify').style.display = 'block';
        }
        else
        {
            $get('pnlFlash').style.display = 'block';
            button.src = "http://images.dhmiservices.com/dhmcore/IDX/MapView/close_tab.gif";
            button.style.cursor = 'pointer';
            button.attachEvent("onclick",ToggleModifySearch);
            $get('pnlModify').style.display = 'none';
        }
    }
}
function FixFlashObject()
{
   $get('flashContainer').innerHTML = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" WIDTH="480" HEIGHT="80" id="myMovieName" name="myMovieName"><PARAM NAME="movie" VALUE="/FlashObjects/small_map.swf"><PARAM NAME="FlashVars" value="quality=high&bgcolor=#FFFFFF"></OBJECT>';
}


function runSort()
{
    var type = $get('sortType');
    var dir = $get('sortDir');
    if(type && type.options[type.selectedIndex].value != "N/A" && dir)
        OrderColumns(type.options[type.selectedIndex].value,dir.options[dir.selectedIndex].value);
}
function OrderColumns(column,dir)
{
    switch(column)
    {
        case 'address':
            if(dir  == "DESC")
                _sortAddressAsc = Math.abs(_sortAddressAsc) * -1;
            else
                _sortAddressAsc = Math.abs(_sortAddressAsc);
            _listings.listings.sort(AddressSort);
            DisplayResults();
            break;
        case 'city':
            if(dir  == "DESC")
                _sortCityAsc = Math.abs(_sortAddressAsc) * -1;
            else
                _sortCityAsc = Math.abs(_sortAddressAsc);
            _listings.listings.sort(CitySort);
            DisplayResults();
            break;
        case 'price':
            if(dir  == "DESC")
                _sortPriceAsc = Math.abs(_sortAddressAsc) * -1;
            else
                _sortPriceAsc = Math.abs(_sortAddressAsc);
            _listings.listings.sort(PriceSort);
            DisplayResults();
            break;
        case 'beds':
            if(dir  == "DESC")
                _sortBedsAsc = Math.abs(_sortAddressAsc) * -1;
            else
                _sortBedsAsc = Math.abs(_sortAddressAsc);
            _listings.listings.sort(BedsSort);
            DisplayResults();
            break;
        case 'baths':
            if(dir  == "DESC")
                _sortBathsAsc = Math.abs(_sortAddressAsc) * -1;
            else
                _sortBathsAsc = Math.abs(_sortAddressAsc);
            _listings.listings.sort(BathsSort);
            DisplayResults();
            break;
        case 'status':
            if(dir  == "DESC")
                _sortStatusAsc = Math.abs(_sortAddressAsc) * -1;
            else
                _sortStatusAsc = Math.abs(_sortAddressAsc);
            _listings.listings.sort(StatusSort);
            DisplayResults();
            break;
        case 'sqrfeet':
            if(dir  == "DESC")
                _sortSqrFeetAsc = Math.abs(_sortAddressAsc) * -1;
            else
                _sortSqrFeetAsc = Math.abs(_sortAddressAsc);
            _listings.listings.sort(SqrFeetSort);
            DisplayResults();
            break;
    }
}
function AddressSort(a, b)
{
    var addressA = a.Address.Address.toLowerCase();
    var addressB = b.Address.Address.toLowerCase();
    
    if(addressA == addressB)
        return 0;
    //compare each character
    for(var iLoopCnt = 0; iLoopCnt < addressA.length && iLoopCnt < addressB.length; iLoopCnt++)
    {
        if(addressA.charAt(iLoopCnt) > addressB.charAt(iLoopCnt)) return _sortAddressAsc;
        else if(addressA.charAt(iLoopCnt) < addressB.charAt(iLoopCnt)) return - 1 * _sortAddressAsc;
    }
    //Shortest comes first
    if(addressA.length < addressB.length)return _sortAddressAsc;
    else return - 1 * _sortAddressAsc;
}
function CitySort(a, b){
    var cityA = a.Address.City.toLowerCase();
    var cityB = b.Address.City.toLowerCase();
    
    if(cityA == cityB)
        return 0;
    for(var iLoopCnt = 0; iLoopCnt < cityA.length && iLoopCnt < cityB.length; iLoopCnt++)
    {
        if(cityA.charAt(iLoopCnt) > cityB.charAt(iLoopCnt)) return _sortCityAsc;
        else if(cityA.charAt(iLoopCnt) < cityB.charAt(iLoopCnt)) return - 1 * _sortCityAsc;
    }
    if(cityA.length < cityB.length)return _sortCityAsc;
    else return - 1 * _sortCityAsc;
}
function PriceSort(a, b)
{
    return (a.Core.PriceList - b.Core.PriceList) * _sortPriceAsc;
}
function BedsSort(a, b)
{
    return (a.Core.Beds - b.Core.Beds) * _sortBedsAsc;
}
function BathsSort(a, b)
{
    return (a.Core.Baths - b.Core.Baths) * _sortBathsAsc;
}
function StatusSort(a, b)
{
    var statusA = a.Core.ListingActiveStatus.toLowerCase();
    var statusB = b.Core.ListingActiveStatus.toLowerCase();
    
    if(statusA == statusB)
        return 0;
    for(var iLoopCnt = 0; iLoopCnt < statusA.length && iLoopCnt < statusB.length; iLoopCnt++)
    {
        if(statusA.charAt(iLoopCnt) > statusB.charAt(iLoopCnt)) return _sortStatusAsc;
        else if(statusA.charAt(iLoopCnt) < statusB.charAt(iLoopCnt)) return - 1 * _sortStatusAsc;
    }
    if(statusA.length < statusB.length)return _sortStatusAsc;
    else return - 1 * _sortStatusAsc;
}
function SqrFeetSort(a, b)
{
    if(!a) a = 0;
    if(!b) b = 0;
    return (a.Core.SquareFeet - b.Core.SquareFeet) * _sortSqrFeetAsc;
}

function SearchComplete(listingPack)
{
    if(!listingPack) return;
    slPinPoints.DeleteAllShapes();
    ClearGrid();
    //No _listings.listings = Error
    $get('messageDiv').appendChild(doc.createTextNode(listingPack.message));
    $get('messageDiv').innerHTML = listingPack.message;
    if(!listingPack.listings)
    {
        $get('mapStatusText').innerHTML = 'Error';/*listingPack.message;*/
        return;
    }
    if (_listings && _listings.paging) {
        for(var i = 0; i < listingPack.listings.length; i++)
            _listings.listings.push(listingPack.listings[i]);
    }
    else   
        _listings = listingPack;
    if(lm_customSort)
        OrderColumns(lm_sortby,lm_sortdir);
    DisplayResults();
}
function SearchFailed(e)
{
    if (_request && !_request.get_executor().get_aborted())
        alert('Search Failed!\nMessage:\t\t' + e._message + 
            '\nStack Trace:\t' + e._stackTrace);
}
function InitializeParameters(lat,log, state, city, zip, minPrice,maxPrice ,beds, baths, sqrft, source, limitcities, defaultsortby, defautsortdir)
{
    ToggleLeftColDiv('searching');
    GetMLSBounds();

    if(GetStates)
        GetStates(true);
    if(defaultsortby && defautsortdir)
    {
        lm_customSort = true;
        lm_sortby = defaultsortby;
        lm_sortdir = defautsortdir;
    }
    if(state)
    {
        if (limitcities) {
            if (city.indexOf(",") > 0) {
                var citylist = city.split(',');
                if (citylist.length > 0) {
                    _limitedCitiesList = "";
                    for (var i = 0; i < citylist.length; i++) {
                        if (citylist[i] != null) {
                            _limitedCitiesList += trim(citylist[i].substring(0, citylist[i].indexOf("(")));
                            if (i != (citylist.length - 1))
                                _limitedCitiesList += "|";
                        }
                    }
                }
            } else {
            _limitedCitiesList = city;
            }
        }
        lm_search = true; 
        if(city) lm_city = city;
        if(state) lm_state = state; 
        if(PopulateCheck)
            PopulateCheck(lm_state,lm_city);
        lm_customView = true;
        lm_useMapFind = true;
        if(_runRefresh != null)
            _runRefresh = true;
    }
    if(lat && log)
    {
        lm_x = lat;
        lm_y = log;
        lm_customView = true;
        lm_zoom = 8;
    }
    if(zip)
    {
        lm_search = true; 
        var ELzip = $get('Zip');
        if(ELzip)
            ELzip.value = zip;
    }
    if(minPrice)
    {
        var ELminPrice = $get('MinPrice');
        if(ELminPrice)
            ELminPrice.value = minPrice;
    }
    if(maxPrice)
    {
        var ELmaxPrice = $get('MaxPrice');
        if(ELmaxPrice)
            ELmaxPrice.value = maxPrice;
    }
    if(beds)
    {
        var ELbeds = $get('Beds');
        if(ELbeds)
        {
            for (var iLoopCnt = 0; iLoopCnt<ELbeds.options.length; iLoopCnt++)
            {
                if(ELbeds.options[iLoopCnt].value == beds)
                    ELbeds.options[iLoopCnt].selected = true;
            }
        }
    }
    if(baths)
    {
        var ELbaths = $get('Baths');
        if(ELbaths)
        {
            for (var iLoopCnt = 0; iLoopCnt<ELbaths.options.length; iLoopCnt++)
            {
                if(ELbaths.options[iLoopCnt].value == baths)
                    ELbaths.options[iLoopCnt].selected = true;
            }
        }
    }
    if(sqrft)
    {
        var ELsqrft = $get('SqrFeet');
        if(ELsqrft)
        {
            for (var iLoopCnt = 0; iLoopCnt<ELsqrft.options.length; iLoopCnt++)
            {
                if((ELsqrft.options[iLoopCnt].value*1) > (sqrft*1))
                {
                    ELsqrft.options[(iLoopCnt>0?iLoopCnt-1:0)].selected = true;
                    iLoopCnt=ELsqrft.options.length;
                }
            }
        }
    }
    if(source)
        lm_sources = source;
    /*end prepopulation code 02/03/09 Jon Hudson*/
    
    /*added getmap to end of function to keep events in order.  This keeps the life cycle in line.*/
    GetMap();
    
}
function GetMap()
{
    var QS = new Querystring();
    if(QS['zoom'])
        lm_zoom = QS['zoom'];
    /*added function call to mapV2.aspx on 6/9/09 instead of leaving here
    InitializeParameters(QS['latitude'],QS['longitude'],QS['state'],QS['city'],QS['zip'],QS['minprice'],QS['maxprice'],QS['beds'],QS['baths'],QS['sqrft'],QS['sourceId']);*/
    
    
    /*Load Cookies*/
    var polyCookie = ReadCookie('MapPolyPoints');
    if(polyCookie && !lm_customView)
    {
        var polyPoint = polyCookie.split(',');
        for (var iLoopCnt = 0; iLoopCnt < polyPoint.length; iLoopCnt++)
            _myPoints.push(new VELatLong(
                parseFloat(polyPoint[iLoopCnt].split(':')[0]), parseFloat(polyPoint[iLoopCnt].split(':')[1])));
    }
    /*End Load Cookies*/
    $get('divMap').style.width = $get('divMap').parentNode.offsetWidth + 'px';
    map = new VEMap('divMap');  
    map.LoadMap(new VELatLong(lm_x, lm_y ), lm_zoom, lm_mode, false);
    map.ClearInfoBoxStyles();
    if(_initialBounds && _boundsLoaded && !lm_customView)
    {
        map.SetMapView(_initialBounds);
        lm_search = true;
    }
    _localMap = new LocalMap(map);
    ResizeMap();
    map.AddShapeLayer(slDrawing);
    map.AddShapeLayer(slPinPoints);   
    if(_myPoints.length > 0)
    {
        $get('polySearch').src = 'http://images.dhmiservices.com/dhmcore/IDX/MapView/stop_btn.gif';
        $get('polySearch').onclick = ClearMap;
        $get('polyimage').onclick = ClearMap;
        SearchPoly();
        return true;
    }
    else if(lm_search)
    {
        if(lm_useMapFind)
            map.Find(null, lm_city+", "+lm_state+", United States", null, null, 0, 1, false,false,false,true, MoreResults);
        if(!_runRefresh)
            Refresh();
    }
    _mapLoaded = true;
}
function ClearMap()
{
    AbortRequest();
    ClearGrid();
    map.DetachEvent("onclick", DrawPolyMouseClick);
    map.DetachEvent("onmousemove", DrawPolyMouseMove);
    
    slDrawing.DeleteAllShapes();
    slPinPoints.DeleteAllShapes();
    /* added to put back Drawing div if Stop button was clicked for clearmap so that instructions stay visible */
    if($get('polySearch').src == 'http://images.dhmiservices.com/dhmcore/IDX/MapView/stop_btn.gif')
        ToggleLeftColDiv('Drawing');
    $get('polySearch').src = 'http://images.dhmiservices.com/dhmcore/IDX/MapView/start_btn.gif';
    $get('polySearch').onclick = Draw;
    $get('polyimage').onclick = Draw;
    _myPoints = new Array();
    EraseCookie('MapPolyPoints');
    $get("divMap").style.cursor = 'http://maps.live.com/cursors/grab.cur';
}
function ClearGrid()
{
    if($get('pagingHeader'))
        $get('pagingHeader').innerText = "";
    _currentPage = 1; _totalPages = 0;
    if(divPaging)
    {
        $get('mapResultsGrid').removeChild(divPaging);
        divPaging.innerText = "";
        divPaging = null;
    }
    if(mapDataGrid)
    {
        clearChildren(mapDataGrid);
        mapDataGrid.appendChild(doc.createTextNode(""));
        //mapDataGrid.innerText = mdgtext;
        $get('mapResultsGrid').removeChild(mapDataGrid);
        mapDataGrid = null;
    }
    if($get('noResultsImg'))
    {
        var img = $get('noResultsImg');
        $get('mapResultsGrid').removeChild(img);
    }
}
function ResizeMap() //resize
{
    if (map != null)
        map.Resize($get('divMap').parentNode.offsetWidth - 10, mapHeight); //-10 = padding
}
function SaveCookie()
{
    var style = map.GetMapStyle();
    if (style == VEMapStyle.Birdseye)
    {
        return;
    }
    var cookieValue;
    if(_myPoints.length > 2)
    {
        cookieValue = '';
        for (var iLoopCnt = 0; iLoopCnt < _myPoints.length; iLoopCnt++)
            cookieValue += _myPoints[iLoopCnt].Latitude + ':' + _myPoints[iLoopCnt].Longitude + ',';
        cookieValue = cookieValue.substring(0,cookieValue.length-1);
        CreateCookie('MapPolyPoints', cookieValue, 1);
    }
}
function AbortRequest()
{
    if(!_request) return;
    
    $get('mapStatusText').innerText = 'Cancelling Previous Search....';
    var executor = _request.get_executor();

    if (executor.get_started())
        executor.abort();
        
    ToggleLeftColDiv('Idle');
}
function UnloadMap() //dispose map etc
{
    ClearGrid();
    AbortRequest();
    if (map != null)
	{
		map.ClearInfoBoxStyles();
        map.Dispose();
	}
}
function BoundsSuccess(result)
{
    _initialBounds = new VELatLongRectangle(
        new VELatLong(result[0].Latitude, result[0].Longitude), new VELatLong(result[1].Latitude, result[1].Longitude),
        new VELatLong(result[0].Latitude, result[1].Longitude), new VELatLong(result[1].Latitude, result[0].Longitude));
       if(_mapLoaded)
            map.SetMapView(_initialBounds);
        _boundsLoaded = true;
        if(!lm_search)
            Refresh();
} 
function BoundsFailed(error)
{
    if (_request && !_request.get_executor().get_aborted())
            alert('Search Failed!\nMessage:\t\t' + error._message + 
                '\nStack Trace:\t' + error._stackTrace);
                
}

function SetXYCoordinate(rowID,ObjPopUpDiv)
{
    var height = ObjPopUpDiv.offsetHeight;
    var width = ObjPopUpDiv.offsetWidth;
    var xyCoords = { x: $get(rowID).offsetLeft, y: $get(rowID).offsetTop };

    //Internet Explorer Requires Offset of all parents
    if(isIE){
        tempcontrol = $get(rowID).offsetParent;
        while(tempcontrol)
        {
            if(tempcontrol.offsetParent)
            {
                xyCoords.x += tempcontrol.offsetLeft;
                xyCoords.y += tempcontrol.offsetTop;
            }
            tempcontrol = tempcontrol.offsetParent;
         }
    }else{
         xyCoords.x += $get(rowID).offsetParent.offsetLeft;
         xyCoords.y += $get(rowID).offsetParent.offsetTop;
    }
    if($get(rowID))
    {
        ObjPopUpDiv.style.top = (xyCoords.y-(height/2)+5)+'px'; //center vertically
        ObjPopUpDiv.style.left = (xyCoords.x+40)+'px'; //indent 40px
    }
    else
        return;
    //alert(rowID);
}
function PopUpItemDetails(id)
{
    _hide = false;
    var integerIndex = id.substring(id.lastIndexOf("_")+1);
    var popUpDiv = $get('itemDetailPopUpDiv')
    if(!popUpDiv)
    {
        popUpDiv = doc.createElement('div');
        popUpDiv.setAttribute('id','itemDetailPopUpDiv');
        BGpopUpDiv = doc.createElement('div');
        BGpopUpDiv.setAttribute('id','itemDetailBackgroundDiv');
        contentDiv = doc.createElement('div');
        contentDiv.setAttribute('id','itemContentDiv');
        doc.body.appendChild(popUpDiv);
        popUpDiv.appendChild(BGpopUpDiv);
        BGpopUpDiv.appendChild(contentDiv);
        popUpDiv = $get('itemDetailPopUpDiv');
        BGpopUpDiv = $get('itemDetailBackgroundDiv');
        contentDiv = $get('itemContentDiv');
        popUpDiv.style.position = 'absolute';
        popUpDiv.style.zIndex = '1000';
        BGpopUpDiv.style.position = 'static';
        if(isIE){
            BGpopUpDiv.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="http://images.dhmiservices.com/dhmcore/IDX/MapView/bubble2.png", sizingMethod="image")';
        }else{
            BGpopUpDiv.style.background = 'top left url("http://images.dhmiservices.com/dhmcore/IDX/MapView/bubble2.png") no-repeat';
        }
        contentDiv.style.left = '30px';
        popUpDiv.style.width= '267px';
        popUpDiv.style.height = '121px';
        BGpopUpDiv.style.width= '267px';
        BGpopUpDiv.style.height = '121px';
        contentDiv.style.width = '220px';
        contentDiv.style.height = '65px';
        contentDiv.style.position = 'relative';
        contentDiv.style.top = '15px';
        
        //added for hiding pop up only when mouse out of popup or row.
        popUpDiv.onmouseout = function(){HideItemDetails();};
        contentDiv.onmouseover = function(){_hide=false;};
        BGpopUpDiv.onmouseover = function(){_hide=false;};
        popUpDiv.onmouseover = function(){_hide=false;};   
    }
    
    popUpDiv.style.display = 'block';
    SetXYCoordinate(id,popUpDiv);
    FillItemDetails(contentDiv,integerIndex);
}
function HideItemDetails()
{
    _hide=true;
    window.setTimeout('HandleHide()',1750);
}
function HandleHide()
{
    if(_hide)
        if($get('itemDetailPopUpDiv'))
            $get('itemDetailPopUpDiv').style.display = 'none';
}
function FillItemDetails(objPopUpDiv,integerIndex)
{
    if(!objPopUpDiv)
        return false;
    /*INDEXES
    0 = address
    1 = Price
    2 = Image
    3 = City
    4 = State
    5 = Zip
    6 = Source
    7 = MLSID
    */
    if(ItemDetails[integerIndex])
    {
    var theinnerHtml = '<span style="float:left; font-weight: bold; color: #A31818;">$' + ItemDetails[integerIndex][1] + '</span><span style="float:right;color:black;font-weight: bold;">'+ItemDetails[integerIndex][0] + '</span><br clear="left">';
    theinnerHtml +='<a id="idlink_'+ ItemDetails[integerIndex][6]+'_' + ItemDetails[integerIndex][7]+'" '+(showGuestbook==true?'onclick="if(AttachGuestBookData){AttachGuestBookData(\'/ListingDetails.aspx?homeID='+ ItemDetails[integerIndex][6]+'_' + ItemDetails[integerIndex][7]+'&rownum='+(iLoopCnt+1)+'\');}return ShowUserPopUp(\'guestbook\', this.id);"':'')+' href="/ListingDetails.aspx?homeID=' + ItemDetails[integerIndex][6]+'_' + ItemDetails[integerIndex][7]+ '&rownum=' + integerIndex + '"><img src="' + (ItemDetails[integerIndex][2] && ItemDetails[integerIndex][2].length > 0 ? ItemDetails[integerIndex][2] : 'http://images.dhmiservices.com/dhmcore/IDX/Default.gif') + '" width="85" height="60" align="left"></a>' + '<span style="text-align:left; color: black;">' + ItemDetails[integerIndex][3] + ' ' + ItemDetails[integerIndex][4] + ', ' + ItemDetails[integerIndex][5] + '</span>';
    objPopUpDiv.innerHTML.appendChild(doc.createTextNode(theinnerHtml));
    objPopUpDiv.innerHTML = theinnerHtml;
    }
    //set popup div innerHTML to contents of ItemDetails array at index of integerIndex
}
(function()
{
    var mouseEvt;
    if (typeof doc.createEvent !== 'undefined')
    {
        mouseEvt = doc.createEvent('MouseEvents');
    }
    if (mouseEvt && mouseEvt.__proto__ && mouseEvt.__proto__.__defineGetter__)
    {
        mouseEvt.__proto__.__defineGetter__('pageX', function()
        {
            return this.clientX + window.pageXOffset;
        });
        mouseEvt.__proto__.__defineGetter__('pageY', function()
        {
            return this.clientY + window.pageYOffset;
        });
    }
})();
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var iLoopCnt=0; iLoopCnt<arrElements.length; iLoopCnt++){
		oElement = arrElements[iLoopCnt];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}
function check4dupes(arr,value) {
    var iLoopCnt;
    var loopCnt = arr.length;
    for (var iLoopCnt = 0;iLoopCnt < loopCnt; iLoopCnt++) {
        if(arr[iLoopCnt] == value){
            return true;
        }
    }
    return false;
}
function AddToDirections(obj)
{
    var listing_index = obj.id.replace("directionsGroup_","");
    var arr = new Array();
    var arr = _directionsList.split(",");
    if(check4dupes(arr,listing_index) == false)
        _directionsList += listing_index + ",";
    else
        alert('You have already added this location to your directions.');
    
    GetDirectionsPopup();
    
}
function RemoveFromDirections(obj)
{
    var listing_index = obj.id.replace("RemoveListing_","");
    var splitResult = _directionsList.split(",");
    _directionsList = "";
    if(splitResult.length > 0){  
       for (var iLoopCnt = 0; iLoopCnt < (splitResult.length - 1); iLoopCnt++){
            if(splitResult[iLoopCnt] != listing_index)
                _directionsList += splitResult[iLoopCnt] + ",";    
            
       }
    } 
    GetDirectionsPopup();
}
function GetDirectionsPopup(){
    var popUpDiv = $get('Map_PopupDiv');
    
    if(!_directionsList.length > 0){
        ShowDropDowns();
        //dd.elements.Map_PopupDiv.hide(true);
        if(popUpDiv)
            popUpDiv.style.display = 'none';
        return;
    }
    if(popUpDiv){
        HideDropDowns();
        //dd.elements.Map_PopupDiv.show();
        var width;
        width = screen.width;
        var left = ((width-586)/2)+'px';
        var top = '200px'; 
        popUpDiv.style.left = left;
        popUpDiv.style.top = top;    
        popUpDiv.style.display = 'block';
    }
  
    var styles = new Array();
	styles[0] = 'mapRow1';
	styles[1] = 'mapRow2';
    if(_directionsList.length > 0){  
        
        if(isIE){
            _getDirectionsGrid = '<div style="margin-left:85px;height:44px;"><img src="http://images.dhmiservices.com/dhmcore/IDX/MapView/map_map_directions_btn.gif" id="ViewDirections" onClick="if($get(\'startAddress\').value.length > 0){GetDirections();}else{alert(\'Please enter Starting Address\');return false;}" alt="Click to see these locations plotted on the map!" style="position:relative;z-index:10;cursor:hand;" />&nbsp;&nbsp;&nbsp;&nbsp;';
            _getDirectionsGrid += '<img src="http://images.dhmiservices.com/dhmcore/IDX/MapView/map_print_directions_btn.gif" id="btnPrintDirections" onClick="if($get(\'startAddress\').value.length > 0){PrintMapDirections();}else{alert(\'Please enter Starting Address\');}return false;" alt="Click to Print these directions!" style="position:relative;z-index:10;cursor:hand;" /></div>';
            _getDirectionsGrid += '<table width="305" border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse;height:auto;margin:0px auto 0 10px"><tbody>';
        }else{
            _getDirectionsGrid = '<div style="margin-left:70px;height:44px;"><img src="http://images.dhmiservices.com/dhmcore/IDX/MapView/map_map_directions_btn.gif" id="ViewDirections" onClick="if($get(\'startAddress\').value.length > 0){GetDirections();}else{alert(\'Please enter Starting Address\');return false;}" alt="Click to see these locations plotted on the map!" style="position:relative;z-index:10;cursor:hand;" />&nbsp;&nbsp;&nbsp;&nbsp;';
            _getDirectionsGrid += '<img src="http://images.dhmiservices.com/dhmcore/IDX/MapView/map_print_directions_btn.gif" id="btnPrintDirections" onClick="if($get(\'startAddress\').value.length > 0){PrintMapDirections();}else{alert(\'Please enter Starting Address\');}return false;" alt="Click to Print these directions!" style="position:relative;z-index:10;cursor:hand;" /></div>';
            _getDirectionsGrid += '<table width="305" border="0" cellpadding="0" cellspacing="0" style="border-collapse:collapse;height:auto;margin-top:10;"><tbody>';
        }
        //alert(browser);
        var splitResult = _directionsList.split(",");
        if((splitResult.length - 1) > 0){  
            for (var iLoopCnt = 0; iLoopCnt < (splitResult.length - 1); iLoopCnt++){
                if(splitResult[iLoopCnt] != ""){         
                    if(!isIE){
                        _getDirectionsGrid += '<tr><td valign="top"><table width="300" border="0" style="border:1px solid #b5b5b5;margin-top:3px;border-collapse:collapse;"><tr id="houseRow' + iLoopCnt + '" class="' + styles[iLoopCnt % 2] + '">';
                    }else{
                        _getDirectionsGrid += '<tr><td valign="top"><table width="300" border="0" style="border:1px solid #b5b5b5;margin-top:2px;border-collapse:collapse;" class="' + styles[iLoopCnt % 2] + '"><tr id="houseRow' + iLoopCnt + '" style="margin-top:0px;">';
                    }
                    if(isIE)
                        _getDirectionsGrid += '<td valign="top" style="width:55px;cursor:pointer;height:40px;font-size:9pz;font-family:Tahoma,sans-serif;position:relative;text-align:left;">';
                    else
                        _getDirectionsGrid += '<td valign="top" style="width:55px;cursor:pointer;height:45px;font-size:9pz;font-family:Tahoma,sans-serif;text-align:left;">';           
                    if(_listings.listings[splitResult[iLoopCnt]].Core.PrimaryPhoto.length > 0)
                        _getDirectionsGrid += '<img src="'+_listings.listings[splitResult[iLoopCnt]].Core.PrimaryPhoto+'" width="50" style="margin-left: 5px;margin-right: 5px;" align="left"></td>';
                    else
                        _getDirectionsGrid += '<img src="http://images.dhmiservices.com/dhmcore/IDX/no_pic_95x63.gif" width="50" style="margin-left: 1px;margin-top: 2px;margin-right: 5px;" align="left"></td>';
                    _getDirectionsGrid += '<td valign="top">';
                    var citystate = "";
                    var state = "";
		            if(_listings.listings[splitResult[iLoopCnt]].Address.State.length > 0)
		                state = stateToAbb(_listings.listings[splitResult[iLoopCnt]].Address.State.toLowerCase());
		            else
		                state = _listings.listings[splitResult[iLoopCnt]].Address.State;
                    if(_listings.listings[splitResult[iLoopCnt]].Address.City.length >0 && _listings.listings[splitResult[iLoopCnt]].Address.State.length > 0)
                        citystate = _listings.listings[splitResult[iLoopCnt]].Address.City+', '+state;
                    else if(_listings.listings[splitResult[iLoopCnt]].Address.City.length > 0 && _listings.listings[splitResult[iLoopCnt]].Address.State.length == 0)
                        citystate = _listings.listings[splitResult[iLoopCnt]].Address.City;
                    else if(_listings.listings[splitResult[iLoopCnt]].Address.City.length == 0 && _listings.listings[splitResult[iLoopCnt]].Address.State.length > 0)
                        citystate = _listings.listings[splitResult[iLoopCnt]].Address.State;
                    _getDirectionsGrid += '<span style="color: #a54b4d; font-weight: bold;">'+addCommas(_listings.listings[splitResult[iLoopCnt]].Core.PriceList)+'</span><br  />';
                    if(_listings.listings[splitResult[iLoopCnt]].Core.Beds>0 && _listings.listings[splitResult[iLoopCnt]].Core.Baths>0){
		                _getDirectionsGrid += '<span class="smBoldDescTxt detailText">'+_listings.listings[splitResult[iLoopCnt]].Core.Beds+ " Beds</span>";
		                _getDirectionsGrid += '<span class="smBoldDescTxt detailText">/ '+_listings.listings[splitResult[iLoopCnt]].Core.Baths+ ' Baths</span>';
		            }
                    //_getDirectionsGrid += '<span style="color: #5b5b5b; font-size: 9px; font-weight: bold;">Bed:'+_listings.listings[splitResult[iLoopCnt]].Core.Beds+' | Bath:' + _listings.listings[splitResult[iLoopCnt]].Core.Baths +'</span>';
                    if(_listings.listings[splitResult[iLoopCnt]].Core.SquareFeet.length > 0){
                        _getDirectionsGrid += '<div style="color: #5b5b5b; font-size: 9px; font-weight: bold;width:95px">SqFt: '+_listings.listings[splitResult[iLoopCnt]].Core.SquareFeet +'</div>';
                    }
                    _getDirectionsGrid += '<div style="color: #5b5b5b; font-size: 9px; font-weight: bold;width:95px">' + citystate + '</div>';
                    _getDirectionsGrid += '<div style="color: #5b5b5b; font-size: 9px; font-weight: bold;width:95px">' + _listings.listings[splitResult[iLoopCnt]].Extended.DetailDisclosure + '</div></td></td>';
                    _getDirectionsGrid += '<td valign="top"><a id="RemoveListing_'+splitResult[iLoopCnt]+'" style="font-size:9px;position:relative;z-index:600;" href="javascript:void(\'\');" onclick="RemoveFromDirections(this);return false;">Remove</a></td></tr></table></td>';
                    _getDirectionsGrid += '</tr>';
                }
            }
        }
        _getDirectionsGrid += '</tbody></table>';
    }
    
    if($get('btnClosePopup') && !isIE)
    {
       $get('btnClosePopup').style.top = "-50px";
       $get('btnClosePopup').style.left = "277px";
    }
    if($get('getDirectionsGrid') && !isIE)
    {
       $get('getDirectionsGrid').style.marginTop = "0px";
    }
    if($get('getDirectionsGrid'))
    {
        $get('getDirectionsGrid').innerHTML = _getDirectionsGrid;
    }
    
}

function PrintMapDirections()
{
    _isPrint = true;
    GetDirections();
}
function SendToPrintPage(directions){
    var printWin = window.open("","PrintDirections","width=500, height=400, scrollbars=yes");
	printWin.document.open();	
    printWin.document.write('<html><head><title>Print Directions</title>');
    printWin.document.write('<style type="text/css">body{ font-family:Tahoma, sans-serif; color:black;font-size:12px;margin:0px;padding:0px; background-color:#f0f0f0; } input.button{font-size:11px;font-weight:bold;border:1px solid #b6b4b5;background-color:#ccc;}</style>');
    printWin.document.write('</head><body><div style="width:100%;" align="right"><input type="button" class="button" value="Print Directions" onclick="window.print();" />&nbsp;<input type="button" value="Close Window" class="button" onclick="window.close();" /></div>');
    printWin.document.write('<div style="margin-left:15px;">' + directions + '</p>');
    printWin.document.write('</body></html>');
	printWin.document.close();
	//printWin.print();
    HideMapPopUp();
}
function HideMapPopUp()
{
    var popUpDiv = $get('Map_PopupDiv');
    if(popUpDiv){
        popUpDiv.style.display = 'none';
        ShowDropDowns();
    }
}
function clearChildren(obj)
{
  self.onerror = "Remove Children Failed.";

  try {
    if(obj.hasChildNodes() && obj.childNodes) {
      while(obj.firstChild) {
        obj.removeChild(obj.firstChild);
      }
    }
  }
  catch(e) {
    //  do nothing, or uncomment the error message
    //alert(e.message);
  }
}
function trim(sString) {
    while (sString.substring(0, 1) == ' ') {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length - 1, sString.length) == ' ') {
        sString = sString.substring(0, sString.length - 1);
    }
    return sString;
}


