/**************************************************************
Global variables
**************************************************************/

var pagenum;
var req;
var centerLatitude = 37.12257173708531;
var centerLongitude = -76.4813232421875;


//set globals for centerlat and centerlng variables that will come from server
var centerlat = 0;
var centerlng = 0;

var global_centeron;

var startZoom = 9;
var map;

//keep track of whether an infowindow is open because if it is, we don't want to clear the overlays
var infoWindowOpen = 0;

var blankIcon = new GIcon();
blankIcon.image = "http://dailypress2.com/propertysales/media/blank.png";
blankIcon.iconSize = new GSize(28,28);
blankIcon.iconAnchor = new GPoint(14,14);

//for clustering
var clusterer;
var clusterIcon = new GIcon();
clusterIcon.image = "http://dailypress2.com/newsroom/fishing/graphics/cluster.png";
clusterIcon.iconSize=new GSize(24,25);
clusterIcon.iconAnchor=new GPoint(6,20);
clusterIcon.infoWindowAnchor=new GPoint(5,5);

var bounds;
var southWest;
var northEast;
var exclude_southWest;
var exclude_northEast;
var exclude_bounds;



//variable for overview map
var overviewmap;



var clusterMarkers = []; //new Array();

//Icons to place over each locality on map when user is zoomed out 
var gIcon = new GIcon();
gIcon.image = "http://dailypress2.com/propertysales/media/glomarker.png";
gIcon.iconSize = new GSize(52,30);
gIcon.iconAnchor = new GPoint(26,15);
var gPoint = new GLatLng(37.4137282185,-76.5750423040);
var gMarker = new GMarker(gPoint,gIcon);
var gFocus = function() { map.setCenter(gPoint,13); };

var hIcon = new GIcon();
hIcon.image = "http://dailypress2.com/propertysales/media/hammarker.png";
hIcon.iconSize = new GSize(52,30);
hIcon.iconAnchor = new GPoint(26,15);
var hPoint = new GLatLng(37.027224915558826, -76.343994140625);
var hMarker = new GMarker(hPoint,hIcon);
var hFocus = function() { map.setCenter(hPoint,13); };

var iwIcon = new GIcon();
iwIcon.image = "http://dailypress2.com/propertysales/media/iwmarker.png";
iwIcon.iconSize = new GSize(52,30);
iwIcon.iconAnchor = new GPoint(26,15);
var iwPoint = new GLatLng(36.9918263842,-76.7021598230);
var iwMarker = new GMarker(iwPoint,iwIcon);
var iwFocus = function() { map.setCenter(iwPoint,13); };

var jcIcon = new GIcon();
jcIcon.image = "http://dailypress2.com/propertysales/media/jcmarker.png";
jcIcon.iconSize = new GSize(52,30);
jcIcon.iconAnchor = new GPoint(26,15);
var jcPoint = new GLatLng(37.25000751785145, -76.76902770996094);
var jcMarker = new GMarker(jcPoint,jcIcon);
var jcFocus = function() { map.setCenter(jcPoint,13); };

var matIcon = new GIcon();
matIcon.image = "http://dailypress2.com/propertysales/media/matmarker.png";
matIcon.iconSize = new GSize(52,30);
matIcon.iconAnchor = new GPoint(26,15);
var matPoint = new GLatLng(37.4863869795,-76.4491671267);
var matMarker = new GMarker(matPoint,matIcon);
var matFocus = function() { map.setCenter(matPoint,13); };

var nnIcon = new GIcon();
nnIcon.image = "http://dailypress2.com/propertysales/media/nnmarker.png";
nnIcon.iconSize = new GSize(52,30);
nnIcon.iconAnchor = new GPoint(26,15);
var nnPoint = new GLatLng(37.0808262743,-76.4938162242);
var nnMarker = new GMarker(nnPoint,nnIcon);
var nnFocus = function() { map.setCenter(nnPoint,13); };

var pqIcon = new GIcon();
pqIcon.image = "http://dailypress2.com/propertysales/media/poqmarker.png";
pqIcon.iconSize = new GSize(52,30);
pqIcon.iconAnchor = new GPoint(26,15);
var pqPoint = new GLatLng(37.1314897458,-76.3768938249);
var pqMarker = new GMarker(pqPoint,pqIcon);
var pqFocus = function() { map.setCenter(pqPoint,13); };

var sufIcon = new GIcon();
sufIcon.image = "http://dailypress2.com/propertysales/media/sufmarker.png";
sufIcon.iconSize = new GSize(52,30);
sufIcon.iconAnchor = new GPoint(26,15);
var sufPoint = new GLatLng(36.7739369660,-76.5575844069);
var sufMarker = new GMarker(sufPoint,sufIcon);
var sufFocus = function() { map.setCenter(sufPoint,13); };

var wIcon = new GIcon();
wIcon.image = "http://dailypress2.com/propertysales/media/wbgmarker.png";
wIcon.iconSize = new GSize(52,30);
wIcon.iconAnchor = new GPoint(26,15);
var wPoint = new GLatLng(37.27760430457319, -76.68937683105469);
var wMarker = new GMarker(wPoint,wIcon);
var wFocus = function() { map.setCenter(wPoint,13); };

var yIcon = new GIcon();
yIcon.image = "http://dailypress2.com/propertysales/media/yrkmarker.png";
yIcon.iconSize = new GSize(52,30);
yIcon.iconAnchor = new GPoint(26,15);
var yPoint = new GLatLng(37.1883658375,-76.5148389455);
var yMarker = new GMarker(yPoint,yIcon);
var yFocus = function() { map.setCenter(yPoint,13); };


//global variables for searching/filtering
var global_maxpage = null;
var global_zip = null;
var global_city = null;
var global_price_start = null;
var global_price_end = null;
var global_street = null;
var global_jranges = null;
var global_jlocalities = null;
var global_jdays = null;
var global_jmonths = null;
var global_jyears = null;
var global_sort;
var global_order;
var global_seller;
var global_buyer;
var global_near;
var global_radius;
var global_date_start;
var global_date_end;


//icon urls
var url0 = 'http://dailypress2.com/newsroom/propsales/icons/mm_20_white.png';
var url1 = 'http://dailypress2.com/newsroom/propsales/icons/mm_20_gray.png';
var url100 = 'http://dailypress2.com/newsroom/propsales/icons/mm_20_orange.png';
var url250 = 'http://dailypress2.com/newsroom/propsales/icons/mm_20_purple.png';
var url500 = 'http://dailypress2.com/newsroom/propsales/icons/mm_20_green.png';
var url750 = 'http://dailypress2.com/newsroom/propsales/icons/mm_20_blue.png';
var url1000 = 'http://dailypress2.com/newsroom/propsales/icons/mm_20_red.png';

//keep track of row numbers for alternating row coloring
var rownum = 0;

//array of coordinates that have already been queried for; we can exclude these from future queries
var exclude = [];//new Array();



function excludeVars() {
  exclude_bounds = bounds;
  exclude_southWest = southWest;
  exclude_northEast = northEast;
  
  bounds = map.getBounds();
  southWest = bounds.getSouthWest().lat() + ',' + bounds.getSouthWest().lng();
  northEast = bounds.getNorthEast().lat() + ',' + bounds.getNorthEast().lng();

};


//function to clear exclude array
function clearExclude() {
  exclude.length = 0;
};

//functions for finding min and max coords of an array of coordinates
function excludeCoords(array) {

    var longitudes = []; //new Array();
    var latitudes = []; //new Array();
    
    //max number < 0 will be NE longitude
    //min number < 0 will be SW longitude
    for(i=0;i<array.length;i++) {
        if(array[i] < 0) {
            longitudes.push(array[i]);
        }
    }
    
    longitudes.sort();
    
    var ne_lng = longitudes[0];
    var sw_lng = longitudes[longitudes.length-1];
    
    //max number > 0 will be NE latitude
    //min number > 0 will be SW latitude
    for(i=0;i<array.length;i++) {
        if(array[i] > 0) {
            latitudes.push(array[i]);
        }
    }
    
    latitudes.sort();
    
    var sw_lat = latitudes[0];
    var ne_lat = latitudes[latitudes.length-1];
    
    return ne_lat + ',' + ne_lng + '|' + sw_lat + ',' + sw_lng;

};

//Create table with headers to hold sales list. Will be passed arguments of the table header cells.
/*
function createTable() {
    
    var heading = [];//new Array();
    
    heading_num = 0;
    //create a header cell for each argument passed to the function
    for(i=0;i<arguments.length;i++) {
        heading[i] = arguments[i];
    }


    var tableDiv = document.getElementById('saleslist');

    headRow = document.createElement('tr');
    tableHead.appendChild(headRow);
    tableDiv.appendChild(theTable);
    theTable.appendChild(tableHead);
    theTable.appendChild(tableBody);

    for (i=0; i<heading.length; i++)
    {
        headCell = document.createElement("th");
        
        //if the heading is for Address, don't allow sorting
        if(heading[i] == 'Address') {
            headCell.innerHTML = heading[i];
            } else {
            headCell.innerHTML = '<a href="javascript:sort(\'' + heading[i].toLowerCase() + '\')">' + heading[i] + '</a>';
            }
            
        headRow.appendChild(headCell);
    }

};
*/

//Function to change server request depending on which checkboxes are selected
function checkBoxes(id) {

    var ranges = [];//new Array(); //array to hold ID's of checked range items
    var rangeform = document.rangeform;
    
    //loop through each category's checkboxes to see which are checked.
    //if one is checked, add it to the proper array
    for(i=0;i<rangeform.elements.length;i++) {
        if(rangeform.elements[i].checked === true) {
            ranges.push(rangeform.elements[i].id);
        }
    }
    update(null,ranges,'search');
    
};


function ajaxReq() {
                      try{
                              // Opera 8.0+, Firefox, Safari
                              req = new XMLHttpRequest();
                          } catch (e){
                              // Internet Explorer Browsers
                              try{
                                  req = new ActiveXObject("Msxml2.XMLHTTP");
                              } catch (e) {
                                  try{
                                      req = new ActiveXObject("Microsoft.XMLHTTP");
                                  } catch (e){
                                      // Something went wrong
                                      //alert("Your browser broke!");
                                      return false;
                                  }
                              }
                          }
                        return req;
                      };



//init function - loads map, calls update function to get data
function init() {

    if (GBrowserIsCompatible())
        {
            /* set up our map */
            map = new GMap2(document.getElementById("map_canvas"));
            map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            //map.enableGoogleBar();
            //map.addControl(new GOverviewMapControl());
            map.enableDoubleClickZoom();
            
            //clear the exclude array when map is zoomed
            GEvent.addListener(map,'zoomend',function() {
                clearExclude();
            });

            GEvent.addListener(map,'moveend',function() {
                update(null,global_jranges,'move');
                
                excludeVars();
                
                
            });
            
            GEvent.addListener(map,'zoomend',function() {
                
                update(null,global_jranges,'zoom');
                
              });
              
              
            //run update function to get records and markers
            update(null,global_jranges,'search');
            
            
            //hack
            showHide();
            showHide();
            showHide();
            
            var mapdiv = document.getElementById("map_canvas");
            
            if(checkBrowser() == 'IE') {
                mapdiv.style.width = '777px';
            } else {
                mapdiv.style.width = '777px';
            }
            
            map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
            
            
        }

};


//function to initialize small map for standalone map pages
function small_init(lat,lng,address,city) {
            map = new GMap2(document.getElementById("small_map_canvas"));
            
            map.addControl(new GSmallMapControl());
            map.addControl(new GMapTypeControl());
            map.enableDoubleClickZoom();
            map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
            
            
            if(typeof(lat) != 'undefined' && typeof(lng) != 'undefined' && typeof(address) != 'undefined') {
              var thispoint = new GLatLng(lat,lng);
              
              map.setCenter(thispoint, 14);
              
              var thismarker = new GMarker(thispoint);
              
              map.addOverlay(thismarker);
              
              
              if(typeof(address) != 'undefined') {
                    
                    var popup = document.createElement('popup');
                    popupHtml = '<div class="popup">' + address + '<br>' + city + '</div>';
                    popup.innerHTML = popupHtml;
                    map.openInfoWindowHtml(thispoint, popup);
                    
                    var small_info_open = function() {
                        thismarker.openInfoWindowHtml(popupHtml);
                        return false;
                        };
                        
                    GEvent.addListener(thismarker, 'click', small_info_open);
                    
                    //GEvent.addListener(map,'moveend',function() {
                    //  small_map_update();
                    //});
                }

    }

};



//function to clear filter(reset everything to defaults);
function clearFilter() { 
      init();
      };

function clearSearch() {
    theform = document.getElementById('propSearch');
    
    for(i=0;i<theform.elements.length;i++) {
    
        if(theform.elements[i].type != 'button') {
            theform.elements[i].value = '';
            }
        }
    
    };
    

//function to send sort criteria and order to update()
//also changes global order variable to opposite of what it is set at now
function sort(sort) { 

      global_sort = sort;

      if(global_order == 'desc') {
          order = 'asc';
          global_order = 'asc';
          } else {
          order = 'desc';
          global_order = 'desc';
          }
      
      update(null,global_jranges);
      
    };
    
//update function for small map page
function small_map_update(lat,lng) {

    //holds variables to pass to query string
    getVars = '';
    
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    getVars += '&ne=' + northEast.toUrlValue();
    getVars += '&sw=' + southWest.toUrlValue();
    getVars += '&mappoints=1';

    
    getVars += '&near=' + lat + ',' + lng;
    getVars += '&radius=1';
    
    req = ajaxReq();
    
    req.open("GET", "/propertysales/server.php?" + getVars, true);
    
    req.onreadystatechange = function(){
        
        if(req.readyState == 4) {
        
            var points;
            
            jscript = req.responseText;
            
            eval(jscript);
            
            /*********************************************************************
            * points variable (an array) comes from server.php
            *********************************************************************/
            
            if(typeof(points) != 'undefined') {
              for(i in points) {
                    createMarker(points[i]);
                    }
              }
          
        }
    };
    
    req.send(null);
    
};




//fetches and updates records using Ajax
function update(centeron,jranges,event) {


  global_jranges = jranges;

    //clear overlays from map if user zooms in or out
    if(event == 'zoom' || event == 'search') {
        map.clearOverlays();
      } else if(event == 'move') {
      }
    
     
    //holds variables to pass to query string
    getVars = '';
    
    
      //create the boundry for the data to provide
      //initial filtering
      var bounds = map.getBounds();
      var southWest = bounds.getSouthWest();
      var northEast = bounds.getNorthEast();
      getVars += '&ne=' + northEast.toUrlValue();
      getVars += '&sw=' + southWest.toUrlValue();
      
      overviewmap =  new GOverviewMapControl();
      
      
      //check to see whether user is zoomed in enough to see points on map
      if(map.getZoom() > 11) {
          getVars += '&mappoints=1';
          
          map.addControl(overviewmap);
          

          } else {
              
              
              //remove overview map
              map.removeControl(overviewmap);

              //place icons over each locality and let user click on them to zoom in
              map.addOverlay(gMarker);
              gtooltip = 'Click to see Gloucester property transfers';
              GEvent.addListener(gMarker,'click',gFocus);
              GEvent.addListener(gMarker,'mouseover',function() { gMarker.openToolTip(gtooltip); });
              GEvent.addListener(gMarker,'mouseout',function() { gMarker.closeToolTip(); });
              map.addOverlay(hMarker);
              htooltip = 'Click to see Hampton property transfers';
              GEvent.addListener(hMarker,'click',hFocus);
              GEvent.addListener(hMarker,'mouseover',function() { hMarker.openToolTip(htooltip); });
              GEvent.addListener(hMarker,'mouseout',function() { hMarker.closeToolTip(); });
              map.addOverlay(iwMarker);
              iwtooltip = 'Click to see Isle of Wight property transfers';
              GEvent.addListener(iwMarker,'click',iwFocus);
              GEvent.addListener(iwMarker,'mouseover',function() { iwMarker.openToolTip(iwtooltip); });
              GEvent.addListener(iwMarker,'mouseout',function() { iwMarker.closeToolTip(); });
              map.addOverlay(jcMarker);
              jctooltip = 'Click to see James City property transfers';
              GEvent.addListener(jcMarker,'click',jcFocus);
              GEvent.addListener(jcMarker,'mouseover',function() { jcMarker.openToolTip(jctooltip); });
              GEvent.addListener(jcMarker,'mouseout',function() { jcMarker.closeToolTip(); });
              map.addOverlay(matMarker);
              mattooltip = 'Click to see Mathews property transfers';
              GEvent.addListener(matMarker,'click',matFocus);
              GEvent.addListener(matMarker,'mouseover',function() { matMarker.openToolTip(mattooltip); });
              GEvent.addListener(matMarker,'mouseout',function() { matMarker.closeToolTip(); });
              map.addOverlay(nnMarker);
              nntooltip = 'Click to see Newport News property transfers';
              GEvent.addListener(nnMarker,'click',nnFocus);
              GEvent.addListener(nnMarker,'mouseover',function() { nnMarker.openToolTip(nntooltip); });
              GEvent.addListener(nnMarker,'mouseout',function() { nnMarker.closeToolTip(); });
              map.addOverlay(pqMarker);
              pqtooltip = 'Click to see Poquoson property transfers';
              GEvent.addListener(pqMarker,'click',pqFocus);
              GEvent.addListener(pqMarker,'mouseover',function() { pqMarker.openToolTip(pqtooltip); });
              GEvent.addListener(pqMarker,'mouseout',function() { pqMarker.closeToolTip(); });
              map.addOverlay(sufMarker);
              suftooltip = 'Click to see Suffolk property transfers';
              GEvent.addListener(sufMarker,'click',sufFocus);
              GEvent.addListener(sufMarker,'mouseover',function() { sufMarker.openToolTip(suftooltip); });
              GEvent.addListener(sufMarker,'mouseout',function() { sufMarker.closeToolTip(); });
              map.addOverlay(wMarker);
              wtooltip = 'Click to see Williamsburg property transfers';
              GEvent.addListener(wMarker,'click',wFocus);
              GEvent.addListener(wMarker,'mouseover',function() { wMarker.openToolTip(wtooltip); });
              GEvent.addListener(wMarker,'mouseout',function() { wMarker.closeToolTip(); });
              map.addOverlay(yMarker);
              ytooltip = 'Click to see York property transfers';
              GEvent.addListener(yMarker,'click',yFocus);
              GEvent.addListener(yMarker,'mouseover',function() { yMarker.openToolTip(ytooltip); });
              GEvent.addListener(yMarker,'mouseout',function() { yMarker.closeToolTip(); });
          
          }


    //check to see if arguments are set. if not, use defaults
    if(typeof centeron != 'undefined' && centeron != null && centeron != 0) {
        getVars += '&centeron=' + centeron;

        }
    
    //check to see which checkboxes are checked by looking in 'checked' array passed to function
    if(typeof jranges != 'undefined' && jranges != null) {
        var rangestring = '&ranges=';
        for(i=0;i<jranges.length;i++) {
            rangestring += jranges[i] + ',';
        }
      getVars += rangestring;
    }
    

    
//if(event == 'move' || event == 'search') {
//Changed by aaron 7/7/08 - map wasn't showing anything on zoom
if(event == 'move' || event == 'search' || event == 'zoom') {

    req = ajaxReq();
    
    req.open("GET", "/propertysales/server.php?" + getVars, true);
    
    req.onreadystatechange = function(){
        
        if(req.readyState < 4) {
            document.getElementById('loading').style.display = '';
        }
        if(req.readyState == 4) {
        
            var points;
            
            document.getElementById('loading').style.display = 'none';
            
            jscript = req.responseText;
            
            eval(jscript);
            
            
            
            //If a center is set, it means the user searched for an area around an address or a zip code
            //if so, set that as the center of the map and zoom in on it
            //first check to see if that point is already the center and if the zoom level is already set
            //if we don't do that check, it will repeatedly fire the setZoom and setCenter methods,
            //crashing the browser
            if(event == 'search') {
                if(centerlat != 0 && centerlng != 0) {
                  var newcenter = new GLatLng(centerlat,centerlng);
                  var currentlat = map.getCenter().lat();
                  var currentlng = map.getCenter().lng();
                  
                  if(map.getZoom() != 13) {
                      map.setZoom(14);
                      }
                  
                  if(currentlat != centerlat && currentlng != centerlng) {
                      map.setCenter(newcenter);
                      }
                }
            }
            
            
            /*********************************************************************
            * prices variable (an array) comes from server.php
            *********************************************************************/
            
            var rangelist = document.getElementById('rangelist');
            rangeTable = '<table>';
            
            //create header
            rangeTable += '<tr class="filterHeader"><td colspan="5">Price filter</td></tr>';
            
            numrows = paging[0].numrows;
            
            for(i in ranges) {
                  
                  range = ranges[i];
                  
                  //determine what percentage of total this range makes up - so we can make a graph of it
                  pct = parseInt(range.num.replace(',',''),10) / parseInt(numrows.replace(',',''),10);
                  pct = Math.round(pct*1000)/10;

                  //if pct is >0<.5, make it 1 so that a small bar shows up. If it's 0, make it 0.
                  if(pct > 0 && pct < 1) {
                      pct = 1;
                      } else {
                      pct = Math.round(pct);
                      }

                  if(range.num.replace(',','') == 0) {
                      pct = 0;
                      }

                  //create checkbox for selecting/unselecting item
                  checkbox = '<input type="checkbox" name="' + range.abbreviation + '" id="' + range.abbreviation + '" onclick="javascript:checkBoxes(\'' + range.abbreviation + '\')" />';
                  
                  //create table row to hold information
                  rangeTable += '<tr>';
                  rangeTable += '<td class="check">' + checkbox + '</td>';
                  rangeTable += '<td class="cat">' + range.range + '</td>';
                  rangeTable += '<td class="num">' + range.num + '</td>';
                  
                  //because IE shows a small bar even when the pct is 0, only show the bar div when pct > 0
                  if(pct != 0) {
                    rangeTable += '<td class="pct"><div class="bar' + range.abbreviation + '" style="width:' + pct + '%;">&nbsp;</div></td>';
                    } else {
                    rangeTable += '<td class="pct"></td>';
                  }
                  
                  rangeTable += '</tr>';
                  
            }
            
            rangeTable += '</table>';
            rangelist.innerHTML = rangeTable;
            
            
            
            //re-check the checkboxes that the user checked (the check goes away when the item list is re-created
            if(typeof jranges != 'undefined' && jranges != null && jranges.length) {
                for(i=0;i<jranges.length;i++) {
                    document.getElementById(jranges[i]).checked = true;
                    }
                }

            if(typeof jlocalities != 'undefined' && jlocalities != null && jlocalities.length != 0) {
                for(i=0;i<jlocalities.length;i++) {
                    document.getElementById(jlocalities[i]).checked = true;
                }
            }

            if(typeof jdays != 'undefined' && jdays != null && jdays.length != 0) {
                for(i=0;i<jdays.length;i++) {
                    document.getElementById(jdays[i]).checked = true;
                }
            }

            if(typeof jmonths != 'undefined' && jmonths != null && jmonths.length != 0) {
                for(i=0;i<jmonths.length;i++) {
                    document.getElementById(jmonths[i]).checked = true;
                }
            }
            
            if(typeof jyears != 'undefined' && jyears != null && jyears.length != 0) {
                for(i=0;i<jyears.length;i++) {
                    document.getElementById(jyears[i]).checked = true;
                }
            }
          

            /*********************************************************************
            * points variable (an array) comes from server.php
            *********************************************************************/
            
            rownum = 0;


                  //check to see if there's a real marker included in set. if so, show the legend
                  var pointsa = points;
                  var legendDiv = document.getElementById('legend_items')
                  var realmarker = 0; //change to 1 if there's a real marker found
                  for(i in pointsa) {
                      if(pointsa[i].type == 'm') {
                          realmarker = 1;
                          break;
                      }
                  }
                  
                  if(realmarker == 1) {
                      legendDiv.style.display=''; //show legend
                  } else {
                      legendDiv.style.display='none'; //hide legend
                      }

                  //check to see whether user is zoomed in enough to see points on map

                  if(map.getZoom() > 11) {
                      
                      for(i in points) {
                          //use createMarker to create map marker and table row
                          createMarker(points[i]);
                      }
                    }
          
          
        }
        
        
    }
    

    
    req.send(null);
    
  } else {
  
    document.getElementById('loading').style.display = 'none';
    
    }
    
}




/**********************************************************************************
Function to create map markers
**********************************************************************************/
function createMarker(pointData){


    var point = new GLatLng(pointData.lat, pointData.lng);
    
    
    myIcon = new GIcon();
    myIcon.iconSize = new GSize(12,20);
    myIcon.iconAnchor = new GPoint(6,20);
    myIcon.infoWindowAnchor = new GPoint(5,6);
    var selectImage;
    
    var price = parseInt(pointData.price.replace(',','').replace(',','').replace(',','').replace(',','').replace('$',''),10);


    /* determine which icon to use, depending on sale price
     */
    switch(true)
    {
         case (price == 0 || price == ''):
             defaultImage = url0;
             break;    
         case (price <= 100000 && price > 0):
             defaultImage = url1;
             break;
         case (price > 100000 && price <= 250000 ):
             defaultImage = url100;
             break;
         case (price > 250000 && price <= 500000):
             defaultImage = url250;
             break;
         case (price > 500000 && price <= 750000):
             defaultImage = url500;
             break;
         case (price > 750000 && price <= 1000000):
             defaultImage = url750;
             break;
         case (price > 1000000):
             defaultImage = url1000;
             break;
         default:
             defaultImage = url0;
    }
    myIcon.image = defaultImage;
    

    //number of clustered markers in each cluster
    var clusterNum = pointData.num;
    
    opts = {
            "icon": blankIcon,
            "clickable": true,
            "labelText": clusterNum,
            "labelOffset": new GSize(-10,-10)
    };
    
    //create marker if the the item has a latitude and longitude
    if(pointData.lat != 0 && pointData.lng != 0) {
    
      if(pointData.type=='c') {
           var marker = new LabeledMarker(point, opts); //create the cluster marker
        } else {
           var marker = new GMarker(point, myIcon, false); //create the marker
          
      }

    }

    //variables for information to go in infowindows and table
    var buyer = pointData.salutation + ' ' + pointData.first + ' ' + pointData.last;
    var grantor = pointData.grantor;
    var date = pointData.date;
    var street = pointData.street;
    var city = pointData.city;
    var zip = pointData.zip;
    var price = pointData.price;
    
    var type = pointData.type;
    
     

    /* What to put in the infowindow
     */
    var popupHtml = '<div class="popup">';
    if(price != 0) {
        popupHtml += '<strong><span class="price">' + pointData.price + '</span></strong>';
        }
    popupHtml += '<p>Buyer: ' + buyer + '<br />';
    popupHtml += 'Seller: ' + grantor + '<br />';
    popupHtml += 'Date: ' + date + '</p>';
    popupHtml += '<p>';
    popupHtml += pointData.street + '<br />' + pointData.city + ' ' + pointData.zip + '</p>';
    
    //if map isn't zoomed in all the way, show link to zoom in
    if(map.getZoom() != 17) {
        popupHtml += '<p><a href="javascript:zoomIn(\'' + pointData.lat + '\',\'' + pointData.lng + '\')">Zoom in</a></p>';
    }
    
    
    if(pointData.zipmedian != '') {
      popupHtml += 'Median price in this ZIP code: ' + pointData.zipmedian + '<br />';
    }
    popupHtml += '</div>';
    
      /* This is the same as focusPoint 2 above, but it doesn't scroll the user to the top.
       * This one is used when a user clicks on a marker on the map. They're already near the
       * top of the page, so there's no need for us to scroll them up.
       */
      var focusPoint2_notop = function() {
        marker.openInfoWindowHtml(popupHtml);
          infoWindowOpen = 1;
        return false;
      }
      
      
      /*  This is a function to be called when a user clicks on a cluster
       *  It zooms the map in and sets the center to the coordinates of the clicked point
       */
      var markerCenter = new GLatLng(pointData.lat,pointData.lng)
      var nowZoom = map.getZoom() + 1;

      var clusterZoom = function() {
          map.setCenter(markerCenter,nowZoom);
          map.clearOverlays();
          return false;
      }

      
    //Call focusPoint2_notop when user clicks on a marker on the map
    //only do this for real markers -- type 'm'
    if(pointData.lat != 0 && pointData.lng != 0) {
        if(type == 'm') {
            GEvent.addListener(marker, 'click', focusPoint2_notop);
          } else {
        //if type is 'c'(cluster), zoom in when user clicks cluster icon
            //GEvent.addListener(marker,'click',map.setCenter(markerCenter,nowZoom));
            GEvent.addListener(marker, 'click', clusterZoom);
          }
        }
        

    //create marker if the the item has a latitude and longitude
    if(pointData.lat != 0 && pointData.lng != 0) {
        map.addOverlay(marker); //add the marker to the map
        
        //if it's a cluster marker, add marker to clusterMarkers array so we can remove it onmove
        if(type == 'c') {
            clusterMarkers.push(marker);
            }
        
    }
    

        //advance rownum number
        rownum++;

    //only do this if the item has a latitude and longitude
    if(pointData.lat != 0 && pointData.lng != 0) {
        var getMarkerDetail = function(){
            //var markerHTML = html;
            return false;
        } 

        //what to put in the tooltip:
        //if type is 'm'(actual marker), show information on sale
        //if type is 'c'(cluster), show how many real markers it represents
        if(type == 'm') {
            if(price != 0) {
              var tooltip = street + '<br />' + price + '<br /> Click icon for details.';
              } else {
              var tooltip = street + '<br />Click icon for details.';
              }
            } else {
                var tooltip = 'There are ' + clusterNum + ' property sales in this area.<br />Click to zoom in.';
              }
        
        // Pop up the tooltips on mouseover 
        GEvent.addListener(marker,'mouseover',function() {
          marker.openToolTip(tooltip);
        });

        // Hide the tooltips on mouseout
        GEvent.addListener(marker,'mouseout',function() {
          marker.closeToolTip();
        });

        
        return marker;
    }
        

};


/*************************************************************************************
FOR CUSTOM TOOLTIPS
*************************************************************************************/
//create the ToolTip overlay object
function ToolTip(marker,html,width) {
	this.html_ = html;
	this.width_ = (width ? width + 'px' : 'auto');
	this.marker_ = marker;
};

ToolTip.prototype = new GOverlay();

ToolTip.prototype.initialize = function(map) {
	var div = document.createElement("div");
	div.style.display = 'none';
	map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
	
	this.map_ = map;
	this.container_ = div;
};

ToolTip.prototype.remove = function() {
	this.container_.parentNode.removeChild(this.container_);
};

ToolTip.prototype.copy = function() {
	return new ToolTip(this.html_);
};

ToolTip.prototype.redraw = function(force) {
	if (!force) return;
	
	var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
	this.container_.innerHTML = this.html_;
	
	// Styles for custom tooltips

	this.container_.style.position = 'absolute';
	this.container_.style.left = pixelLocation.x - 2 + "px";
	this.container_.style.top = pixelLocation.y + 2 + "px";
	this.container_.style.width = this.width_;
	this.container_.style.font = 'normal 11px/11px verdana, arial, sans';
  this.container_.style.letterSpacing = '-0.01em';
  this.container_.style.lineHeight = '14px';
	this.container_.style.color = '#000';
	this.container_.style.border = '1px solid #424142';
	this.container_.style.background = '#F7F7F7';
	this.container_.style.filter = 'alpha(opacity=95)';
	this.container_.style.opacity = '.95';
	this.container_.style.padding = '4px';
	
	//one line to desired width
	this.container_.style.whiteSpace = 'nowrap';
	if(this.width_ != 'auto') this.container_.style.overflow = 'hidden';
	this.container_.style.display = 'block';
};

GMarker.prototype.ToolTipInstance = null;

// function to open tooltip 
GMarker.prototype.openToolTip = function(content) {
	//don't show the tool tip if there is acustom info window
	if(this.ToolTipInstance == null) {
		this.ToolTipInstance = new ToolTip(this,content)
		map.addOverlay(this.ToolTipInstance);
	}
};

// function to close tooltip 
GMarker.prototype.closeToolTip = function() {
	if(this.ToolTipInstance != null) {
		map.removeOverlay(this.ToolTipInstance);
		this.ToolTipInstance = null;
	}
};

/********************************************************************************
END TOOLTIP CODE
********************************************************************************/


//for switching between miles/mile depending on number selected
function makePlural() {
  var miles = document.getElementById('propSearch_full').radius.value;
  if(miles == 1) {
    document.getElementById('miles').innerHTML = 'mile';
    } else {
    document.getElementById('miles').innerHTML = 'miles';
  }

};

//search function - city, county, address or zip
function search() {
  var inputID = document.getElementById('centeron');
  
  var centeron = inputID.value;
  global_centeron = centeron;

  map.clearOverlays();

  update(centeron,global_jranges,'search');
  
  
};


//search function - for full search (buyer, seller, near address, price range, date, etc.
function search_full() {
  var theform = document.getElementById('propSearch_full');
  
  //search fields
  //seller,buyer,near,radius,price_start,price_end,date_start,date_end
  var seller = theform.seller.value;
  var buyer = theform.buyer.value;
  var near = theform.near.value;
  var radius = theform.radius.value;
  var zip = theform.zip.value;
  var price_start = null; //theform.price_start.value;
  var price_end = null; //theform.price_end.value;
  var date_start_month = theform.date_start_month.value;
  var date_start_day = theform.date_start_day.value;
  var date_start_year = theform.date_start_year.value;
  var date_end_month = theform.date_end_month.value;
  var date_end_day = theform.date_end_day.value;
  var date_end_year = theform.date_end_year.value;
  
  //add parts of date start and end together to get date start and end
  var date_start = date_start_year + '-' + date_start_month + '-' + date_start_day;
  var date_end = date_end_year + '-' + date_end_month + '-' + date_end_day;
  
  //set globals so we can retain variables when paging, sorting, etc.
  var global_seller = seller;
  var global_buyer = buyer;
  var global_near = near;
  var global_radius = radius;
  var global_price_start = price_start;
  var global_price_end = price_end;
  var global_date_start = date_start;
  var global_date_end = date_end;
  var global_zip = zip;
  
  map.clearOverlays();
  
};


//function to be called when user clicks to find properties near here on small map
function nearHere(lat,lng) {

  small_map_update(lat,lng);
  
};



//function to zoom in on map point
function zoomIn(lat,lng) {

  var center = new GLatLng(lat,lng);

  var currentZoom = map.getZoom();
  var newZoom = map.getZoom() + 1;
  
  if(currentZoom < 17 && currentZoom >= 15) {
    map.setCenter(center,newZoom);
    }
  
  if(currentZoom < 15) {
    map.setCenter(center,15);
    }
    
  if(currentZoom == 17) {
    }

};

//funciton to show or hide filter box
function showHide() {
    filterdiv = document.getElementById('filter');
    mapdiv = document.getElementById('map_canvas');
    togglediv = document.getElementById('toggle');
    mapcenter = map.getCenter();

    filterstate = filterdiv.style.display;
    mapstate = mapdiv.style.display;

    if(filterstate == 'none') {
        filterdiv.style.display = '';
        if(checkBrowser() == 'IE') {
            mapdiv.style.width = '543px';
        } else {
            mapdiv.style.width = '543px';
        }
        mapdiv.style.borderRight = '4px solid #000';
        mapdiv.style.borderBottom = '0';
        togglediv.innerHTML = '<a href="javascript:showHide()"><img src="http://dailypress2.com/propertysales/media/hidefilter.jpg" alt="hide filter" /></a>';
      
        //toggle overviewmap off and then back on. needed for ie bug
        if(map.getZoom() > 11) {
            map.removeControl(overviewmap);
            map.addControl(overviewmap);
        }
    } else {
        filterdiv.style.display = 'none';
        if(checkBrowser() == 'IE') {
            mapdiv.style.width = '777px';
        } else {
            mapdiv.style.width = '777px';
        }
        mapdiv.style.borderRight = '0';
        mapdiv.style.borderBottom = '0';
        togglediv.innerHTML = '<a href="javascript:showHide();"><img src="http://dailypress2.com/propertysales/media/showfilter.jpg" alt="show filter" />';
        
        //toggle overviewmap off and then back on. needed for ie bug
        if(map.getZoom() > 11) {
            map.removeControl(overviewmap);
            map.addControl(overviewmap);
        }
    }

    map.checkResize();

};

function checkBrowser() {
    var browser = navigator.appName;
    var b_version = navigator.appVersion;
    var version = parseFloat(b_version);

    if(browser == 'Microsoft Internet Explorer') {
        return 'IE';
    }

    if(browser == 'Netscape') {
        return 'Netscape';
    }

};


window.onunload = GUnload;
