$(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:
          status = $("#edit-properties-detached").attr('checked');
        break;
      case 10:
      case 24:
      case 49:
          status = $("#edit-properties-multiplex").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:
          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 = marker.PropertyType;
  
  switch(fullTypeID){
      case 'detached':
          markerOptions = { icon:icons.detached };
        break;
      case 'multiplex':
          markerOptions = { icon:icons.semi };
        break;
      case 'townhomes':
          markerOptions = { icon:icons.town };
        break;
      case 'condos':
          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-multiplex").attr('checked')){
      params = params + '&properties[multiplex]=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 + '&saleprice_minprice=' + $("#edit-saleprice-minprice").val();
    params = params + '&saleprice_maxprice=' + $("#edit-saleprice-maxprice").val();
    params = params + '&rentprice_minprice=' + $("#edit-rentprice-minprice").val();
    params = params + '&rentprice_maxprice=' + $("#edit-rentprice-maxprice").val();

        
    $.ajax ({
      dataType:"json",
      type:"GET",
      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-multiplex").attr('checked')){
      params = params + '&properties[multiplex]=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 + '&saleprice_minprice=' + $("#edit-saleprice-minprice").val();
    params = params + '&saleprice_maxprice=' + $("#edit-saleprice-maxprice").val();
    params = params + '&rentprice_minprice=' + $("#edit-rentprice-minprice").val();
    params = params + '&rentprice_maxprice=' + $("#edit-rentprice-maxprice").val();
   
    
//    if(newZoomLevel > 8){   
//    alert(params); 
    $.ajax ({
      dataType:"json",
      type:"POST",
      data:params,
      url:"/mapSearch/getProperties",
      success: function(msg){
         if(msg.markers.length > 0){
           gmsLoadMarkers(msg.markers);
         }else{
				  if(markerCluster != null) {
				    markerCluster.clearMarkers();
				  }         
         }
         $("#gmapSearchLoading").hide();        
      }
    });

}

$(document).ready(function(){
  $("#edit-properties-detached").click();
  $("#edit-properties-multiplex").click();
  $("#edit-properties-townhomes").click();
  $("#edit-properties-condos").click();
  $("#edit-properties-other").click();  
  $("#gmapSearchPrevious").hide();
  $("#rentprice").hide();
  
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(defaultLatitude, defaultLongtitude), defaultZoom);
    map.setUIToDefault();
    map.disableScrollWheelZoom();
    var options = {
      onGenerateMarkerHtmlCallback: function() { map.closeInfoWindow();},
      onMarkersSetCallback: function() { map.closeInfoWindow();}
    };
  
    map.addControl(new google.maps.LocalSearch(options));
    
    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 15 };
    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-saleprice-minprice").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();        
    });
    $("#edit-saleprice-maxprice").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();

    });
    
    $("#edit-rentprice-minprice").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();        
    });
    $("#edit-rentprice-maxprice").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();

    });
    
    
    $("#edit-properties-detached").change(function(){
      gmsLoadMapList(0,"TRUE");
      gmsLoadPropertiesList();
    }); 
        
    $("#edit-properties-multiplex").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;
      if(curListPage == 1){
        $("#gmapSearchPrevious").show();
      }
      gmsLoadPropertiesList();

      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);
    });
  }
});




