﻿
// global variables used all over in file
var OffficeMapping = "0"; // bit flag to get results for listings or Offices
var OfficeDetails = null;
var shape = null;
var PriceFrom = "0";
var PriceTo = "0";
var Bedrooms = "0";
var Bathrooms = "0";
var SquareFeet = "0";
var Timeonmarket = "0";
var YearBuilt = "0";
var MinAcreage = "0";
var MaxAcreage = "0";
var OpenHouses = "0";
var Stories = "0";
var Garages = "0";
var isDebug = true;
var OpenHouseOnly = true;
var dt1 = new Date();
var lastTime = dt1.getTime();
var SingleFamily = false;
var Condo = false;
var MultiFamily = false;
var ManuHome = false;
var Farm = false;
var LotsLand = false;
var Gas = false;
var Electric = false;
var Water = false;
var Sewer = false;
var FeatureView = false; var divalertleft = null;
var FeatureFront = false;
var FeatureBoat = false; var OpenAgentList = ""; var legendleft = null;
var SeperateDwelling = false;
var BonusRoom = false;
var MasterOnMain = false;
var legendtop = null;
var quote = '"';
//var LiveURL = "'/CB.Web.UI.ClientApplication";//+ window.document.domain; //thttp://localhost:2739/CB.Web.UI.ClientApplication"; // set it live url  TO DO
var tempShapeID = "";
var LinkButonId = "";
var SaveSearchbtnId = "";
var FavListings = new Array();
var FavoriteListings = "";
var hearticon = "";
var listing = ""; // main listing results
var point = "";
var listingImageUrl = "";
var MLSListingID = "";
var ListingID = "";
var UniversalDate = null;
var Favicon = "0";
var QryListing = "";
var counts = 0;
var pos = null;
var lpos = null;
var ListingDate = null;
var ListingAddTime = 0;
var dt1 = null;
var dt2 = null;
var counter = 0;
//Set 1 day in milliseconds
var one_day = 1000 * 60 * 60 * 24;
// get days between current and listing is added
var NewPropertyDays = null;
var mapleft = null; // moves the div to right side of MAp
var maptop = null;
// get address string  
var Address = "";
var QryListing = "";
var QryFavorite = "";
var OpenFavWin = "";
var gridContext = null;
var mapContext = null;
var resultCount = 0;
var ControlType = { CheckBox: 0, DropDownList: 1 };
var ListingType = { Default: 0, NewListing: 1, OpenHouse: 2, Favorite: 3, SoldListing: 4 };

//var PropertyImageUrl = "http://photos.realestateadmin.com/";
//var PropertyImageUrl = "http://bainmedia.zaifworks.com/";
//var OfficeBaseImageUrl = "http://bainmedia.zaifworks.com/";




var map = null;
var z = null;
var Latitude = null;                    //Map Center Latitude from Querystring
var Longitude = null;                  //Map Center Longitude from Querystring
var hiddnefieldID = "";
var hiddenFavListingID = "";
var MapLatLongs = null;
var LatLongArray = null;
var tempLatitude = null;
var tempLongitude = null;
var qs = null;
var mapzoomlevel = null;
var criteriaContext = null;



function LoadMap() {
    showmapcon();
    ReadControlValues(this);
    GetListings();
}

//Load map control and wireup all necessary events to controls
function showmapcon() {
    //skip if map already initalized
    if (map != null)
        return;
    //Get Lat/Long for Map Center if passed from querystring
    
    tempLatitude = null;
    tempLongitude = null;

    var IOHLL = GetCookie("IOHLL");
    if (IOHLL != null) {
        IOHLL = IOHLL.replaceAll(",", ";");
        document.getElementById(hiddnefieldID).value = IOHLL;
        MapLatLongs = document.getElementById(hiddnefieldID).value
        LatLongArray = MapLatLongs.split(";");
    }


    if (LatLongArray != null && LatLongArray[4] != "" && LatLongArray[5] != "") //check if center lat long given
    {
        Latitude = LatLongArray[4];
        Longitude = LatLongArray[5];
        mapzoomlevel = LatLongArray[6];

        $("#hfLatitude").val(Latitude);
        $("#hfLongitude").val(Latitude);

    }
    else {
        // No Query string,
        // Set to defaults
        Latitude = "47.63115648664201";
        Longitude = "-122.19509124755862";
        mapzoomlevel = "10";

    }


    map = new VEMap('veMap');
    map.LoadMap(new VELatLong(Latitude, Longitude), mapzoomlevel, 'r', false);
    var search = document.getElementById('divpopup');


    map.AttachEvent("onendzoom", GetListings);
    map.AttachEvent("onendpan", GetListings);
    //map.AttachEvent("onstartzoom",GetListings);


    // Attacht Evenet Lsitner from Here
    // catch and call listners here

    if (criteriaContext == null)
        criteriaContext = $("#InteractiveMapSearFormArea");

    // Dropdowns 
    $(".ddlSelectPriceFrom", criteriaContext).change(function() { PriceFrom = $(this).val(); GetListings(this); });
    $(".ddlSelectPriceTo", criteriaContext).change(function() { PriceTo = $(this).val(); GetListings(this); });
    $(".ddlBeds", criteriaContext).change(function() { Bedrooms = $(this).val(); GetListings(this); });
    $(".ddlBaths", criteriaContext).change(function() { Bathrooms = $(this).val(); GetListings(this); });
    $(".ddlSquareFeet", criteriaContext).change(function() { SquareFeet = $(this).val(); GetListings(this); });
    $(".ddlTimeOnMarket", criteriaContext).change(function() { Timeonmarket = $(this).val(); GetListings(this); });
    $(".ddlyearbuild", criteriaContext).change(function() { YearBuilt = $(this).val(); GetListings(this); });
    $(".ddlMinAcreage", criteriaContext).change(function() { MinAcreage = $(this).val(); GetListings(this); });
    $(".ddlMaxAcreage", criteriaContext).change(function() { MaxAcreage = $(this).val(); GetListings(this); });
    $(".ddlStories", criteriaContext).change(function() { Stories = $(this).val(); GetListings(this); });
    $(".ddlGarage", criteriaContext).change(function() { Garages = $(this).val(); GetListings(this); });
    $(".ddlOpenHouses", criteriaContext).change(function() { OpenHouses = $(this).val(); GetListings(this); });
    $(".ddlPropertiesPerPage").change(PageListingTable);


    $(".chkNewOnMarket :checkbox").click(function() { ValidateCheckBoxes(this); if (!$(this).is(":checked")) { GetListings(this); } });
    
    //set lotland checkboxed to disabled
    $(".chkGas  :checkbox ", criteriaContext).attr('disabled', true);
    $(".chkElectric :checkbox", criteriaContext).attr('disabled', true);
    $(".chkWater :checkbox", criteriaContext).attr('disabled', true);
    $(".chkSewer :checkbox", criteriaContext).attr('disabled', true);


    // CHECK BOXES  
    // (Property Types)
    $(".chkSingleFamily :checkbox", criteriaContext).click(function() { SingleFamily = $(this).is(":checked"); ValidateCheckBoxes(this); GetListings(this); })
    $(".chkCondo :checkbox", criteriaContext).click(function() { Condo = $(this).is(":checked"); ValidateCheckBoxes(this); GetListings(this); });
    $(".chkMultiFamily :checkbox", criteriaContext).click(function() { MultiFamily = $(this).is(":checked"); ValidateCheckBoxes(this); GetListings(this); });
    $(".chkManufacturedHome :checkbox", criteriaContext).click(function() { ManuHome = $(this).is(":checked"); ValidateCheckBoxes(this); GetListings(this); });
    $(".chkFarm :checkbox", criteriaContext).click(function() { Farm = $(this).is(":checked"); ValidateCheckBoxes(this); GetListings(this); });

    // Lots and Land
    $(".chknLotsLand :checkbox", criteriaContext).click(function() { LotsLand = $(this).is(":checked"); ValidateCheckBoxes(this); GetListings(this); });
    $(".chkGas :checkbox", criteriaContext).click(function() { Gas = $(this).is(":checked"); GetListings(this); });
    $(".chkElectric :checkbox", criteriaContext).click(function() { Electric = $(this).is(":checked"); GetListings(this); });
    $(".chkWater :checkbox", criteriaContext).click(function() { Water = $(this).is(":checked"); GetListings(this); });
    $(".chkSewer :checkbox", criteriaContext).click(function() { Sewer = $(this).is(":checked"); GetListings(this); });

    // featuers
    $(".chkView :checkbox", criteriaContext).click(function() { FeatureView = $(this).is(":checked"); GetListings(this); });
    $(".chkWaterFront :checkbox", criteriaContext).click(function() { FeatureFront = $(this).is(":checked"); GetListings(this); });
    $(".CheckbchkHouseBoatox :checkbox", criteriaContext).click(function() { FeatureBoat = $(this).is(":checked"); GetListings(this); });

    $(".chkSeperateDwelling :checkbox", criteriaContext).click(function() { SeperateDwelling = $(this).is(":checked"); GetListings(this); });
    $(".chkBonusRoom :checkbox", criteriaContext).click(function() { BonusRoom = $(this).is(":checked"); GetListings(this); });
    $(".chkMasterOnMain :checkbox", criteriaContext).click(function() { MasterOnMain = $(this).is(":checked"); GetListings(this); });

    // Chk ViewLegend
    //$(".chkViewLegends :checkbox").click(GetListings);
    //$(".lnkViewLegends").click(function() { ShowHideLegend(true,450,200); return false; });
    //$(".divLegendClose").click(function() { ShowHideLegend(false,450,200); });



    // also check if View Office listing is called
    // attach listner here
    $(".chkShowOffices :checkbox").click(GetOffices);

    //Swiitching Classes so the map has more room to operate in.
    //There has to be a better way to do this (remove these remarks).
    $('#Canvas').width("998px");
    $('#Header').width("998px");



}

//---------------------------------------------------------------------------
// Map manuplation methods
//---------------------------------------------------------------------------



/**
* function to get id of hiddenfield
* that will contain Four Map Coordinates
* to send to handler(HidMapCor)
* @param {String} id - Hidden Map Coordinates.
*/
function GetId(id)
{ hiddnefieldID = id; }


/**
* function to get Id of ListView Link Button (lnkbtnListView) id
* @param {String} id - ListView Button Id.
*/
function GetListViewId(id)
{ LinkButonId = id; }

/**
* function to get ID of FavListing Hidden field (HidFavoriteListignIds)
* @param {String} id - Member Favorite Listing Ids.
*/
function GetHiddenFavListId(id)
{ hiddenFavListingID = id; }

/**
* function to get Id of Save Search Button (BtnSaveSearch) id
* @param {String} id - SaveSearch Button Id.
*/
function GetSaveSearchbtnId(id)
{ SaveSearchbtnId = id; }

/**
* function to Read all checkboxes and apply rules on them
* @param {object} objElement-DOM Element object
*/
function ValidateCheckBoxes(sender) {
    // get all values for parameters  to send it to search handler one by one 
    if (criteriaContext == null)
        criteriaContext = $("#InteractiveMapSearFormArea");


    //check if the sender is particular element then do
    //sender.ParentNode is used to get parent element on which class is applied
    if (sender != undefined)
        if (sender.parentNode != null)
        if (HasClassName(sender.parentNode, "chkSingleFamily") || HasClassName(sender.parentNode, "chkCondo")
            || HasClassName(sender.parentNode, "chkMultiFamily") || HasClassName(sender.parentNode, "chkManufacturedHome")
            || HasClassName(sender.parentNode, "chkFarm")) {

        Condo = GetCheckboxValue(".chkCondo", ControlType.CheckBox);
        MultiFamily = GetCheckboxValue(".chkMultiFamily", ControlType.CheckBox);
        ManuHome = GetCheckboxValue(".chkManufacturedHome", ControlType.CheckBox);
        Farm = GetCheckboxValue(".chkFarm", ControlType.CheckBox);
        if (((Condo == false) && (MultiFamily == false)) && ((ManuHome == false) && (Farm == false))) {
            // enable singel family selection              
            $(".chkSingleFamily :checkbox", criteriaContext).attr('checked', true);

        }


        $(".chknLotsLand :checkbox", criteriaContext).attr('checked', false);

        $(".chkGas :checkbox", criteriaContext).attr('disabled', true);
        $(".chkElectric :checkbox", criteriaContext).attr('disabled', true);
        $(".chkWater :checkbox", criteriaContext).attr('disabled', true);
        $(".chkSewer :checkbox", criteriaContext).attr('disabled', true);

        $(".chkGas :checkbox", criteriaContext).attr('checked', false);
        $(".chkElectric :checkbox", criteriaContext).attr('checked', false);
        $(".chkWater :checkbox", criteriaContext).attr('checked', false);
        $(".chkSewer :checkbox", criteriaContext).attr('checked', false);

        LotsLand = false;
        Gas = false;
        Electric = false;
        Water = false;
        Sewer = false;
    }
    else if (HasClassName(sender.parentNode, "chknLotsLand")) {
        var cbValue = GetCheckboxValue(".chknLotsLand", ControlType.CheckBox);
        if (cbValue) {
            //enable all sub checkboxes
            $(".chkGas :checkbox", criteriaContext).attr('disabled', false);
            $(".chkElectric :checkbox", criteriaContext).attr('disabled', false);
            $(".chkWater :checkbox", criteriaContext).attr('disabled', false);
            $(".chkSewer :checkbox", criteriaContext).attr('disabled', false);

            //uncheck all property types
            $(".chkSingleFamily :checkbox", criteriaContext).attr('checked', false);
            $(".chkCondo :checkbox", criteriaContext).attr('checked', false);
            $(".chkMultiFamily :checkbox", criteriaContext).attr('checked', false);
            $(".chkManufacturedHome :checkbox", criteriaContext).attr('checked', false);
            $(".chkFarm :checkbox", criteriaContext).attr('checked', false);

            SingleFamily = false;
            Condo = false;
            MultiFamily = false;
            ManuHome = false;
            Farm = false;

        }
        else {
            // make them disable
            // enable sub check boxes
            $(".chkGas :checkbox", criteriaContext).attr('disabled', true);
            $(".chkElectric :checkbox", criteriaContext).attr('disabled', true);
            $(".chkWater :checkbox", criteriaContext).attr('disabled', true);
            $(".chkSewer :checkbox", criteriaContext).attr('disabled', true);
            Gas = false;
            Electric = false;
            Water = false;
            Sewer = false;

            $(".chkSingleFamily :checkbox", criteriaContext).attr('checked', true);
            SingleFamily = true;
        }
    }
    else if (HasClassName(sender.parentNode, "chkNewOnMarket")) {

        var checked = $(sender).is(":checked");
        var ddlTimeOnMarket = $(".ddlTimeOnMarket");
        ddlTimeOnMarket.attr('disabled', !checked);
        if (!checked) {
            ddlTimeOnMarket.attr('value', '0')
            Timeonmarket = "0";
        }


    }
           


}

/**
* function to Read all search criteria building elements 
* @param {object} objElement-DOM Element object
* @param {string} strClass- name of the class to search on Element
* @return (bool) Returns bool value which shows element has the class applied or not
*/
function ReadControlValues(sender) {
    //WriteDebug("Getting values from controls");
    if (criteriaContext == null)
        criteriaContext = $("#InteractiveMapSearFormArea");

    // all dropdown boxes    
    PriceFrom = $(".ddlSelectPriceFrom", criteriaContext).val();
    PriceTo = $(".ddlSelectPriceTo", criteriaContext).val();
    Bedrooms = $(".ddlBeds", criteriaContext).val();
    Bathrooms = $(".ddlBaths", criteriaContext).val();
    SquareFeet = $(".ddlSquareFeet", criteriaContext).val();
    Timeonmarket = $(".ddlTimeOnMarket", criteriaContext).val();
    YearBuilt = $(".ddlyearbuild", criteriaContext).val();
    MinAcreage = $(".ddlMinAcreage", criteriaContext).val();
    MaxAcreage = $(".ddlMaxAcreage", criteriaContext).val();
    OpenHouses = $(".ddlOpenHouses", criteriaContext).val();
    Stories = $(".ddlStories", criteriaContext).val();
    Garages = $(".ddlGarage", criteriaContext).val();
    // dropdown ends

    // get values of all check boxes 

    // PROPERTY TYPES
    SingleFamily = GetCheckboxValue(".chkSingleFamily", ControlType.CheckBox);
    Condo = GetCheckboxValue(".chkCondo", ControlType.CheckBox);
    MultiFamily = GetCheckboxValue(".chkMultiFamily", ControlType.CheckBox);
    ManuHome = GetCheckboxValue(".chkManufacturedHome", ControlType.CheckBox);
    Farm = GetCheckboxValue(".chkFarm", ControlType.CheckBox);


    // Land and Lots                
    LotsLand = GetCheckboxValue(".chknLotsLand", ControlType.CheckBox);
    Gas = GetCheckboxValue(".chkGas", ControlType.CheckBox);
    Electric = GetCheckboxValue(".chkElectric", ControlType.CheckBox);
    Water = GetCheckboxValue(".chkWater", ControlType.CheckBox);
    Sewer = GetCheckboxValue(".chkSewer", ControlType.CheckBox);

    // Feature
    FeatureView = GetCheckboxValue(".chkView", ControlType.CheckBox);
    FeatureFront = GetCheckboxValue(".chkWaterFront", ControlType.CheckBox);
    FeatureBoat = GetCheckboxValue(".CheckbchkHouseBoatox", ControlType.CheckBox);

    SeperateDwelling = GetCheckboxValue(".chkSeperateDwelling", ControlType.CheckBox);
    BonusRoom = GetCheckboxValue(".chkBonusRoom", ControlType.CheckBox);
    MasterOnMain = GetCheckboxValue(".chkMasterOnMain", ControlType.CheckBox);
    // checkboxes end here
    //WriteDebug("Completed Getting values from Controls");
}


/**
* Basic function to get listings from search handler
* Called whenever any change occur in search criteria
* @param {object} e- usually contain sender
*/
function GetListings(e) {
    //WriteDebug("Starting to get Listing");
    
    //map.Clear();  Commented out on 11-10-09 due to bug in VE Map API and replaced with following three lines
    
    map.DeleteAllShapes();
    map.DeleteRoute();
    map.DeleteAllShapeLayers();
    
    //WriteDebug("Deleted Shapes");
    //get all search criteria building elements values

    // MAp code goes here
    // get Map Co-ordinates andfour corners
    //WriteDebug("Started Getting map coordinates");
    var view = map.GetMapView();

    //check if map scene is not available then get bounding rectange through birdview
    if (view.BottomRightLatLong.Latitude == null || view.BottomRightLatLong.Longitude == null) {
        if (map.IsBirdseyeAvailable()) {
            view = GetBoundingBoxForBirdEye('veMap');
        }
        else {
            alert("Sorry, birdseye is not available");
            return;
        }

    }

    var topleft = view.TopLeftLatLong;
    var bottomright = view.BottomRightLatLong;

    //get the points of the box. I am not sure how accurate this is.
    var EastLon = topleft.Longitude;
    var WestLon = bottomright.Longitude;
    var NorthLat = topleft.Latitude;
    var SouthLat = bottomright.Latitude;
    //alert(NorthLat + " " + SouthLat + " : " + WestLon  + " : " + EastLon);

    // Save Map Co-ordinates to hidden field.
    // We will save Four corners (North,South,West,East) of Map, 
    // Starting Latitude and Longitutde and Map current Zoom Level to hidden filed respectively,
    // We will save all these with column ';' seperated vlaue.


    // So (first 4) fields represent NorthLat +  SouthLat +  WestLon + EastLon,
    //(and 5 ,6 fields represent Map Co-ordinates Latitude +  Longitude and finally 
    // last one represent Mpa current Zoom level

    // get currrent zoom level of map
    var mapzoomlevel = map.GetZoomLevel();
    var mapcenter = map.GetCenter();


    // get hidden filed and set its value to null and then save record
    var hidfield = $("#" + hiddnefieldID);
    hidfield.val(null);
    // now save
    hidfield.val(roundNumber(NorthLat, 4) + ";" + roundNumber(SouthLat, 4) + ";" + roundNumber(WestLon, 4) + ";" + roundNumber(EastLon, 4) + ";" + mapcenter.Latitude + ";" + mapcenter.Longitude + ";" + mapzoomlevel);
    var hidval = roundNumber(NorthLat, 4) + ";" + roundNumber(SouthLat, 4) + ";" + roundNumber(WestLon, 4) + ";" + roundNumber(EastLon, 4) + ";" + mapcenter.Latitude + ";" + mapcenter.Longitude + ";" + mapzoomlevel;
    hidval = hidval.replaceAll(";", ",");
    SetCookie("IOHLL", hidval, (60 * 60 * 1000));

    // As this the case of Listings so set this 
    // flag set it to null

    OffficeMapping = "0";
    //This calls the handler page to return the listings.
    //WriteDebug("Started Calling MapSearch Handler");



    //ShowSearching Div Alert
    var mapleft = map.GetLeft(); // moves the div to right side of MAp
    var maptop = map.GetTop();

    mapleft += 200;
    maptop += 150;

    var QuickOpenHouseContainer = $('#QuickOpenHousesContainer');
    if (mapcenter.Longitude > -122.98645019531251 && mapcenter.Longitude < -120.02464730398996 && mapcenter.Latitude < 48.90094957553023 && mapcenter.Latitude > 46.30104415159213) {
        QuickOpenHouseContainer.show();
    }
    else {
        QuickOpenHouseContainer.hide();
    }
    


    var $divSearchAlert = $('#divSearAlert');
    $divSearchAlert.show();

    GetControl(map, "divSearAlert", mapleft, maptop);



    $.ajax({
        type: "POST",
        url: "MapSearchHandler.aspx",
        data: { NorthLat: NorthLat, SouthLat: SouthLat, EastLon: EastLon, WestLon: WestLon, PriceFrom: PriceFrom,
            PriceTo: PriceTo, Bedrooms: Bedrooms, Bathrooms: Bathrooms, SquareFeet: SquareFeet,
            Timeonmarket: Timeonmarket, YearBuilt: YearBuilt, MinAcreage: MinAcreage, MaxAcreage: MaxAcreage, Stories: Stories, Garages: Garages,
            SingleFamily: SingleFamily, Condo: Condo, MultiFamily: MultiFamily, ManuHome: ManuHome, Farm: Farm,
            Gas: Gas, Electric: Electric, Water: Water, Sewer: Sewer, FeatureView: FeatureView,SearchType:14,OpenHouses:OpenHouses,
            FeatureFront: FeatureFront, FeatureBoat: FeatureBoat, OffficeMapping: OffficeMapping, LotsLand: LotsLand,
          ZoomLevel: mapzoomlevel, MapCenterLat: mapcenter.Latitude, MapCenterLong: mapcenter.Longitude ,
          SeperateDwelling: SeperateDwelling, BonusRoom: BonusRoom, MasterOnMain: MasterOnMain, OpenHouseOnly: OpenHouseOnly
        },
        dataType: "json",
        success: ShowListings,
        error: OnError

    });


    //WriteDebug("Completed Map Search Call.");            
}

/**
* Function Called when a error is occured dusing ajax call
* @param {object} msg - error message
* @param {object} e - error message
*/
function OnError(msg, e) {
    //Hide Searching div alert
    var $divSearchAlert = $('#divSearAlert');
    $divSearchAlert.hide();
    if (e.toLowerCase().indexOf('parser') >= 0) {
        alert('Your session has expired. Please refresh the browser.');
    }
    else {
        alert(e);
    }
}


/**
* Main Function called when ajax called successfully got all the listing
* This Method first add pushpins to map then call other methods to create grid 
* @param (object) msg - is a JSON object can contain many info like record count,array of leads and anyother info message
*/
function ShowListings(msg) {

    if (msg == null) {
        return;
    }
    
    //Hide Searching div alert
    var $divSearchAlert = $('#divSearAlert');
    $divSearchAlert.hide();


    //set grid to empty
    if (gridContext == null)
        gridContext = $("InteractiveMapSearRCDetailGrid");
    var $gridDiv = $('div#ListingGridContainer');
    $gridDiv.html('');
    //set featurefrid empty
    $('#featureDivContainer').html('');
    


    //WriteDebug("Starting the show listings method");
    if (mapContext = null)
        mapContext = $("#InteractiveMapSearRC");

    mapleft = map.GetLeft(); // moves the div to right side of MAp
    maptop = map.GetTop();

    divalertleft = mapleft + 365;
    maptop += 5;

    GetControl(map, "divAlert", divalertleft, maptop);
    
    // call offices if checkbox is checked
    if ($(".chkShowOffices :checkbox").is(":checked")) {
        // also call officelistings
        // to show images
        GetOffices();
    }

    
    //check if count object is returned in response then show message only
    //The handler either returns results or count
    if (msg.ErrorInfo != null) {
        alert(msg.ErrorInfo);
        return;
    }
    else if (msg.Count != null)//check if count object is returned in response then show message only
    {

        resultCount = msg.Count;
        ShowCount();

        ShowHideAlert();
        if (msg.Count > 300) //why are we doing this? shouldn't this always be > 300?
        {

            // disable link button   for Listview 
            // TRY WITH JQUERY TO ENABLE/DISABLE LINKBUTTON BUT NO LUCK FULLY
            // AS ONE WORK AT TIME EITHER ENABLE OR DISABLE WITH JQUERY. 
            // TO DO (ANY HELP IF ONE CAN WITH JQUERY)

            // CURRENTLY WORKING ON JS
            document.getElementById(LinkButonId).onclick = function() { return false; };


            document.getElementById(SaveSearchbtnId).onclick = function() { return false; };
            // change colour
            // this works with JQUERY                
            $(".lnkbtnListView").css({ color: "gray" });




            return; // just inform and get out of script
        }

        if (msg.Count == 0)
            return;

    }
    else {
        resultCount = msg.Results.length;
        ShowHideAlert();
        // enable listview  on click and change the colour
        // set it to default
        document.getElementById(LinkButonId).onclick = "";
        document.getElementById(SaveSearchbtnId).onclick = "";

        // change the colour
        $(".lnkbtnListView", mapContext).css({ color: "blue" });

    }

    ShowCount();
    //ShowHideLegend();



    // main condition to show map
    //WriteDebug("Starting the pushpin sequence");

    var ShapeID = new Array(); // stores shapes IDs to map below
    var cc; // for counter
    var currentListingType;
    var currentListingIcon;
    var shapes = new Array(); //this will hold all shapes for bulk loading 
    if (msg.Results.length > 0) {
        for (var i = 0; i < msg.Results.length; i++) {

            //WriteDebug("Start loop" + counter);
            var listing = msg.Results[i];

            var ListingID = listing.ListingID;
            var isFav = IsFavoriteListing(listing);
            var currentListingType = GetTypeForListing(listing);
            var currentListingIcon = GetIconForType(currentListingType);

            var point = new VELatLong(listing.Latitude, listing.Longitude);
            var shape = new VEShape(VEShapeType.Pushpin, point);
            var MLSListingID = listing.MlslistingId;


            // get address string 
            var CityName = listing.CityName == null ? '' : listing.CityName.toString().trim();
            var StrtAddress = listing.StreetAdd == null ? '' : listing.StreetAdd.toString().trim();
            var State = listing.State == null ? '' : listing.State;

            var Address = StrtAddress + ", " + CityName + ", " + State;
            if (Address.length > 15)
                Address = Address.substring(0, 15) + "...";
            var QryListing = LiveURL + listing.SEOUrl + "'";

            if (!isFav)
                var QryFavorite = LiveURL + "/Popups/AddFavoriteListing.aspx?FLI=" + ListingID + '&PRC=' + listing.ListPrice + "&P=InteractiveOpenHouseSearch.aspx'";
            else
                var QryFavorite = LiveURL + "/Popups/RemoveFavoriteListing.aspx?FLI=" + ListingID + '&PRC=' + listing.ListPrice + "&P=InteractiveOpenHouseSearch.aspx'";

            var OpenFavWin = "Javascript:window.open(" + QryFavorite + ",'InteractiveSearch','location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,height=630,width=630');";

            // set photo image path
            if (MLSListingID != "unknown") {
                var listingImageUrl = getPropertyImageUrl(MLSListingID, listing.MlsId2) + '?Height=100&Width=100';
            }
            // make info ballon
            var listingDetail = new StringBuilder();
            listingDetail.append("<div >");
            listingDetail.append("<table border='0' cellpadding='0' cellspacing='0' >");
            listingDetail.append("<tbody>");
            listingDetail.append("<tr>");
            listingDetail.append("<td colspan='2'>");
            listingDetail.append("<div style='height:30px;width:25px;float:left;background-color:Transparent background-repeat:no-repeat;background-image: url(../App_Themes/Default/Images/InteractiveMap/baloon.gif)'></div>");
            listingDetail.append("<div style='float:left;width:auto;font-size:12px;color:Blue;'>");
            listingDetail.append("<div class='RowContents FontBold'>Open House</div>");
            listingDetail.append("<div class='RowContents FontBold'>" + listing.FormattedOpenHouse + "</div>");
            listingDetail.append("</div>");
            listingDetail.append("</td>");
            listingDetail.append("</tr>");
        
            listingDetail.append("<tr>");
            listingDetail.append("<td align='center' valign='middle'>");
            listingDetail.append("<a href=" + QryListing + " ><img style='vertical-align: middle;' src='" + listingImageUrl + "' ></a>&nbsp;");
            listingDetail.append("</td>");

            listingDetail.append("<td>");
            listingDetail.append("<div class='ListingInfoContainer'><b>" + listing.FormattedPrice + "</b><br><b>" + listing.Beds + "</b> Beds&nbsp;&nbsp;<b>" + listing.Baths + "</b> Baths<br><b>" + listing.FormattedLivingarea + "</b> Square feet<br>" + Address + "<br>" + CityName + "<br>MLS#: " + MLSListingID + "</div>");

            listingDetail.append("</td>");
            listingDetail.append("</tr>");
            listingDetail.append("</tbody>");
            listingDetail.append("</table>");
            listingDetail.append("</div>");

            listingDetail.append("<div class='ListingDetailLinkContainer' style='float:left'><a href=" + QryListing + " >View details</a>&nbsp;&nbsp;</div>");
            if (!listing.isSold) {
                if (!isFav)
                    listingDetail.append("<div class='ListingFavLinkContainer'><a href='#'  onclick=" + quote + OpenFavWin + quote + " >Add to favorites</a></div>");
                else
                    listingDetail.append("<div class='ListingFavLinkContainer'><a href='#'  onclick=" + quote + OpenFavWin + quote + " >Remove from favorites</a></div>");
            }
            listingDetail.append("</div>");


            //WriteDebug("End loop");

            // increment i to display number from 1 in 
            //custom icons;           
            counter = i + 1;
            shape.SetCustomIcon(SetCustomShape(currentListingIcon, listing.LPSortOrder, currentListingType));
            shape.SetDescription(listingDetail.toString());
            shapes.push(shape);



        } // for loop
        //WriteDebug("Starting Add Shapes");
        map.AddShape(shapes); //doing bulk add
        //WriteDebug("Completed Add Shapes");
        //store shapeids to array for later use(show/hide)
        for (var i = 0; i < shapes.length; i++)
        { ShapeID[msg.Results[i].LPSortOrder - 1] = shapes[i].GetID(); }

        //WriteDebug("Starting Add Shapes");
        //map.AddShape(shapes);
        //WriteDebug("Completed Add Shapes");


        msg.Results.sort(sortByLP);

        //WriteDebug("Completed Pushpin Sequence.");
        //create listing grid
        ShowListingGrid(msg, ShapeID);
        //create grid columns sortable
        MakeListingTableSortable();
        //create paging on grid
        PageListingTable();
        //WriteDebug("Map rendering complete.");
        //WriteDebug("------------------------");
    } // if count

}



/**
* basic function that generates the grid
* results in tabular form
* @param (object) msg - JSON object which contain collection of listing
* @param (array) ShapeID - shapeids of the pushpins(shapes) placed on the map
*/
function ShowListingGrid(msg, ShapeID) {
    if (gridContext == null)
        gridContext = $("InteractiveMapSearRCDetailGrid");
    var $gridDiv = $('div#ListingGridContainer');
    $gridDiv.html('');
    //WriteDebug("Started Showing the listing grid");

    var htmlForListingGrid = new Array();
    //var quote = '"' ;
    //    var listing;
    var k;
    var counts;
    var featureListingIndexs = msg.FeaturedListings;
    var htmlfeatureProperties = new Array(); 
    htmlForListingGrid.push("<table id='tableListings' class='stripeMe paginated sortable'><thead><tr><th class='sort-numeric'>Property</th><th class='sort-alpha'>Address</th><th class='sort-alpha'>City</th><th class='sort-numeric'>Price</th><th class='sort-numeric'>Beds</th><th class='sort-numeric'>Baths</th><th class='sort-alpha'>Status</th><th class='sort-numeric'>SqFt.</th><th class='sort-numeric'>Lot Size</th><th class='sort-alpha'>MLS</th></tr></thead><tbody>");
    for (var i = 0; i < msg.Results.length; i++) {


        var listing = msg.Results[i];
        // get image 
        // Favicon="0";

        var MLSListingID = listing.MlslistingId;
        var ListingID = listing.ListingID;

        
        var currentListingType = GetTypeForListing(listing);
        var currentListingIcon = GetIconForType(currentListingType);
        var listingImageUrl;

        if (MLSListingID != "unknown") {
            var listingImageUrl = getPropertyImageUrl(MLSListingID, listing.MlsId2) + '?Height=100&Width=100';
        }
        var QryListing = LiveURL +listing.SEOUrl+ "'";
        htmlForListingGrid.push("<tr>");

        //if(i <= 20) {
        //WriteDebug("Start loop " + i);  }
        // counter to number icons
        counts = i + 1;
        htmlForListingGrid.push(GetCustomIcon(currentListingIcon, listingImageUrl, counts));


        //rest same
        htmlForListingGrid.push("<td align='left' style='padding-left:8px;' ><a href=" + QryListing + " title='Click to view details about" + listing.StreetAdd + "'>" + listing.StreetAdd + "</a></td>");
        htmlForListingGrid.push("<td align='left' style='padding-left:8px;' >" + listing.CityName + "</td>");
        htmlForListingGrid.push("<td align='right' style='padding-right:8px;' >" + listing.FormattedPrice + "</td>");
        htmlForListingGrid.push("<td align='center'>" + listing.Beds + "</td>");
        htmlForListingGrid.push("<td align='center'>" + listing.Baths + "</td>");
        htmlForListingGrid.push("<td align='center' >" + GetStatusForListing(listing) + "</td>");
        htmlForListingGrid.push("<td align='center'>" + listing.FormattedLivingarea + "</td>");
        htmlForListingGrid.push("<td align='center'>" + listing.LotSize + "</td>");
        htmlForListingGrid.push("<td align='center' style='height:22px; width:38px; padding-left:2px;'><div style='height:22px; width:37px; background-repeat:no-repeat; background-image:url(../App_Themes/Default/Images/InteractiveMap/" + GetMLSImageByMLSID(listing) + ")'></div></td>");
        htmlForListingGrid.push("</tr>");
        listingImageUrl = "";
        //if (i <= 20) {
        //WriteDebug("End loop " + i);
        //}

    }
    //WriteDebug(htmlForListingGrid.length);
    htmlForListingGrid.push("</tbody></table>");


    htmlfeatureProperties.push('<table class="featureListings">');
    for (i in featureListingIndexs) {

        ind = featureListingIndexs[i];
        htmlfeatureProperties.push('<tr class="mainRow"><td>');

        var listing = msg.Results[ind];
        var MLSListingID = listing.MlslistingId;
        var ListingID = listing.ListingID;
        var isFav = IsFavoriteListing(listing);
        var currentListingType = GetTypeForListing(listing);
        var currentListingIcon = GetIconForType(currentListingType);
        var listingImageUrl;

        var QryListing = LiveURL + listing.SEOUrl+ "'";

        if (!isFav)
            var QryFavorite = LiveURL + "/Popups/AddFavoriteListing.aspx?FLI=" + ListingID + '&PRC=' + listing.ListPrice + "&P=InteractiveOpenHouseSearch.aspx'";
        else
            var QryFavorite = LiveURL + "/Popups/RemoveFavoriteListing.aspx?FLI=" + ListingID + '&PRC=' + listing.ListPrice + "&P=InteractiveOpenHouseSearch.aspx'";

        var OpenFavWin = "Javascript:window.open(" + QryFavorite + ",'InteractiveSearch','location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,height=630,width=630');";


        if (MLSListingID != "unknown") {
            var listingImageUrl = getPropertyImageUrl(MLSListingID, listing.MlsId2) + '?Height=75&Width=75';
        }

        // get address string 
        var CityName = listing.CityName == null ? '' : listing.CityName.toString().trim();
        var StrtAddress = listing.StreetAdd == null ? '' : listing.StreetAdd.toString().trim();
        var State = listing.State == null ? '' : listing.State;

        var Address = StrtAddress + ", " + CityName + ", " + State;
        if (Address.length > 12)
            Address = Address.substring(0, 12) + "...";
            
        if(CityName.length > 12)
            CityName = CityName.substring(0, 12) + "...";

        var listingDetail = new StringBuilder();
        listingDetail.append("<div style='padding:8px 0px 0px 0px' >");
        listingDetail.append("<table border='0' cellpadding='0' cellspacing='0' style='font-size:11px' >");
        listingDetail.append("<tbody>");
        listingDetail.append("<tr>");
        listingDetail.append("<td colspan='2'>");
        listingDetail.append("<div style='height:30px;width:25px;float:left;background-color:Transparent background-repeat:no-repeat;background-image: url(../App_Themes/Default/Images/InteractiveMap/baloon.gif)'></div>");
        listingDetail.append("<div style='float:left;width:160px;font-size:12px;color:Blue;'>");
        listingDetail.append("<div class='RowContents FontBold' style='padding-bottom:0px'>Open House</div>");
        listingDetail.append("<div class='RowContents FontBold' style='padding-top:0px'>" + listing.FormattedOpenHouse + "</div>");
        listingDetail.append("</div>");
        listingDetail.append("</td>");
        listingDetail.append("</tr>");
        listingDetail.append("<tr>");
        listingDetail.append("<td align='center' valign='top'>");
        listingDetail.append("<a href=" + QryListing + " ><img style='vertical-align: middle;' src='" + listingImageUrl + "' ></a>&nbsp;");
        listingDetail.append("</td>");

        listingDetail.append("<td>");
        listingDetail.append("<div class='ListingInfoContainer'><b>" + listing.FormattedPrice + "</b><br><b>" + listing.Beds + "</b> Beds&nbsp;&nbsp;<b>" + listing.Baths + "</b> Baths<br><b>" + listing.FormattedLivingarea + "</b> Square feet<br>" + Address + "<br>" + CityName + "<br>MLS#: " + MLSListingID + "</div>");

        listingDetail.append("</td>");
        listingDetail.append("</tr>");
        listingDetail.append("</tbody>");
        listingDetail.append("</table>");
        listingDetail.append("</div>");

        listingDetail.append("<div class='ListingDetailLinkContainer' style='float:left;font-size:11px'><a   href=" + QryListing + " >View details</a>&nbsp;&nbsp;</div>");
        if (!listing.isSold) {
            if (!isFav)
                listingDetail.append("<div class='ListingFavLinkContainer' style='font-size:11px'><a href='#' onclick=" + quote + OpenFavWin + quote + " >Add to favorites</a></div>");
            else
                listingDetail.append("<div class='ListingFavLinkContainer' style='font-size:11px'><a href='#' onclick=" + quote + OpenFavWin + quote + " >Remove from favorites</a></div>");
        }
        listingDetail.append("</div>");
        
        htmlfeatureProperties.push(listingDetail.toString());   
        htmlfeatureProperties.push('</td></tr>');
    }
    htmlfeatureProperties.push('</table >');
    
    $('#featureDivContainer').html(htmlfeatureProperties.join(''));


    $gridDiv.html(htmlForListingGrid.join(''));
    $(".stripeMe tr").mouseover(function() { $(this).addClass("over"); }).mouseout(function() { $(this).removeClass("over"); });
    $(".stripeMe tr:even").addClass("even");


    $('.stripeMe tr').each(function(index)//iterate through all rows in table and set their mouseover and out actions
    {
        $(this).mouseover(function() { if (tempShapeID != ShapeID[index - 1]) { HideInfoBox(); }; shape = map.GetShapeByID(ShapeID[index - 1]); map.ShowInfoBox(shape); tempShapeID = ShapeID[index - 1]; }).mouseout(function() { HideInfoBox(); });
    });

    $('.featureListings tr:[class=mainRow]').each(function(index)//iterate through all rows in table and set their mouseover and out actions
    {
        $(this).mouseover(function() { shape = map.GetShapeByID(ShapeID[featureListingIndexs[index]]); map.ShowInfoBox(shape); }).mouseout(function() { HideInfoBox(); });
    });
    //WriteDebug("Complted Showing Listinggrid");

}




/**
* function create a custom icon HTML markup to be placed on the grid as icon 
* @param (string) IconPath- icon image file path
* @param (string) listingimgurl- image path of the listing
* @param (number) counter- number to placed on the icon
*/
function GetCustomIcon(IconPath, listingimgurl, counter) {
    var Icon = new StringBuilder();
    Icon.append("<td>");
    Icon.append("<div style='height:30px;width:25px;float:left;background-color:Transparent background-repeat:no-repeat; background-image: url(../App_Themes/Default/Images/InteractiveMap/baloon.gif)'>&nbsp; </div>");
    Icon.append("<div style='font-family:Tahoma; float:left;width:25px; padding-top:5px; padding-bottom:10px; padding-left:8px; padding-right:8px;");
    Icon.append("Icon= z-index:500; overflow:visible; font-size:7.5pt; color:white; background-repeat:no-repeat; background-image:url(../App_Themes/Default/Images/InteractiveMap/");
    Icon.append(IconPath);
    Icon.append(")' onMouseOver='javascript:ShowGridImageRowPopup(");
    Icon.append(quote);
    Icon.append(listingimgurl);
    Icon.append(quote);
    Icon.append("); ' onMouseOut='javascript:HideGridImageRowPopup();'>");
    Icon.append(counter);
    Icon.append("</div>");
    Icon.append("</td>");
    return Icon;
}


/**
* function create a custom icon HTML markup of offices to be placed on the map as pushpin icon 
* @param (string) IconPath- icon image file path
*/
function SetCustomShapeOffice(IconPath) {
    var IconOff = " <span style='font-family:Tahoma;  width:25px; padding-top:5px; padding-bottom:10px; padding-left:6px; padding-right:10px; z-index:500; overflow:visible; font-size:7.5pt; color:white;'> <img alt =''  src='../App_Themes/Default/Images/InteractiveMap/" + IconPath + "' style=' padding-top:5px; padding-bottom:10px; padding-left:6px; padding-right:10px;'/></span>";
    return IconOff;
}

////////////////////////// OFFIce Coding Goes here ///////////////////////

/**
* function called by Ajax when request for offices is made
* @param (object) msg- (TODO remove it if not needed)
*/
function GetOffices(msg) {
    var view = map.GetMapView();
    var topleft = view.TopLeftLatLong.toString();
    var bottomright = view.BottomRightLatLong.toString();

    //get the points of the box. I am not sure how accurate this is.
    var EastLon = topleft.substring(topleft.indexOf(',') + 1, topleft.length);
    var WestLon = bottomright.substring(bottomright.indexOf(',') + 1, bottomright.length);
    var NorthLat = topleft.substring(0, topleft.indexOf(',') - 1);
    var SouthLat = bottomright.substring(0, bottomright.indexOf(',') - 1);




    // flagshows brign the office detail only
    OffficeMapping = "1";
    //This calls the handler page to return the Office listings.
    $.ajax({
        type: "POST",
        url: "MapSearchHandler.aspx",
        data: { NorthLat: NorthLat, SouthLat: SouthLat, EastLon: EastLon, WestLon: WestLon, OffficeMapping: OffficeMapping },
        dataType: "json",
        success: ShowOfficeListings,
        error: function(msg, e) {
            alert(e);
        }
    });


}


/**
* function used for javascript debuging
* @param (string) msg- custom msg to be shown when debug enabled
*/
function WriteDebug(msg) {
    if (isDebug) {
        var date = new Date();

        $("#divDebug", mapContext).append(date.getTime() - lastTime + " " + msg + "<br />");
        lastTime = date.getTime();
    }
}
var officeicon = new Array();


/**
* function used to show offices on the map
* @param (object) msg- JSON object contain collection of office
*/
function ShowOfficeListings(msg) {
    // show offfices here

    if (msg.Results.length > 0) {
        //hide alert baloon
        var $divAlert = $('#divAlert');
        $divAlert.hide();

        // set to null
        listingDeatil = "";

        for (var i = 0; i < msg.Results.length; i++) {
            // if checked then add shapes
            // other delete shapes if added
            if ((($($(".chkShowOffices")[0].childNodes[0])).is(":checked"))) {

                OfficeDetails = msg.Results[i];

                point = new VELatLong(OfficeDetails.Latitude, OfficeDetails.Longitude);

                shape = new VEShape(VEShapeType.Pushpin, point);
                //shape.SetTitle(OfficeDetails.Officewebname); 
                // get office image 
                listingImageUrl = OfficeBaseImageUrl + "/O/" + OfficeDetails.Officeid + ".jpg";
                // qry path ti Office detail         
                QryListing = LiveURL + "/Pages/OfficeDetail.aspx?OID=" + OfficeDetails.Officeid + "'";

                // apth to Agent List
                OpenAgentList = LiveURL + "/Pages/AgentList.aspx?OID=" + OfficeDetails.Officeid + "'";

                shape.SetCustomIcon(SetCustomShapeOffice("office_icon.gif"));
                // shape.SetCustomIcon(SetCustomShape("office_icon.gif",44));


                //             listingDeatil = "<div><span class='FontBold'>" + OfficeDetails.Address + "</span></div>";
                //             listingDeatil += "<div><span class='FontBold'>" + formatDate(OfficeDetails.Contactphone) + "</span></div>"
                //              listingDeatil += "<div><img src='" +  listingImageUrl + "' alt='' width='80px' ></img></div>";
                //              listingDeatil += "<div><a href=" + QryListing + " >View Office Detail</a>&nbsp; &nbsp;";
                //               listingDeatil += "<a href=" + OpenAgentList + " >View Office Agents </a> </div>";


                var listingDeatil = "<div >";
                listingDeatil += "<table border='0' cellpadding='0' cellspacing='0' >";
                listingDeatil += "<tbody>";
                listingDeatil += "<tr>";
                listingDeatil += "<td align='center' valign='middle'>";
                listingDeatil += "<a href=" + QryListing + " ><img style='vertical-align: middle;' src='" + listingImageUrl + "' width='100'></a>&nbsp;";
                listingDeatil += "</td>";
                listingDeatil += "<td>";
                listingDeatil += "<div class='ListingInfoContainer' style='word-wrap:break-word'><b>" + OfficeDetails.Officewebname + "</b><br>" + OfficeDetails.Address + "<br>" + OfficeDetails.City + "<br>" + FormatPhone(OfficeDetails.Contactphone) + "</div>";
                listingDeatil += "</td>";
                listingDeatil += "</tr>";
                listingDeatil += "</tbody>";
                listingDeatil += "</table>";
                listingDeatil += "</div>";
                listingDeatil += "<div style='float:left'><a href=" + QryListing + " >View Office details</a>&nbsp;&nbsp;</div>";
                listingDeatil += "<div style='float:left'><a href=" + OpenAgentList + " >View Office Agents</a>&nbsp;&nbsp;</div>";

                listingDeatil += "</div>";



                shape.SetDescription(listingDeatil);
                if (map != null) {

                    map.AddShape(shape);
                    officeicon[i] = shape.GetID();
                }

            } //checkbox 
            else {
                ShowHideAlert();
                // if show office is not checked then check if any
                // shapes are added if there are ,then remove them from Map

                if (officeicon != null) {

                    for (var i = 0; i < officeicon.length; i++) {
                        shape = map.GetShapeByID(officeicon[i]);
                        if (shape != null) {
                            map.DeleteShape(shape);
                        }
                    }
                    //return;
                }


            }
        }

    }


}
      
      
