$(document).unload(function(){
  GUnload();
});

var map,markerCluster, icons = {}, gIcons = {},curBounds, zoomManager,curCenter,centerChanged,curListPage = 0;


function gmsGetPropertyInfo(pids){
  var params;
  var first=1;
  for(var i in pids){
    if(first){
      first=0;
      params = "pid[" + i + "]=" + pids[i];
    }else{
      params = params + "&pid[" + i + "]=" + pids[i]; 
    }
  }
  $.ajax ({
    dataType:"json",
    type:"POST",
    data:params,
    url:"/mapSearch/getProperty",
    success: function(msg){
       $('#BubbleInfo').html(msg.html);
       map.updateInfoWindow();
       map.updateInfoWindow();
    }
  });
};

function checkGroupStatus(type){
  var status = false;
  var fullTypeID = parseInt(type);
  switch(fullTypeID){
      case 4:
      case 52:
      case 95:      
          status = $("#edit-properties-detached").attr('checked');
        break;
      case 10:
      case 24:
      case 49:
          status = $("#edit-properties-semi-detached").attr('checked');
        break;
      case 1:
      case 16:
          status = $("#edit-properties-townhomes").attr('checked');
        break;
      case 14:
      case 15:
      case 19:
      case 20:
      case 22:
      case 24:
      case 27:
      case 49:
      case 120:      
          status = $("#edit-properties-condos").attr('checked');
        break;
      case 32:
          status = $("#edit-properties-land").attr('checked');
        break;
      
  }
  return status;
}


function gmsMarkerOptions(marker){
  var markerOptions;
  
  var type = parseInt(marker.type);
  if(type == 1){
    markerOptions = { icon:icons.commercial };
    return markerOptions;
  }
  var fullTypeID = parseInt(marker.propertyFullTypeID);
  
  switch(fullTypeID){
      case 4:
      case 52:
      case 95:       
          markerOptions = { icon:icons.detached };
        break;
      case 10:
      case 24:      
      case 49:
          markerOptions = { icon:icons.semi };
        break;
      case 1:
      case 16:
          markerOptions = { icon:icons.town };
        break;
      case 14:
      case 15:
      case 19:
      case 20:
      case 22:
      case 24:
      case 27:
      case 49:
      case 120:       
          markerOptions = { icon:icons.condo };
        break;          
      default:

          markerOptions = { icon:icons.others };
  }

  return markerOptions;
}


function gmsCreateMarker(m, pids) {
  var latlng = new GLatLng(m.latitude, m.longitude);
  var markerOptions = gmsMarkerOptions(m);  
  var marker = new GMarker(latlng, markerOptions);
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml('<div id="BubbleInfo">Loading ..</div>');
    gmsGetPropertyInfo(pids);
  });
  
  return marker;
}


function gmsLoadMarkers(newmarkers){
  var j,pids=[],marker,markers=[],markerOptions;
  for (var i in newmarkers){
    if (!pids.length){
      pids.push(newmarkers[i].pid);
      j=i;
    }else{
      if((newmarkers[j].latitude == newmarkers[i].latitude) && (newmarkers[j].longitude == newmarkers[i].longitude) ){
        pids.push(newmarkers[i].pid);
      }else{
        marker=new gmsCreateMarker(newmarkers[j],pids);
        markers.push(marker);
        pids = [];
        pids.push(newmarkers[i].pid);
        j=i;
      }
    }
  }
  if (!pids.length){
      marker=new gmsCreateMarker(newmarkers[j],pids);
      markers.push(marker);
  }else{
      marker=new gmsCreateMarker(newmarkers[i],pids);
      markers.push(marker);
  }
  if(markerCluster != null) {
    markerCluster.clearMarkers();
  }
  var mcOptions = { gridSize: 20};
  markerCluster = new MarkerClusterer(map, markers,mcOptions);
}

function gmsMarkerGroupOptionsLabeled(marker){
  if(marker.count <= 99){
     var markerOptions = { icon:gIcons['20'],"clickable": true,"labelText": marker.count,"labelOffset": new GSize(4, 5) };
  }else{
    if(marker.count >99 && marker.count < 1000){
      var markerOptions = { icon:gIcons['50'],"clickable": true,"labelText": marker.count,"labelOffset": new GSize(6, 11)  };
    }else{
      var markerOptions = { icon:gIcons['100'],"clickable": true,"labelText": marker.count,"labelOffset": new GSize(16, 25)  };
    }
  }

  return markerOptions;
}
function gmsLoadMarkersGroup(newmarkers,zoom){
  var markers =[];
  for (var i in newmarkers){
    var latlng = new GLatLng(newmarkers[i].latitude,newmarkers[i].longitude);
    var marker = new LabeledMarker(latlng,gmsMarkerGroupOptionsLabeled(newmarkers[i]));
    GEvent.addListener(marker, "click", function() {
      map.setCenter(latlng, 13);
    });
    markers.push(marker);
  }
  zoomManager.addMarkers(markers, zoom,zoom);
  zoomManager.refresh();
}

function gmsLoadPropertiesList(){
    $('#gmapSearchList').html('<div id="loading" style="width: 100%; color: rgb(88, 151, 183); text-align: center; display: yes; "> '
	    + '<h2 style="margin-top: 100px;">LOADING</h2> '
	    + '<img src="/base_imgs/loading.gif" alt="" height="32" width="32"> '
	    + '<h3 style="font-size: 12px;">PLEASE WAIT</h3> '
      + '</div>');

    curBounds = map.getBounds();
    var geoSouthWestNet = curBounds.getSouthWest();
    var geoNorthEastNet = curBounds.getNorthEast();
    var params = "latNE=" + geoNorthEastNet.lat() + "&latSW=" + geoSouthWestNet.lat() + "&lngNE=" + geoNorthEastNet.lng() + "&lngSW=" + geoSouthWestNet.lng();
    if($("#edit-properties-detached").attr('checked')){
      params = params + '&properties[detached]=1';
    }
    if($("#edit-properties-detached").attr('checked')){
      params = params + '&properties[detached]=1';
    }
    if($("#edit-properties-semi-detached").attr('checked')){
      params = params + '&properties[semi-detached]=1';
    }
    if($("#edit-properties-townhomes").attr('checked')){
      params = params + '&properties[townhomes]=1';
    }
    if($("#edit-properties-condos").attr('checked')){
      params = params + '&properties[condos]=1';
    }
    if($("#edit-properties-land").attr('checked')){
      params = params + '&properties[land]=1';
    }
    if($("#edit-sale").attr('checked')){
      params = params + '&sale=1';
    }    
    if($("#rentLease").attr('checked')){
      params = params + '&lease=1';
    }
    if($("#edit-properties-other").attr('checked')){
      params = params + '&properties[other]=1';
    }    
    if(curListPage > 0){
      params = params + '&page=' + curListPage;
    }

    params = params + '&commonTypeID=' + $("#edit-commonTypeID").val();
    params = params + '&bedrooms=' + $("#edit-bedrooms").val();
    params = params + '&bathrooms=' + $("#edit-bathrooms").val();
    params = params + '&minprice=' + $("#edit-minprice").val();
    params = params + '&maxprice=' + $("#edit-maxprice").val();
        
    $.ajax ({
      dataType:"json",
      type:"POST",
      data:params,
      url:"/mapSearch/getProperties/TableList",
      success: function(msg){
        $('#gmapSearchList').html(msg.html);
      }
    });
}

function gmsLoadMapList(newZoomLevel,dragged){
    $("#gmapSearchLoading").show();
    curBounds = map.getBounds();
    if(!newZoomLevel){
      newZoomLevel = map.getZoom();
    }
    var geoSouthWestNet = curBounds.getSouthWest();
    var geoNorthEastNet = curBounds.getNorthEast();
    var params = "latNE=" + geoNorthEastNet.lat() + "&latSW=" + geoSouthWestNet.lat() + "&lngNE=" + geoNorthEastNet.lng() + "&lngSW=" + geoSouthWestNet.lng() + "&zoom=" + newZoomLevel;
    if($("#edit-properties-detached").attr('checked')){
      params = params + '&properties[detached]=1';
    }
    if($("#edit-properties-detached").attr('checked')){
      params = params + '&properties[detached]=1';
    }
    if($("#edit-properties-semi-detached").attr('checked')){
      params = params + '&properties[semi-detached]=1';
    }
    if($("#edit-properties-townhomes").attr('checked')){
      params = params + '&properties[townhomes]=1';
    }
    if($("#edit-properties-condos").attr('checked')){
      params = params + '&properties[condos]=1';
    }
    if($("#edit-properties-land").attr('checked')){
      params = params + '&properties[land]=1';
    }
    if($("#edit-sale").attr('checked')){
      params = params + '&sale=1';
    }    
    if($("#rentLease").attr('checked')){
      params = params + '&lease=1';
    }
    if($("#edit-properties-other").attr('checked')){
      params = params + '&properties[other]=1';
    }
    
    params = params + '&commonTypeID=' + $("#edit-commonTypeID").val();
    params = params + '&bedrooms=' + $("#edit-bedrooms").val();
    params = params + '&bathrooms=' + $("#edit-bathrooms").val();
    params = params + '&minprice=' + $("#edit-minprice").val();
    params = params + '&maxprice=' + $("#edit-maxprice").val();
   
    
//    if(newZoomLevel > 8){    
    $.ajax ({
      dataType:"json",
      type:"POST",
      data:params,
      url:"/mapSearch/getProperties",
      success: function(msg){
         if(msg.markers.length > 0){
           gmsLoadMarkers(msg.markers);
         }
         $("#gmapSearchLoading").hide();        
      }
    });
/*    }else{
          $.ajax ({
            dataType:"json",
            type:"POST",
            data:params,
            url:"/mapSearch/getProperties/Grouped",
            success: function(msg){
              if(dragged == "TRUE"){
                zoomManager.clearMarkers();
                gmsLoadMarkersGroup(msg.markers,newZoomLevel);
                zoomManager.refresh();
                $("#gmapSearchLoading").hide();
              }else{
                gmsLoadMarkersGroup(msg.markers,newZoomLevel);
                $("#gmapSearchLoading").hide();
              } 
            }
          })    
    }*/
}

$(document).ready(function(){
  $("#edit-properties-detached").click();
  $("#edit-properties-semi-detached").click();
  $("#edit-properties-townhomes").click();
  $("#edit-properties-condos").click();
  $("#edit-properties-other").click();  
  $("#gmapSearchPrevious").hide();

  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(defaultLatitude, defaultLongtitude), 13);
    map.setUIToDefault();
    map.disableScrollWheelZoom();
    
    G_PHYSICAL_MAP.getMinimumResolution = function () { return 11 };
    G_NORMAL_MAP.getMinimumResolution = function () { return 11 };
    G_SATELLITE_MAP.getMinimumResolution = function () { return 11 };
    G_HYBRID_MAP.getMinimumResolution = function () { return 11 };

    G_PHYSICAL_MAP.getMaximumResolution = function () { return 18 };
    G_NORMAL_MAP.getMaximumResolution = function () { return 18 };
    G_SATELLITE_MAP.getMaximumResolution = function () { return 18 };
    G_HYBRID_MAP.getMaximumResolution = function () { return 18 };
    
    centerChanged = 0;
    var properties = new Array("condo","detached","home","others","commercial","semi","town");
    

    var icon;
    for (var i in properties){
      icon = new GIcon();
      icon.image = '/modules/gmapSearch/images/' + properties[i] + '.png';
      icon.iconSize = new GSize(32, 32);
      icon.iconAnchor = new GPoint(16, 16);
      icon.infoWindowAnchor = new GPoint(25, 7);
      var theName = properties[i];
      icons[theName] = icon;
    }

    var grouped_properties = new Array ("20","50","100");
    var sizes = [53, 66, 90];
    
    for (var i in grouped_properties){
      icon = new GIcon();
      icon.image = '/modules/gmapSearch/images/' + grouped_properties[i] + '.png';
      icon.iconSize = new GSize(sizes[i], sizes[i]);
      icon.iconAnchor = new GPoint(16, 16);
      icon.infoWindowAnchor = new GPoint(25, 7);
      var theName = grouped_properties[i];
      gIcons[theName] = icon;
    }

    curCenter = map.getCenter();
    zoomManager = new MarkerManager(map);



    curBounds = map.getBounds();
    var geoSouthWestNet = curBounds.getSouthWest();
    var geoNorthEastNet = curBounds.getNorthEast();
    var params = "latNE=" + geoNorthEastNet.lat() + "&latSW=" + geoSouthWestNet.lat() + "&lngNE=" + geoNorthEastNet.lng() + "&lngSW=" + geoSouthWestNet.lng();

    gmsLoadMapList();
    gmsLoadPropertiesList();
        
    GEvent.addListener(map, "moveend", function() {
      var gmapInfoWindow = map.getInfoWindow();
      var curZoom = map.getZoom();
      var bounds = map.getBounds();
      var geoSouthWestNet = bounds.getSouthWest();
      var geoNorthEastNet = bounds.getNorthEast();

      if(curZoom > 8){
        if(gmapInfoWindow.isHidden()){

        
          var curgeoSouthWestNet = curBounds.getSouthWest();
          var curgeoNorthEastNet = curBounds.getNorthEast();
        
          if(geoSouthWestNet.lat() < curgeoSouthWestNet.lat() || geoSouthWestNet.lng() < curgeoSouthWestNet.lng() || geoNorthEastNet.lat() > curgeoNorthEastNet.lat() || geoNorthEastNet.lng() > curgeoNorthEastNet.lng()){
            curBounds = bounds;
            gmsLoadMapList(curZoom);
          }
          gmsLoadPropertiesList();
        }
        
      }else{
        if(gmapInfoWindow.isHidden()){
          gmsLoadMapList(curZoom,"TRUE");
          gmsLoadPropertiesList();
        }
      }
      
    });
    
    GEvent.addListener(map, "zoomend", function(oldLevel,newLevel) {
      var gmapInfoWindow = map.getInfoWindow();
      var bounds = map.getBounds();
      var geoSouthWestNet = bounds.getSouthWest();
      var geoNorthEastNet = bounds.getNorthEast();
      if(newLevel == 9 && oldLevel < newLevel){
        centerChanged = 0;
        curBounds = bounds;
        gmsLoadMapList(newLevel);
      }
      if((oldLevel > newLevel && newLevel > 8)){// || (newLevel == 13 && oldLevel < newLevel) ){
        var curgeoSouthWestNet = curBounds.getSouthWest();
        var curgeoNorthEastNet = curBounds.getNorthEast();
            
        if(geoSouthWestNet.lat() < curgeoSouthWestNet.lat() || geoSouthWestNet.lng() < curgeoSouthWestNet.lng() || geoNorthEastNet.lat() > curgeoNorthEastNet.lat() || geoNorthEastNet.lng() > curgeoNorthEastNet.lng()){
          curBounds = bounds;
          gmsLoadMapList(newLevel);
        }
      }else{
        if(newLevel <= 8 && oldLevel > newLevel){
          if(oldLevel == 9 ){
            if(markerCluster != null) {
              markerCluster.clearMarkers();
              zoomManager.refresh(); 
            }
          }
          var tmpCenter = map.getCenter();
          if(tmpCenter.lat() != curCenter.lat() || tmpCenter.lng() != curCenter.lng()){
            curCenter=tmpCenter;
            zoomManager.clearMarkers();
          }
          if(!zoomManager.getMarkerCount(newLevel)){ // map.getZoom()
            gmsLoadMapList(newLevel);
          }else{
            zoomManager.refresh(); 
          }
        }else{
          if(newLevel <= 8 && oldLevel < newLevel){
            if(!zoomManager.getMarkerCount(newLevel) || centerChanged){
              gmsLoadMapList(newLevel);
            }else{
              zoomManager.refresh(); 
            }
          }
        }
      }
      gmsLoadPropertiesList();
    });
    $("#edit-bedrooms").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();        
    });
    $("#edit-bathrooms").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();        
    });
    $("#edit-minprice").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();        
    });
    $("#edit-maxprice").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();

    });
    $("#edit-properties-detached").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();
    }); 
        
    $("#edit-properties-semi-detached").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();
    });
        

    $("#edit-properties-townhomes").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();
    });
        
    $("#edit-properties-condos").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();
    });     
    $("#edit-properties-land").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();
    });
    $("#edit-properties-other").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();
    });
    $("#edit-sale").click(function(){
      if($(this).attr('checked')){
        $("#saleprice").show('slow');
      }else{
        $("#saleprice").hide('slow');
      }
      $(this).blur();
      $(this).focus();
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();
    });
    $("#rentLease").click(function(){
      if($(this).attr('checked')){
        $("#rentprice").show('slow');
      }else{
        $("#rentprice").hide('slow');
      }
      $(this).blur();
      $(this).focus();
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();
    });   
    $("#edit-commonTypeID").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();

    });
    $("#gmapSearchNext").click(function(){
      curListPage=curListPage+1;
      gmsLoadPropertiesList();
      if(curListPage == 1){
        $("#gmapSearchPrevious").show();
      }
      return false;

    });
    $("#gmapSearchPrevious").click(function(){
      if(curListPage > 0){
        curListPage=curListPage-1;
        gmsLoadPropertiesList();
        if(curListPage == 0){
          $("#gmapSearchPrevious").hide();
        }
      }
      return false;

    });
    $("#edit-city").change(function(){
      var v = $("#edit-city").val();
      var values = v.split(";");
			map.setCenter(new GLatLng(values[0],values[1]),13);
    });
  }
});


