﻿// Static
// Ernest 5 Dec 2009

var MyMap = new function()
{
   var fnname = null;
   var map = null;
   var locationlist = null;
   var images = null;
   var allowedBounds = null;
//   var map = new GMap2(document.getElementById("map"));
//   The allowed region which the whole map must be within
//   var allowedBounds = new GLatLngBounds(new GLatLng(22.140348,113.818359), new GLatLng(22.570268,114.419174 ));
   var longitude = null;
   var lat = null;
   var zoom = null;
   var chosen = null;
   var bound = null;
   var ajaxRequest = null;
   var waiter = null;
   var inOrganize = false;
   var locationid = -1;
   var hotspotcountdiv = null;
/* ***   Function createMarker     **** */
   this.createMarker = function(point,html) 
   {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        return marker;
   } // end function
/* ***   Function goDistrict **** */
   this.goDistrict = function(districtid, longitude, lat, zoom) 
   {
      this.goLocation(longitude, lat, zoom);
      new Ajax.Request('getareas.php', {
	  method: 'post',
	  parameters: {
		districtid: districtid
 	  }, // end parameters
	  onComplete: function(x) {
	 	MyMap.getAreasDone(x);
	  } // end onComplete
        } // end
      ) // end Ajax.Request 
   } // end function
/* ***   Function listDistrict **** */
   this.listDistricts = function() {
      new Ajax.Request('getdistricts.php', {
	  method: 'post',
	  parameters: {
 	  }, // end parameters
	  onComplete: function(x) {
	 	MyMap.getDistrictsDone(x);
	  } // end onComplete
        } // end
      ) // end Ajax.Request 
   } // end function listDistricts
/* ***   Function this.getDistrictsDone  **** */
   this.getDistrictsDone = function(x) {
      var obj = this.parseJSON(x);
      if (obj.rsp=='fail') {
	alert('fail');
        $('directories').innerHTML = 'fail';
        return;
      }
      var data = obj.data;
      var count = data.count;
      var txt = '<ul>';
      for (var i=0; i < count; i++) {
	var dist = data.districts[i];
	txt += '<li style="cursor: pointer;" onclick="MyMap.goDistrict(' + dist.districtid + ', ' + dist.longitude + ', ' + dist.latitude + ', ' + dist.zoom + ')">' + dist.district + '</li>';
      } // end for
	$('directories').innerHTML = txt + '</ul>';
   } // end getDistrictsDone
   this.getAreasDone = function(x) {
      var obj = this.parseJSON(x);
      if (obj.rsp=='fail') {
	alert('fail');
        $('directories').innerHTML = 'fail';
        return;
      }
      var data = obj.data;
      var count = data.count;
      var txt = '<ul><li style="cursor: pointer;" onclick="MyMap.listDistricts()">[' + txtbacktotop + ']';
      for (var i=0; i < count; i++) {
	var dist = data.districts[i];
	txt += '<li style="cursor: pointer;" onclick="MyMap.goLocation(' + dist.longitude + ', ' + dist.latitude + ', ' + dist.zoom + ')">' + dist.district + '</li>';
      } // end for
	$('directories').innerHTML = txt + '</ul>';
   } // end function


/* ***   Function this.goLocation **** */
   this.goLocation = function(longitude, lat, zoom) 
   {
        this.map.setZoom(zoom);
        this.map.panTo(new GLatLng(lat, longitude));
        this.boundChanged();
   } // end function

/* ***   Function this.showMap **** */
   this.showMap = function()  
   {  
     if (GBrowserIsCompatible()) {
      // ====== Restricting the range of Zoom Levels =====
      // Get the list of map types      
      var mt = this.map.getMapTypes();
      // Overwrite the getMinimumResolution() and getMaximumResolution() methods
      for (var i=0; i<mt.length; i++) {
        mt[i].getMinimumResolution = function() {return 10;}
        mt[i].getMaximumResolution = function() {return 18;}
      } // end for
      this.map.addControl(new GLargeMapControl());
      this.map.addControl(new GMapTypeControl());
      this.map.setCenter(new GLatLng(22.366220, 114.125620), 10);
      GEvent.addListener(this.map, "moveend", function() {
	MyMap.moveEnd();
        }
      );
      GEvent.addListener(this.map, "zoomend", function(oldLevel, newLevel) {
	MyMap.zoomEnd(oldLevel, newLevel);
        }
      );
      GEvent.addListener(this.map, "click", function(overlay, point) {
        MyMap.clicked(overlay, point);
	}
      );
      // Add a move listener to restrict the bounds range
      GEvent.addListener(this.map, "move", function() { MyMap.checkBounds(); });
      }
      else {
          alert("Sorry, the Google Maps API is not compatible with this browser");
      } // end else
   } // end function showMap
	
   this.moveEnd = function() {
      this.boundChanged();
   } // end function moveEnd

   this.zoomEnd = function(oldLevel, newLevel) {
      this.bound = this.map.getBounds();
      /* alert('New Zoom: ' + 
	MyMap.bound.getNorthEast().lat() + ', ' + 
	MyMap.bound.getNorthEast().lng() + ', ' + 
	MyMap.bound.getSouthWest().lat() + ', ' + 
	MyMap.bound.getSouthWest().lng() );
	*/
/* Ernest 7 Oct 2008 */
	  MyMap.zoom = MyMap.map.getZoom();
// $('point').innerHTML = 'Zoom level: ' + MyMap.zoom;
     this.boundChanged();

   } // end function zoomEnd
   // Clicked
   this.clicked = function(overlay, point) {
	MyMap.map.clearOverlays();
	if (point) {
	  // MyMap.map.addOverlay(new GMarker(point));
	  MyMap.chosen = true;
	  MyMap.longitude = point.lng();
	  MyMap.lat = point.lat();
	  MyMap.zoom = MyMap.map.getZoom();
          MyMap.map.setZoom(MyMap.zoom + 1);
	  MyMap.map.panTo(point);
          MyMap.bound = MyMap.map.getBounds();
          this.boundChanged();
          
        }
   }  // end function clicked

   // If the map position is out of range, move it back
   this.checkBounds = function() {
   // Perform the check and return if OK
     if (this.allowedBounds.contains(this.map.getCenter())) {
        return;
     }
     // It`s not OK, so find the nearest allowed point and move there
     var C = this.map.getCenter();
     var X = C.lng();
     var Y = C.lat();

     var AmaxX = this.allowedBounds.getNorthEast().lng();
     var AmaxY = this.allowedBounds.getNorthEast().lat();
     var AminX = this.allowedBounds.getSouthWest().lng();
     var AminY = this.allowedBounds.getSouthWest().lat();

     if (X < AminX) {X = AminX;}
     if (X > AmaxX) {X = AmaxX;}
     if (Y < AminY) {Y = AminY;}
     if (Y > AmaxY) {Y = AmaxY;}
     //alert ("Restricting "+Y+" "+X);
     this.map.setCenter(new GLatLng(Y,X));
     this.bound = this.map.getBounds();
     if (MyMap.inOrganize) {
       this.boundChanged();
     }
   } // end function checkBounds

  this.boundChanged = function() {
    if (waiter == null) {
	waiter = setTimeout(this.performBoundChanged, 1800);
    } else {
	clearTimeout(waiter);
	waiter = setTimeout(this.performBoundChanged, 1800);
    } // end if
  } // end function boundChanged

  this.showLoader = function(id) {
     $(id).style.display = 'block';
     $(id).innerHTML = '<span style="padding:10px; margin:10px; text-align:center;"><img src="../images/loader4.gif"/>' + txtpleasewait + '</span>';
  } // end showLoader
  this.hideLoader = function(id) {
     $(id).style.display = 'none';
     $(id).innerHTML = '';
  }
  this.performBoundChanged = function() {
	// alert('performBoundChanged');
        this.waiter = null;
        this.bound = MyMap.map.getBounds();
	var obj = this;
        var neLat = this.bound.getNorthEast().lat();
	var neLng = this.bound.getNorthEast().lng();
	var swLat = this.bound.getSouthWest().lat();
	var swLng = this.bound.getSouthWest().lng();

	if (this.map.getZoom() < 16) {	// Don't overcrowd the map with points
	  new Ajax.Request('gethotspotcount.php', {
	    method: 'post',
	    parameters: {
		nelat: neLat,
		nelng: neLng,
		swlat: swLat,
		swlng: swLng
          },
          onComplete: function(x) {
		MyMap.getHotspotsCountDone(x);
	  }
	 } )
	  return; 
	}  

        MyMap.showLoader('overlay');
        new Ajax.Request('gethotspots.php', {
	  method: 'post',
	  parameters: {
		nelat: neLat,
		nelng: neLng,
		swlat: swLat,
		swlng: swLng
          },
          onComplete: function(x) {
		MyMap.getHotspotsDone(x);
	  }
         }
	)
  } // end function performBoundChanged
  this.getHotspotsCountDone = function(x) {
     var obj = this.parseJSON(x);
     if (obj.rsp=="fail") {
	// $('images').innerHTML = 'fail';
        return;
     }
     var data = obj.data;
     var count = data.count;
     $('hscount').innerHTML = data.count;
     if (data.count > 0) {
       $('msg2').innerHTML = txtzoomin;
     } else {
       $('msg2').innerHTML = '';
     }
  }
  this.getHotspotsDone = function(x) {
     MyMap.hideLoader('overlay');
     var obj = this.parseJSON(x);
     if (obj.rsp=="fail") {
	// $('images').innerHTML = 'fail';
        return;
     }
// alert('in this.getHotspotsDone ');
     var txt = '';
     var data = obj.data;
     var count = data.count;
     this.map.clearOverlays();
     for (var i = 0; i <count; i++) {
       var hotspot = data.hotspots[i];
	var lng = hotspot.longitude;
	var lat = hotspot.latitude;
	var loc = hotspot.location;
	var addr = hotspot.address;
	var type = hotspot.type;
	var point = new GPoint(lng, lat);
	var customIcon = new GIcon(G_DEFAULT_ICON);
	if (type=='Phonebooth') {
	  customIcon.image = "http://wifi.webit.com.hk/images/phonebooth.gif";
	}
	else if (type=='Starbucks') {
	  customIcon.image = "http://wifi.webit.com.hk/images/starbucks.gif";
	}
	else if (type=='Broadway') {
	  customIcon.image = "http://wifi.webit.com.hk/images/broadway.gif";
	}
	else if (type=='Cafe de Coral') {
	  customIcon.image = "http://wifi.webit.com.hk/images/cafedecoral.gif";
	}
	else if (type=="city'super") {
	  customIcon.image = "http://wifi.webit.com.hk/images/citysuper.gif";
	}
	else if (type=='Delifrance') {
	  customIcon.image = "http://wifi.webit.com.hk/images/delifrance.gif";
	}
	else if (type=='7-eleven') {
	  customIcon.image = "http://wifi.webit.com.hk/images/seveneleven.gif";
	}
	else if (type=='OK') {
	  customIcon.image = "http://wifi.webit.com.hk/images/ok.gif";
	}
	else if (type=='KFC') {
	  customIcon.image = "http://wifi.webit.com.hk/images/kfc.gif";
	}
	else if (type=='Maxims MX') {
	  customIcon.image = "http://wifi.webit.com.hk/images/maximmx.gif";
	}
	else if (type=='Midland - Hong Kong Property') {
	  customIcon.image = "http://wifi.webit.com.hk/images/midland.gif";
	}
	else if (type=='MTRC') {
	  customIcon.image = "http://wifi.webit.com.hk/images/mtr.gif";
	}
	else if (type=="Oliver's Super Sandwiches") {
	  customIcon.image = "http://wifi.webit.com.hk/images/oliver.gif";
	}
	else if (type=='Pacific Coffee') {
	  customIcon.image = "http://wifi.webit.com.hk/images/pacificcoffee.gif";
	}
	else if (type=='HK Jockey Club - OCB') {
	  customIcon.image = "http://wifi.webit.com.hk/images/hkjc.gif";
	}
	else if (type=='HK Jockey Club - Race Course') {
	  customIcon.image = "http://wifi.webit.com.hk/images/hkjc.gif";
	}
	else if (type=='UA Cinema') {
	  customIcon.image = "http://wifi.webit.com.hk/images/uacinema.gif";
	}
	else if (type=='egov') {
	  customIcon.image = "http://wifi.webit.com.hk/images/egov.gif";
	}
	else if (type=='y5zone') {
	  customIcon.image = "http://wifi.webit.com.hk/images/y5zone.gif";
	}
	else {
	  customIcon.image = "http://wifi.webit.com.hk/images/wifi.gif";
	}
	customIcon.iconSize =  new GSize(36, 36);
	// markerOptions = { icon:customIcon, title:loc};
	markerOptions = { icon:customIcon };
	// markerOptions.icon = customIcon;
	markerOptions.title = loc + addr;
	this.map.addOverlay(new GMarker(point, markerOptions));


     }  // end for
	$('hscount').innerHTML = data.count;
	if (data.count > 0) {
	  $('msg2').innerHTML = txtzoomin;
	} else {
	  $('msg2').innerHTML = '';
	}
  }  // end function this.getHotspotsDone 
  
  this.getLocationsDone = function(x) {
     MyMap.hideLoader('locationlist');
     var obj = this.parseJSON(x);
     if (obj.rsp=="fail") {
	$('locationlist').innerHTML = 'fail';
        return;
     }
     var txt = '';
     var data = obj.data;
     var count = data.count;
     for (var i = 0; i <count; i++) {
       var loc = data.locations[i];
       txt += '<span id="loc-' + i + '" style="cursor: pointer;"' +
           ' onmouseout=""' +
           ' onmouseover="javascript:MyMap.showMarker(' + loc.longitude + ', ' +
               loc.latitude + ')" ' +
           ' onclick="javascript:{ MyMap.goLocation(' +  loc.longitude + ', ' + loc.latitude + ', ' + loc.zoom + '); MyMap.addLocation(' + loc.locationid + ', \'' + loc.location + '\');}">' + 
	   loc.location + '&nbsp; </span>';
     }  // end for
     $('locationlist').innerHTML = txt;
  }  // end functio getLocationsDone

  this.parseJSON = function(x) {
    var obj = eval('(' + x.responseText + ')');
    return obj;
  } // end parseJSON

  this.showMarker = function(lng, lat) {
	var point = new GPoint(lng, lat);
	this.map.clearOverlays();
	this.map.addOverlay(new GMarker(point));
  } // end showMarker

  this.removeMarker = function() {
     this.map.clearOverlays();
  } // end removeMarker

  this.showMapAt = function(lng, lat, zoom) {
    MyMap.inOrganize = false;
    if (GBrowserIsCompatible()) {
      var mt = this.map.getMapTypes();
      // Overwrite the getMinimumResolution() and getMaximumResolution() methods
      for (var i=0; i<mt.length; i++) {
        mt[i].getMinimumResolution = function() {return 10;}
        mt[i].getMaximumResolution = function() {return 18;}
      } // end for
      this.map.addControl(new GLargeMapControl());
      this.map.addControl(new GMapTypeControl());
      this.map.setCenter(new GLatLng(lat, lng), zoom); 
      this.map.setMapType(G_HYBRID_MAP);
      this.map.clearOverlays();
      this.map.addOverlay(new GMarker(new GPoint(lng, lat)));
//      GEvent.addListener(this.map, "move", function() { MyMap.checkBounds(); });
    } else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    } // end if 
  } // end showMapAt 
} // end MyMap


