//This file contains functions for the interactive map functions on Interactivemap.aspx page


// 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 Stories = "0";
var Garages = "0";
var OpenHouses = "0";
var isDebug = true;
var IsSold = false;
var OpenHouseOnly = false;
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/";


/**
* 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, "chkOpenHouses")) {
        
            var checked = $(sender).is(":checked");
            var ddlOpenHouses = $(".ddlOpenHouses");
            ddlOpenHouses.attr('disabled', !checked);
            if (!checked) {
                ddlOpenHouses.attr('value', '0')
                OpenHouses = "0";
            }


        }
        else if (HasClassName(sender.parentNode, "chkNewOnMarket")) {
        

            var checked = $(sender).is(":checked");
            var ddlTimeOnMarket = $(".ddlTimeOnMarket");

            if (checked == false) {
                ddlTimeOnMarket.attr('disabled', true);
                ddlTimeOnMarket.attr('value', '0')
                Timeonmarket = "0";
            }
            else if (checked == true) {
            ddlTimeOnMarket.attr('disabled', false);
            Timeonmarket = ddlTimeOnMarket.val();
            }


        }
           
        
}

/**
* 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");

             $(".ddlTimeOnMarket", criteriaContext).val();
             var checked = GetCheckboxValue(".chkNewOnMarket", ControlType.CheckBox); 
             var ddlTimeOnMarket = $(".ddlTimeOnMarket");

             if (checked == false) {
                 ddlTimeOnMarket.attr('disabled', true);
                 ddlTimeOnMarket.attr('value', '0')
                 Timeonmarket = "0";
             }
             else if (checked == true) {
                 ddlTimeOnMarket.attr('disabled', false);
                 Timeonmarket = ddlTimeOnMarket.val();
             }
             
             
            
        // 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);

        //IsSold
        //IsSold = $($(".chkIsSold", mapContext)[0].childNodes[0]).is(":checked");
         IsSold = GetCheckboxValue(".chkIsSold", ControlType.CheckBox);
         OpenHouseOnly = GetCheckboxValue(".chkOpenHouses", 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("IMLL",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 += 300;
   maptop += 150;

   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:1,OpenHouses:OpenHouses,
         FeatureFront: FeatureFront, FeatureBoat: FeatureBoat, OffficeMapping:  OffficeMapping, LotsLand: LotsLand
         ,ZoomLevel: mapzoomlevel, MapCenterLat: mapcenter.Latitude, MapCenterLong: mapcenter.Longitude, isSold: IsSold  
         ,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();
    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)
{

    //Hide Searching div alert
    var $divSearchAlert=$('#divSearAlert');
    $divSearchAlert.hide();


    //set grid to empty
    if(gridContext == null)
        gridContext = $("InteractiveMapSearRCDetailGrid");
    var $gridDiv = $('div#ListingGridContainer');
    $gridDiv.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() ; 
      
    // 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?
           {
                
                 divalertleft=mapleft + 550;
                 //display alert and return
                 GetControl(map,"divAlert",divalertleft,maptop);
                   // 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 currentListingType = GetTypeForListing(listing);
            var currentListingIcon = GetIconForType(currentListingType);
            var isFav = IsFavoriteListing(listing);
            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 + "/Pages/PropertyDetail.aspx?ListingID=" + ListingID + "&NAV=1" + "'";

            if (!isFav)
                var QryFavorite = LiveURL + "/Popups/AddFavoriteListing.aspx?FLI=" + ListingID + '&PRC=' + listing.ListPrice + "&P=InteractiveMapSearch.aspx'";
            else
                var QryFavorite = LiveURL + "/Popups/RemoveFavoriteListing.aspx?FLI=" + ListingID + '&PRC=' + listing.ListPrice + "&P=InteractiveMapSearch.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=0&Width=100';
            }
            // make info ballon
            var listingDetail = new StringBuilder();
            listingDetail.append("<div >");
            listingDetail.append("<table border='0' cellpadding='0' cellspacing='0' >");
            listingDetail.append("<tbody>");

            if (currentListingType == ListingType.OpenHouse) {
                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;
    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=0&Width=100';
            }
          var QryListing=LiveURL + "/Pages/PropertyDetail.aspx?ListingID=" + ListingID +"&NAV=1"+ "'";
          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' style='height:35px' ><div class='RowContents' style='width:100px'>" + GetStatusForListing(listing)+ "</div></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>");


    
    $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();});
    });
    //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 style='font-family:Tahoma; width:25px; padding-top:5px; padding-bottom:20px; 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("</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;
              }
             
             
            }
        }
    
    }


}