var map;
var markers1 = new Array();
var property_icon;
var office_icon;
var urlParam ="";
var datenow,datethen;
var om ;
var clusterer;
var bounds; 
function createFeaturedMap(clientID, page, longitude, lat, zoom, sortBy, agentId, officeId, bedRooms, city, flashTourYN, fullBaths, maxListPrice, minListPrice, openYN, phototourYN, propertyCategory, propertyType, reportYN, tourYN) {

    addMapControls(lat,longitude,zoom);
  urlParam ="&ff=1";
  
  try { 
  loadXMLDoc('/idx/controllers/request.cfm?cid='+clientID+'&random='+(Math.random()*Date.parse(new Date()))+'&pn='+page+'&sb='+sortBy+'&aid='+agentId+'&oid='+officeId+'&bd='+bedRooms+'&cit='+city+'&ft='+flashTourYN+'&fb='+fullBaths+'&mxlp='+maxListPrice+'&mnlp='+minListPrice+'&op='+openYN+'&ptr='+phototourYN+'&pc='+propertyCategory+'&pt='+propertyType+'&rpt='+reportYN+'&tr='+tourYN+'&ct=map&mt=loadFeaturedMap');
      }
  catch(er){/*alert("Not able to load");*/}

}
function createListingsMap(clientID, page, longitude, lat, zoom, sortBy, agedCommunityYN, geographicLike, misc1YN, misc2YN, misc3YN,misc4YN,baseMentYN,bedrooms,boardID,censusTract, cityID, countyID, dateImported, dateRange, diningRoomYN, familyRoomYN,fireplaceYN,fullBaths, garageSpaces, garYN, golfCourseYN, halfBaths,horsePropertyYN,inclusiveYN, listingNumber,lotAcres,lotSqFt,mapCode,maxListPrice, minListPrice, miscInt1, miscInt2, miscInt3, miscInt4, miscInt5,miscInt6,miscInt7,miscInt8, reoYN, shortsaleYN,styleLike,foreClosureYN,miscString1,miscString2, miscString3, miscString4, mlsArea, newYN,  neighborhood, newConstructionYN,numFireplaces,oneStoryYN, openHomesOnlyYN, poolYN, propertyLocation,  propertySubType,  propertySubType2, propertyType, region, schoolDistrict, squareFeet, streetName, streetNumber, style,unitTotal, viewDescription, viewYN, waterBody, waterFrontDesc,waterFrontYN, yearBuilt, zip) {

    addMapControls(lat,longitude,zoom);
  
  try {
  loadXMLDoc('/idx/controllers/request.cfm?cid='+clientID+'&random='+(Math.random()*Date.parse(new Date()))+'&pn='+page+'&sb='+sortBy+'&acYN='+agedCommunityYN+'&gLike='+geographicLike+'&ms1YN='+misc1YN+'&ms2YN='+misc2YN+'&ms3YN='+misc3YN+'&ms4YN='+misc4YN+'&bs='+baseMentYN+'&bd='+bedrooms+'&cet='+censusTract+'&bid='+boardID+'&c1='+cityID+'&cnty='+countyID+'&di='+dateImported+'&dtr='+dateRange+'&dn='+diningRoomYN+'&fr='+familyRoomYN+'&fp='+fireplaceYN+'&fbt='+fullBaths+'&gars='+garageSpaces+'&gar='+garYN+'&gc='+golfCourseYN+'&hbt='+halfBaths+'&hp='+horsePropertyYN+'&iv='+inclusiveYN+'&pid='+listingNumber+'&la='+lotAcres+'&lsf='+lotSqFt+'&map='+mapCode+'&mxlp='+maxListPrice+'&mnlp='+minListPrice+'&msi1='+miscInt1+'&msi2='+miscInt2+'&msi3='+ miscInt3+'&msi4='+miscInt4+'&msi5='+miscInt5+'&msi6='+miscInt6+'&msi7='+miscInt7+'&msi8='+miscInt8+'&reYN='+reoYN+'&ssYN='+shortsaleYN+'&stLike='+styleLike+'&fcYN='+foreClosureYN+'&mss1='+miscString1+'&mss2='+miscString2+'&mss3='+miscString3+'&mss4='+miscString4+'&ma='+mlsArea+'&nyn='+newYN+'&nb='+neighborhood+'&nc='+newConstructionYN+'&nfp='+numFireplaces+'&os='+oneStoryYN+'&oho='+openHomesOnlyYN+'&pl='+poolYN+'&plc='+propertyLocation+'&pst='+propertySubType+'&pst2='+propertySubType2+'&pt='+propertyType+'&rg='+region+'&sds='+schoolDistrict+'&sf='+squareFeet+'&sn='+ streetName+'&sno='+streetNumber+'&sst='+style+'&ut='+unitTotal+'&vwd='+viewDescription+'&vw='+viewYN+'&wb='+waterBody+'&wfd='+waterFrontDesc+'&wf='+waterFrontYN+'&yb='+yearBuilt+'&zip='+zip+'&ct=map&mt=loadListingsMap');
  }
  catch(er){/*alert("Not able to load");*/}

}
function createOpenHomeMap(clientID, page, longitude, lat, zoom, sortBy) {

    addMapControls(lat,longitude,zoom);
  urlParam ="&ff=1";
  
  try{  
  loadXMLDoc('/idx/controllers/request.cfm?cid='+clientID+'&random='+(Math.random()*Date.parse(new Date()))+'&pn='+page+'&sb='+sortBy+'&ct=map&mt=loadOpenHomeMap');
  }
  catch(er){/*alert("Not able to load");*/}

}
function createSearchProfileMap(clientID, page, longitude, lat, zoom, sortBy, agedCommunityYN, geographicLike, misc1YN, misc2YN, misc3YN,misc4YN, baseMentYN,bedrooms,boardID,censusTract, cityID, countyID, dateImported, dateRange, diningRoomYN, familyRoomYN,fireplaceYN,fullBaths, garageSpaces, garYN, golfCourseYN, halfBaths,horsePropertyYN,inclusiveYN, listingNumber,lotAcres,lotSqFt,mapCode,maxListPrice, minListPrice, miscInt1, miscInt2, miscInt3, miscInt4, miscInt5,miscInt6,miscInt7,miscInt8,miscString1,miscString2, miscString3, miscString4, foreClosureYN, reoYN, shortsaleYN, styleLike,mlsArea, newYN,  neighborhood, newConstructionYN,numFireplaces,oneStoryYN, openHomesOnlyYN, poolYN, propertyLocation, propertySubType,  propertySubType2, propertyType, region, schoolDistrict, squareFeet, streetName, streetNumber, style,unitTotal, viewDescription, viewYN, waterBody, waterFrontDesc,waterFrontYN, yearBuilt, zip, startDate, endDate, menuItem) {

    addMapControls(lat,longitude,zoom);
    urlParam ="&fspm=1";
  try{
  loadXMLDoc('/idx/controllers/request.cfm?cid='+clientID+'&random='+(Math.random()*Date.parse(new Date()))+'&pn='+page+'&sb='+sortBy+'&acYN='+agedCommunityYN+'&gLike='+geographicLike+'&ms1YN='+misc1YN+'&ms2YN='+misc2YN+'&ms3YN='+misc3YN+'&ms4YN='+misc4YN+'&bs='+baseMentYN+'&bd='+bedrooms+'&cet='+censusTract+'&bid='+boardID+'&c1='+cityID+'&cnty='+countyID+'&di='+dateImported+'&dn='+diningRoomYN+'&fr='+familyRoomYN+'&fp='+fireplaceYN+'&fbt='+fullBaths+'&gars='+garageSpaces+'&gar='+garYN+'&gc='+golfCourseYN+'&hbt='+halfBaths+'&hp='+horsePropertyYN+'&iv='+inclusiveYN+'&pid='+listingNumber+'&la='+lotAcres+'&lsf='+lotSqFt+'&map='+mapCode+'&mxlp='+maxListPrice+'&mnlp='+minListPrice+'&msi1='+miscInt1+'&msi2='+miscInt2+'&msi3='+ miscInt3+'&msi4='+miscInt4+'&msi5='+miscInt5+'&msi6='+miscInt6+'&msi7='+miscInt7+'&msi8='+miscInt8+'&mss1='+miscString1+'&mss2='+miscString2+'&mss3='+miscString3+'&mss4='+miscString4+'&fcYN='+foreClosureYN+'&reYN='+reoYN+'&ssYN='+shortsaleYN+'&stLike='+styleLike+'&ma='+mlsArea+'&nyn='+newYN+'&nb='+neighborhood+'&nc='+newConstructionYN+'&nfp='+numFireplaces+'&os='+oneStoryYN+'&oho='+openHomesOnlyYN+'&pl='+poolYN+'&plc='+propertyLocation+'&pst='+propertySubType+'&pst2='+propertySubType2+'&pt='+propertyType+'&rg='+region+'&sds='+schoolDistrict+'&sf='+squareFeet+'&sn='+ streetName+'&sno='+streetNumber+'&sst='+style+'&ut='+unitTotal+'&vwd='+viewDescription+'&vw='+viewYN+'&wb='+waterBody+'&wfd='+waterFrontDesc+'&wf='+waterFrontYN+'&yb='+yearBuilt+'&zip='+zip+'&sd='+startDate+'&ed='+endDate+'&mi='+menuItem+'&ct=map&mt=loadSearchProfileMap');
  }
  catch(er){/*alert("Not able to load");*/}

}
function createHotSheetMap(clientID, page, longitude, lat, zoom) {

    addMapControls(lat,longitude,zoom);
  urlParam ="&fh=1";
  
  try{  
  loadXMLDoc('/idx/controllers/request.cfm?cid='+clientID+'&random='+(Math.random()*Date.parse(new Date()))+'&pn='+page+'&ct=map&mt=loadHotSheetMap');
  }
  catch(er){/*alert("Not able to load");*/}

}




function populateMap(req) {
  
  var xmlDoc = req.responseXML;
  
  //element = document.getElementById('myDiv')
  //element.innerHTML = 'populate map ran..<br />' + xmlDoc;
    
  var markers = xmlDoc.documentElement.getElementsByTagName("field")
  var temp = xmlDoc.documentElement.getElementsByTagName("recordset");
  var records = temp[0].getAttribute("rowCount");

  
  //limit mapping of records to 100
  if (records>50){
       records = 50;
  }

  //alert(map.getZoomLevel());
  //map.clearOverlays();
      
  for (i=0;i<records;i++) {
    
    try {
      var street = markers[0].childNodes[i].firstChild.nodeValue;
      street = street.replace(/null/g,'');
      var city = markers[1].childNodes[i].firstChild.nodeValue;
      var state = markers[2].childNodes[i].firstChild.nodeValue;
      var boardID = markers[3].childNodes[i].firstChild.nodeValue;
      var listingnumber = markers[4].childNodes[i].firstChild.nodeValue;
      var longitude = markers[5].childNodes[i].firstChild.nodeValue;
      var latitude = markers[6].childNodes[i].firstChild.nodeValue;
      var propertycategory = markers[7].childNodes[i].firstChild.nodeValue;
      var zip = markers[8].childNodes[i].firstChild.nodeValue;
      var listprice = markers[9].childNodes[i].firstChild.nodeValue;
      
      var bedrooms = 0;
      var fullbaths = 0;
      var halfbaths = 0;
      if (propertycategory == 'SFR' || propertycategory == 'CND' || propertycategory == 'MH' || propertycategory == 'RNT')
      {
        bedrooms = markers[10].childNodes[i].firstChild.nodeValue;
        fullbaths = markers[11].childNodes[i].firstChild.nodeValue;
        halfbaths = markers[12].childNodes[i].firstChild.nodeValue;
      }
      var status = markers[13].childNodes[i].firstChild.nodeValue;
      var fullpartialaddress = markers[14].childNodes[i].firstChild.nodeValue;
      var ownlisting = markers[15].childNodes[i].firstChild.nodeValue;

      var clientID = markers[16].childNodes[i].firstChild.nodeValue;
      var subscriberID = markers[17].childNodes[i].firstChild.nodeValue;
      var thumbnail = markers[18].childNodes[i].firstChild.nodeValue;
      var formatted_price = markers[19].childNodes[i].firstChild.nodeValue;
      var showschedulelink = markers[20].childNodes[i].firstChild.nodeValue;
      var showaddressonfeatured = markers[21].childNodes[i].firstChild.nodeValue;
      var listingbroker = markers[22].childNodes[i].firstChild.nodeValue;
      var mlslogo =markers[23].childNodes[i].firstChild.nodeValue;
      
      //latitude != 37.062500 && longitude != -95.677068
      var bathHtml ="";
      if (halfbaths!=0.0){
        bathHtml ="+" + Math.floor(halfbaths);
      }
      var showingHtml ="";
      if((parseInt(showschedulelink) == 1)&&(status.toUpperCase()=='ACTIVE'|| status.toUpperCase()=='COMING')){
        showingHtml = "<a href='/idx/showingschedule.cfm?cid=" + clientID + "&pid=" + listingnumber + "&bid=" + Math.floor(boardID) + "&pt=" + propertycategory + "'>Schedule a Showing</a> |";
      }
      if(fullpartialaddress.toUpperCase() =='N')
      {
        if ((parseInt(ownlisting)==0) || (parseInt(ownlisting)==1 && parseInt(showaddressonfeatured)==0))
        {
          street ="";
        }
      }
      var markerHtml = "<div id='infowindow' style='width:225px; font-size:11px; font-family: arial;'>" + street + "<br>" + city + ", " + state + " " + zip + "<table cellpadding='2' cellspacing='0' border='0'><tr><td>" +  thumbnail + "</td><td class='textsmall_10_Verdana' nowrap='nowrap'>$" + formatted_price + "<br />" + Math.floor(bedrooms) + " Beds<br />" + Math.floor(fullbaths) + bathHtml +" Baths<br />Listing#" + listingnumber +"<br />" + mlslogo +"</td></tr></table><div id='moredetailslink' style='margin-top:3px'><a href='/idx/detail.cfm?cid=" + clientID + "&pid=" + listingnumber + "&bid=" + Math.floor(boardID) + urlParam +"'>More Details</a> | " + showingHtml + " <a href='/idx/controllers/request.cfm?cid=" + clientID + "&pid=" + listingnumber + "&bid=" + Math.floor(boardID) + "&sid=" + parseInt(subscriberID) + "&ct=organizer&mt=saveProperty'>SAVE!</a></div><div id='listingbroker'style='margin-top:3px' >" + listingbroker +"</div></div>";
    
    
      if (latitude != 0.0 && longitude != 0.0) { // These are the defaults for malformed addresses
        addMarker(longitude, latitude, markerHtml, listingnumber, property_icon);
      }
       
    }
    
    catch(er) {  /* alert(er); */  }
  }
       /* map.setZoom(map.getBoundsZoomLevel(bounds)-6);
          var clat = bounds.getSouthWest().lat() + ((bounds.getNorthEast().lat() 
- bounds.getSouthWest().lat()) / 2); 
          var clng = bounds.getSouthWest().lng() + ((bounds.getNorthEast().lng() 
- bounds.getSouthWest().lng()) / 2);
          map.setCenter(new GLatLng(clat,clng));*/
    om.Clear();
    
}
    
function addMarker(longitude,latitude,html,id,icon) {
  //bounds = new GLatLngBounds();
  var marker = new GMarker(new GLatLng(latitude,longitude),icon);
  markers1["p" + id] = marker;
  //var point = new GLatLng(latitude,longitude);
  //bounds.extend(point);
  map.addOverlay(marker);
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html);
  });
}

function loadXMLDoc(url, divID, height) {
  

  var req;
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
    req.onreadystatechange = function() {
      if (req.readyState == 4 ){
        populateMap(req);
      } 
    }
    req.open("GET", url, true);
    req.send(null);
  // branch for IE/Windows ActiveX version
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange = function() {
        if (req.readyState == 4){
          populateMap(req);
        }
      }
      req.open("POST", url, true);
      req.send(null);
    }
  }
}

function findMarker(id) {

  var marker = markers1["p" + id];
  if (marker == null) { alert('This property could not be mapped'); return; }
  GEvent.trigger(marker, "click");
}
function addMapControls(latitude,longitude,zoomlevel){
  
  om=new OverlayMessage(document.getElementById( 'container' ));
  map = new GMap2(document.getElementById("map"));
  map.addControl(new GSmallZoomControl());
  map.addControl(new GMapTypeControl());
  map.setCenter(new GLatLng(latitude, longitude), zoomlevel);
  
  property_icon = new GIcon();
  property_icon.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
  //property_icon.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
  property_icon.iconSize = new GSize(12, 20);
  //property_icon.shadowSize = new GSize(22, 20);
  property_icon.iconAnchor = new GPoint(6, 20);
  property_icon.infoWindowAnchor = new GPoint(5, 1);      
  
  office_icon = new GIcon();
  office_icon.image = "/idx/images/mapIconYellow.gif";
  //office_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
  office_icon.iconSize = new GSize(20, 20);
  //office_icon.shadowSize = new GSize(22, 20);
  office_icon.iconAnchor = new GPoint(6, 20);
  office_icon.infoWindowAnchor = new GPoint(5, 1);
  om.Set( 'Loading data, Please wait...' );
  //addMarker(long, lat, '', '2', property_icon);
  
  //element = document.getElementById('myDiv')
  //element.innerHTML = page;
}

/*function resizeMap( map, markers ) { 
        // Create new bounds object 
        var bounds = new GLatLngBounds(); 


        // Loop through the points, extending the bounds as necessary 
        for (var i=0; i<markers.length; i++) { 
                bounds.extend(markers[i].getPoint()); 
        } 


        // Find the centre of the new bounds 
       var lat = bounds.getSouthWest().lat() + ((bounds.getNorthEast().lat() 
- bounds.getSouthWest().lat()) / 2); 
        var lon = bounds.getSouthWest().lng() + ((bounds.getNorthEast().lng() 
- bounds.getSouthWest().lng()) / 2); 


        // Get the bounds zoom level 
        var zoom = map.getBoundsZoomLevel(bounds); 


        // Change the map to the new bounds values 
       // map.setCenter(new GLatLng(lat, lon), zoom); 
     
      map.setCenter(bounds.getCenter(), zoom);


}*/ 

  
