﻿/*
// Copyright 2007, Google Inc.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Sets up google.gears.*, which is *the only* supported way to access Gears.
//
// Circumvent this file at your own risk!
//
// In the future, Gears may automatically define google.gears.* without this
// file. Gears may use these objects to transparently fix bugs and compatibility
// issues. Applications that use the code below will continue to work seamlessly
// when that happens.
*/

(function() {
  if (window.google && google.gears) {
    return;
  }

  var factory = null;

  // Firefox
  if (typeof GearsFactory != 'undefined') {
    factory = new GearsFactory();
  } else {
    // IE
    try {
      factory = new ActiveXObject('Gears.Factory');
      // privateSetGlobalObject is only required and supported on IE Mobile on
      // WinCE.
      if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
        factory.privateSetGlobalObject(this);
      }
    } catch (e) {
      // Safari
      if ((typeof navigator.mimeTypes != 'undefined')
           && navigator.mimeTypes["application/x-googlegears"]) {
        factory = document.createElement("object");
        factory.style.display = "none";
        factory.width = 0;
        factory.height = 0;
        factory.type = "application/x-googlegears";
        document.documentElement.appendChild(factory);
      }
    }
  }


  if (!factory) {
    return;
  }

  if (!window.google) {
    google = {};
  }

  if (!google.gears) {
    google.gears = {factory: factory};
  }
})();


function GoogleMapSearchNearByObject(){
    var map;
    var oldCircleOverlay;
    var oldMarker;
    var isClearFooter = false;

    this.MapControlID = null;
    this.Radius = 2*0.46; // default 2km
    this.RootURL;
    this.RestaurantDataOnMap;

    this.Initialize = function() {
        if (GBrowserIsCompatible()) {
            oldCircleOverlay = new Array();
            oldMarker = new Array();

            this.RestaurantDataOnMap = new Array();

            $('#' + this.MapControlID).show();

            // Tạo bản đồ    			
            map = new GMap2(document.getElementById(this.MapControlID));
            map.addControl(new GLargeMapControl());
            this.getUserLocation(this.SetPosition);
        }
    };

    var markerCenter;

    this.Abc = function() {
        map.setCenter(markerCenter.getPoint(), 14);
        var point = markerCenter.getPoint();
        searchNearByObject.eraseCircles();
        searchNearByObject.drawCircle(point, searchNearByObject.Radius, '#C51200', 1, 0.5);
        map.clearOverlays();
        map.addOverlay(markerCenter);
        searchNearByObject.drawCircle(point, searchNearByObject.Radius, '#C51200', 1, 1.0);
    }
    this.SetPosition = function(point) {
        map.setCenter(point, 14);
        markerCenter = new GMarker(point, { draggable: true });

        GEvent.addListener(markerCenter, "dragstart", function() { });


        GEvent.addListener(markerCenter, "dragend", function(overlay, point) {
            searchNearByObject.eraseCircles();
            searchNearByObject.drawCircle(this.getPoint(), searchNearByObject.Radius, '#C51200', 1, 0.5);
        });

        map.clearOverlays();
        map.addOverlay(markerCenter);

        searchNearByObject.drawCircle(point, searchNearByObject.Radius, '#C51200', 1, 1.0);
    }

    this.SetMarkerCenter = function()
    {
        map.setCenter(markerCenter.getPoint(), 14);
    }

    this.drawCircle = function(center, radius, color, thickness, opacity) {
        //Function created by Chris Haas
        var circleQuality = 1; 		//1 is best but more points, 5 looks pretty good, too
        var M = Math.PI / 180; 		//Create Radian conversion constant

        var points = []; 						//Init Point Array
        /*
        //Loop through all degrees from 0 to 360
        for (var i = 0; i < 360; i += circleQuality) {
            var P = new GLatLng(
			    center.lat() + ((radius + 0.2) * Math.sin(i * M)) / 111.2,
			    center.lng() + ((radius + 0.25) * Math.cos(i * M)) / 111.2// * circleSquish
			);
            points.push(P);
        }
        */
        var lat = center.lat();
        var lng = center.lng();
        var d2r = Math.PI / 180;                // degrees to radians
        var r2d = 180 / Math.PI;                // radians to degrees
        var Clat = (radius / 3963) * r2d;      //  using 3963 as earth's radius
        var Clng = Clat / Math.cos(lat * d2r);

        //Add each point in the circle
        for (var i = 0; i < 360; i++) {
            var theta = Math.PI * (i / 180);
            Cx = lng + (Clng * Math.cos(theta));
            Cy = lat + (Clat * Math.sin(theta));
            points.push(new GLatLng(Cy, Cx));
        }
        points.push(points[0]); // close the circle

        var p = new GPolygon(points, color, thickness, opacity, '#DE7663', 0.5)

        map.addOverlay(p);

        setTimeout("searchNearByObject.SetMarkerCenter()", 1000);

        if (!isClearFooter) {
            setTimeout("searchNearByObject.clearFooter()", 1000);
        }

        ///alert('y');
        searchNearByObject.searchNearby(center.lat(), center.lng(), radius);

        oldCircleOverlay.push(p);
    }
    
    this.eraseCircles = function() {
	    if(oldCircleOverlay) {
		    for (var i = 0; i < oldCircleOverlay.length; i++) {
			    map.removeOverlay(oldCircleOverlay[i]);
		    }
		    oldCircleOverlay = new Array();
	    }
    }

    this.getUserLocation = function(successCallback) {
        if (window.google && google.gears) {
            var geo = google.gears.factory.create('beta.geolocation');

            geo.getCurrentPosition(function(position) {
                if (GBrowserIsCompatible()) {
                    var point = new GLatLng(position.latitude, position.longitude);

                    successCallback(point);
                }
            }
								    , function(positionError) { });
        }
        else if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                if (GBrowserIsCompatible()) {

                    var point = new GLatLng(position.coords.latitude, position.coords.longitude);

                    successCallback(point);
                }
            }
												    , function(positionError) { });
        }
    }
    this.clearFooter = function()
	{
		if($("span",$('#' + this.MapControlID)).length > 0)
		{		    
			$("span",$('#' + this.MapControlID)).each(function(){
				if($(this).html().match("Europa Technologies"))
				{
					$(this).html("");
					
					isClearFooter = true;
				}
			});
		}
	}

	this.searchNearby = function (lat, lng, radius) {
	    $.post(this.RootURL + "/ajax/SearchList.aspx"
                , {
                    act: "searchNearby"
                    , lat: lat
                    , lng: lng
                    , radius: radius
                }
                , function (dat) {

                    var data = dat.getElementsByTagName("Restaurant");

                    if (data.length > 0) {
                        removesOldRestaurantMarker();

                        $('#search-near-by-infor-zone-list').html('');

                        for (i = 0; i < data.length; i++) {
                            map.addOverlay(SetRestaurantMarker(data[i], i + 1));
                        }
                        $('#more-result').show();
                    }
                    else {
                        removesOldRestaurantMarker();

                        $('#search-near-by-infor-zone-list').html('');
                        $('#more-result').hide();
                    }
                });
	}
	
	this.CloseInformation = function(index)
	{        
        //oldMarker[index].closeInfoWindow();
	}

    function SetRestaurantMarker(item, stt)
    {    
        var lat = item.childNodes[5].childNodes[0].nodeValue;
        var lng = item.childNodes[6].childNodes[0].nodeValue;
        
        var point = new GLatLng(lat,lng);
        var marker = new GMarker(point, new GIcon(G_DEFAULT_ICON,"./media/img/marker/" + stt + ".png"));
        
        var data = {
                         markerPoint:point
                        ,logo: searchNearByObject.RootURL + item.childNodes[4].childNodes[0].nodeValue
                        ,originalLogo: item.childNodes[4].childNodes[0].nodeValue
                        ,name: item.childNodes[2].childNodes[0].nodeValue
                        ,address: item.childNodes[3].childNodes[0].nodeValue
                        ,url: 'http://nhahang.quanhta.vn' + '/' + item.childNodes[1].childNodes[0].nodeValue + '/' + item.childNodes[7].childNodes[0].nodeValue
                     };
        $('#search-near-by-infor-zone-list').append('<li onmouseover="searchNearByObject.ShowInformation(' + (stt - 1) + ')" onmouseout="searchNearByObject.CloseInformation(' + (stt - 1) + ')" ><div class="near-by-infor-header"><span class="order"><img alt="na" src="media/img/marker/'+stt+'.png" />' + '</span><span class="title"><a href="' + data.url + '">' + data.name + '</a></span></div><div class="clearer"></div></li>');                   
        searchNearByObject.RestaurantDataOnMap.push(data);
        
        GEvent.addListener(marker, "mouseover", function(latlng) {
                                                            
                                                            for (i = 0; i < searchNearByObject.RestaurantDataOnMap.length; i++)
                                                            {
                                                                var temp = searchNearByObject.RestaurantDataOnMap[i];
                                                                
                                                                if (temp.markerPoint.lat() == latlng.lat() && temp.markerPoint.lng() == latlng.lng())
                                                                {
                                                                    temp = searchNearByObject.RestaurantDataOnMap[i];
                                                                    
                                                                    var infor = '<table border="0" width="200px">'
                                                                        +       '<tr>'
                                                                        +           '<td><b>' + temp.name + '</b></td>'
                                                                        +       '</tr>'
                                                                        +       '<tr>'
                                                                        +           '<td>' + temp.address + '</td>'
                                                                        +       '</tr>'
                                                                        +   '</table>'
                                                                
                                                                
																	//marker.openInfoWindowHtml(infor);
                                                                }
                                                            }
														});
		GEvent.addListener(marker, "mouseout", function() {
								marker.closeInfoWindow();
							});
        
        oldMarker.push(marker);
        
        return marker;
    }
    
    function removesOldRestaurantMarker() 
    {
	    if(oldMarker) {
		    for (var i = 0; i < oldMarker.length; i++) {
			    map.removeOverlay(oldMarker[i]);
		    }
		    
		    searchNearByObject.RestaurantDataOnMap = new Array();
		    oldMarker = new Array();
	    }
    }

}


