var map, route;
// support multiple google map start
var multipleMaps = [];
// support multiple google map end
var points = [];
var mtr = [];
var landmark = [];
var properties = [];
var gmarkers = [];
var hotelCities = [];

var maxZoomLevel = 15;
var count =0;
var stopClick = false;
var stationGroups = {};
var landmarkGroups = {};
var fresh='';
var progressBar;
var markerClusterer = null;
var windowTip=null;
      var styles = [[{
        url: '../images/people35.png',
        height: 35,
        width: 35,
        opt_anchor: [16, 0],
        opt_textColor: '#FF00FF'
      },
      {
        url: '../images/people45.png',
        height: 45,
        width: 45,
        opt_anchor: [24, 0],
        opt_textColor: '#FF0000'
      },
      {
        url: '../images/people55.png',
        height: 55,
        width: 55,
        opt_anchor: [32, 0]
      }],
      [{
        url: '../images/conv30.png',
        height: 27,
        width: 30,
        anchor: [3, 0],
        textColor: '#FF00FF'
      },
      {
        url: '../images/conv40.png', 
        height: 36,
        width: 40,
        opt_anchor: [6, 0],
        opt_textColor: '#FF0000'
      },
      {
        url: '../images/conv50.png',
        width: 50,
        height: 45,
        opt_anchor: [8, 0]
      }],
      [{
        url: '../images/heart30.png',
        height: 26,
        width: 30,
        opt_anchor: [4, 0],
        opt_textColor: '#FF00FF'
      },
      {
        url: '../images/heart40.png', 
        height: 35,
        width: 40,
        opt_anchor: [8, 0],
        opt_textColor: '#FF0000'
      },
      {
        url: '../images/heart50.png',
        width: 50,
        height: 44,
        opt_anchor: [12, 0]
      }]];
var images = [
	"templates/images/markers/marker0.png",
	"templates/images/markers/marker1.png",
	"templates/images/markers/marker2.png",
	"templates/images/markers/marker3.png",
	"templates/images/markers/marker4.png",
	"templates/images/markers/marker5.png",
	"templates/images/markers/marker6.png",
	"templates/images/markers/marker7.png",
	"templates/images/markers/marker8.png",
	"templates/images/markers/marker9.png",
	"templates/images/markers/marker10.png",
	"templates/images/markers/marker11.png",
	"templates/images/markers/marker12.png",
	"templates/images/markers/marker13.png",
	"templates/images/markers/marker14.png",
	"templates/images/markers/marker15.png",
	"templates/images/markers/marker16.png",
	"templates/images/markers/marker17.png",
	"templates/images/markers/marker18.png",
	"templates/images/markers/marker19.png",
	"templates/images/markers/marker20.png",
	"templates/images/markers/marker21.png",
	"templates/images/markers/marker22.png",
	"templates/images/markers/marker23.png",
	"templates/images/markers/marker24.png",
	"templates/images/markers/marker25.png",
	"templates/images/markers/marker26.png",
	"templates/images/markers/marker27.png",
	"templates/images/markers/marker28.png",
	"templates/images/markers/marker29.png",
	"templates/images/markers/marker30.png",
	"templates/images/markers/marker31.png",
	"templates/images/markers/marker32.png",
	"templates/images/markers/marker33.png",
	"templates/images/markers/marker34.png",
	"templates/images/markers/marker35.png",
 	"templates/images/markers/marker36.png",
	"templates/images/markers/marker37.png",
	"templates/images/markers/marker38.png",
	"templates/images/markers/marker39.png",
	"templates/images/markers/marker40.png",
	"templates/images/markers/marker40.png",
	"templates/images/markers/marker41.png",
	"templates/images/markers/marker42.png",
	"templates/images/markers/marker43.png",
	"templates/images/markers/marker44.png",
	"templates/images/markers/marker45.png",
	"templates/images/markers/marker46.png",
	"templates/images/markers/marker47.png",
	"templates/images/markers/marker48.png",
	"templates/images/markers/marker49.png",
	"templates/images/markers/marker50.png",
	"templates/images/markers/marker51.png",
	"templates/images/markers/marker52.png",
	"templates/images/markers/marker53.png",
	"templates/images/markers/marker54.png",
	"templates/images/markers/marker55.png",
	"templates/images/markers/marker56.png",
	"templates/images/markers/marker57.png",
	"templates/images/markers/marker58.png",
	"templates/images/markers/marker59.png",
	"templates/images/markers/marker60.png",
	"templates/images/markers/marker61.png",
	"templates/images/markers/marker62.png",
	"templates/images/markers/marker63.png",
	"templates/images/markers/marker64.png",
	"templates/images/markers/marker65.png",
	"templates/images/markers/marker66.png",
	"templates/images/markers/marker67.png",
	"templates/images/markers/marker68.png",
	"templates/images/markers/marker69.png",
	"templates/images/markers/marker70.png",
	"templates/images/markers/marker71.png",
	"templates/images/markers/marker72.png",
	"templates/images/markers/marker73.png",
	"templates/images/markers/marker74.png",
	"templates/images/markers/marker75.png",
	"templates/images/markers/marker76.png",
	"templates/images/markers/marker77.png",
	"templates/images/markers/marker78.png",
	"templates/images/markers/marker79.png"
];

	function togglemap(obj,id) {	
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+365);
		// support multiple hotel start
		if ( (typeof(id) == "undefined") || (id == null) ) {
			id = '';
		}
		// support multiple hotel end
		
		mapId = 'map'+id;
		if(obj=="1") {
			fresh=obj;
			document.getElementById(mapId).style.display='none';		
			document.getElementById('openmap'+id).style.display='';	
			//setcookies('/','googleMapStatus','false','','none');	
		} else {		
			document.getElementById(mapId).style.display='';
			if(window.GMap2!='undefined'&&document.getElementById("GoogleMapComponent"+id)) {			
				onload_google(id);
			}
			//setcookies('/','googleMapStatus','true','','none');	
		}
	}

	function onload_google(id) {	
		//if(fresh!="1") {
			buildMap(id);
			//loadAllHotels();
			loadCityLandmark();
			window.onunload=GUnload;
		//}
	}

	function initialize(){
		if (GBrowserIsCompatible())  {
			var bounds = new GLatLngBounds();
			var map = new GMap2(document.getElementById("map_canvas"));
			map.setCenter(new GLatLng(22.38944415548136,114.1204833984375),10);
			map.addControl(new GMapTypeControl());
			var customUI=map.getDefaultUI();
			// Remove MapType.G_HYBRID_MAP
			customUI.maptypes.hybrid = false;
			map.setUI(customUI);
			GDownloadUrl("/include/HotelCityList.xml", function(data, responseCode) {  
				if (responseCode == "200") {
					var baseIcon = new GIcon(G_DEFAULT_ICON);
					baseIcon.image = "templates/images/markers/hotel.png";
					baseIcon.iconSize = new GSize(20, 23);
					baseIcon.shadowSize = new GSize(0, 0);
					baseIcon.iconAnchor = new GPoint(0, 0);
					markerOptions = { icon:baseIcon };

					var xml = GXml.parse(data);  
					var City = xml.documentElement.getElementsByTagName("City"); 

					var j = 0;
					var increment = 1;
					for (var i = 0; i < City.length; i++) {    
						var point = new GLatLng(parseFloat(City[i].getAttribute("Latitude")),parseFloat(City[i].getAttribute("Longitude")));   
					
						var code = City[i].getAttribute("Code");
						if (googlemapLang == "SC"){
							var name = City[i].getElementsByTagName("NameSC");
						}else if (googlemapLang == "TC"){
							var name = City[i].getElementsByTagName("NameTC");
						}else{
							var name = City[i].getElementsByTagName("NameEN");
						}

						markerOptions = { icon:baseIcon };

						hotelCities[i] = new GMarker(point,markerOptions);		
						bounds.extend(hotelCities[i].getPoint());
						hotelCities[i]["Code"] = code;
						hotelCities[i]["Name"] = name.item(0).firstChild.nodeValue;
						addClickevent(hotelCities[i],"hotel");
						map.addOverlay(hotelCities[i]);  
					}
					bestFit(map, bounds);
				}
			});
		}
	}  

	function foundNearByHotel(lat,lng) {
		var currentLocation = new GLatLng(parseFloat(lat),parseFloat(lng));  
		var northEast = EOffsetBearing(currentLocation,  1000,  45); 
		var southWest = EOffsetBearing(currentLocation,  1000,  225); 
		document.getElementById('NELatitude').value = northEast.lat();
		document.getElementById('NELongitude').value = northEast.lng();
		document.getElementById('SWLatitude').value =  southWest.lat();
		document.getElementById('SWLongitude').value =  southWest.lng();
		var northEastMarker = new GMarker(northEast);
		var southWestMarker = new GMarker(southWest);
		//map.addOverlay(northEastMarker);  
		//map.addOverlay(southWestMarker);  

		submitIt('3');

	}
	
	function refreshMap() {
		if (markerClusterer != null) {
			markerClusterer.clearMarkers();
		}
		var zoom = parseInt(-1, 10);
		var size = parseInt(-1, 10);
		var style =-1;
		zoom = zoom == -1 ? null : zoom;
		size = size == -1 ? null : size;
		style = style == "-1" ? null: parseInt(style, 10);
		markerClusterer = new MarkerClusterer(map, properties, {maxZoom: zoom, gridSize: size, styles: styles[style]});
	}

	function loadAllHotels() {
		GDownloadUrl("/include/HotelList/"+document.regform.city.value+".xml", function(data, responseCode) {  
			if (responseCode == "200") {							
				var baseIcon = new GIcon(G_DEFAULT_ICON);
				baseIcon.image = "templates/images/markers/hotel.png";
				baseIcon.iconSize = new GSize(20, 23);
				baseIcon.shadowSize = new GSize(0, 0);
				baseIcon.iconAnchor = new GPoint(0, 0);
				markerOptions = { icon:baseIcon };

				var xml = GXml.parse(data);  
				var markers = xml.documentElement.getElementsByTagName("Property"); 
				var j = 0;
				var increment = 1;
				for (var i = 0; i < markers.length; i++) {    
					if (markers[i].getAttribute("lat") != "" && markers[i].getAttribute("lng") != "") {
						var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));  
						var code = markers[i].getElementsByTagName("PropertyCode");
						var name = markers[i].getElementsByTagName("PropertyNameSC");
						var hotel = new GMarker(point,markerOptions);
						properties.push(hotel);
						hotel["Code"] = code.item(0).firstChild.nodeValue;
						hotel["Name"] = name.item(0).firstChild.nodeValue;

						/*for (var j = 0; j < mtr.length; j++) { 
							if (point.distanceFrom(mtr[j].getLatLng()) < 500) {
								stationGroups[mtr[j]["Route"]].push(hotel[i]);
							}
						}
						for (var j = 0; j < landmark.length; j++) { 
							if (point.distanceFrom(landmark[j].getLatLng()) < 500) {
								landmarkGroups[landmark[j]["Code"]].push(hotel[i]);
							}
						}*/
						//map.addOverlay(hotel[i]);  
						addClickevent(hotel,"hotel");
						//hotel[i].hide();
					}
				}
				refreshMap();
			}
		});
	}

	function loadCitySubway() {
		GDownloadUrl("/include/CitySubway/"+document.regform.city.value+".xml", function(data, responseCode) {  
			if (responseCode == "200") {					
				var baseIcon = new GIcon(G_DEFAULT_ICON);
				baseIcon.image = "templates/images/markers/train.png";
				baseIcon.iconSize = new GSize(20, 23);
				baseIcon.shadowSize = new GSize(0, 0);
				baseIcon.iconAnchor = new GPoint(0, 0);
				markerOptions = { icon:baseIcon };

				var xml = GXml.parse(data);  
				var station = xml.documentElement.getElementsByTagName("Station"); 

				var j = 0;
				var increment = 1;
				for (var i = 0; i < station.length; i++) {    
					var point = new GLatLng(parseFloat(station[i].getAttribute("lat")),parseFloat(station[i].getAttribute("lng")));    
					var route = station[i].getAttribute("Route");
					if (stationGroups[route] == null) {
						stationGroups[route] = [];
					}
					mtr[i] = new GMarker(point,markerOptions);		
					mtr[i]["Route"] = route;
					//map.addOverlay(mtr[i]);  
				}
				//var poly= new GPolyline(trackpoints, "#ff0000", 3, .5);
				//map.addOverlay(poly);
				//bestFit(map, bounds);
			}
		});
	}

	function loadCityLandmark() {
		if (document.regform.city.value == null || document.regform.city.value == ""){
			return;
		}
		GDownloadUrl("/include/CityLandmark/"+document.regform.city.value+".xml", function(data, responseCode) {  
			if (responseCode == "200") {	
				var xml = GXml.parse(data);  
				var scenery = xml.documentElement.getElementsByTagName("Scenery"); 

				var j = 0;
				var increment = 1;
				for (var i = 0; i < scenery.length; i++) {    
					var point = new GLatLng(parseFloat(scenery[i].getAttribute("latitude")),parseFloat(scenery[i].getAttribute("longitude")));   
					var code = scenery[i].getAttribute("code");
					var sceneryType = scenery[i].getAttribute("type");
					var nameNode = scenery[i].getElementsByTagName("Name");
					for (var k = 0; k < nameNode.length; k++) {    
						if (googlemapLang == nameNode[k].getAttribute("language")){
							if(nameNode[k].firstChild != null)
								var name = nameNode[k].firstChild.nodeValue;
							else
								var name = "";
						}
					}

					if (landmarkGroups[code] == null) {
						landmarkGroups[code] = [];
					}
					var baseIcon = new GIcon(G_DEFAULT_ICON);
					if (sceneryType == "Landmark"){
						baseIcon.image = "templates/images/markers/attraction.png";
					} else if (sceneryType == "Airport") {
						baseIcon.image = "templates/images/markers/airport.png";
					} else if (sceneryType == "Station") {
						baseIcon.image = "templates/images/markers/train.png";
					} else if (sceneryType == "Church") {
						baseIcon.image = "templates/images/markers/church.png";
					} else if (sceneryType == "Park") {
						baseIcon.image = "templates/images/markers/park.png";
					} else if (sceneryType == "Concert") {
						baseIcon.image = "templates/images/markers/event.png";						
					} else if (sceneryType == "SAP"){
                        baseIcon.image = "templates/images/markers/pin-blue.png";
                    } else {
						baseIcon.image = "templates/images/markers/attraction.png";
					}

					baseIcon.iconSize = new GSize(34, 55);
					baseIcon.shadowSize = new GSize(0, 0);
					baseIcon.iconAnchor = new GPoint(15, 55);
					markerOptions = { icon:baseIcon };

					landmark[i] = new GMarker(point,markerOptions);		
					landmark[i]["Code"] = code;
					landmark[i]["Name"] = name;
					addClickevent(landmark[i],"landmark");
					map.addOverlay(landmark[i]);  
				}
			}
		});
	}

	function loadHotelCity() {
		GDownloadUrl("/include/HotelCityList.xml", function(data, responseCode) {  
			if (responseCode == "200") {
				var baseIcon = new GIcon(G_DEFAULT_ICON);
				baseIcon.image = "templates/images/markers/hotel.png";
				baseIcon.iconSize = new GSize(20, 23);
				baseIcon.shadowSize = new GSize(0, 0);
				baseIcon.iconAnchor = new GPoint(0, 0);
				markerOptions = { icon:baseIcon };

				var xml = GXml.parse(data);  
				var City = xml.documentElement.getElementsByTagName("City"); 

				var j = 0;
				var increment = 1;
				for (var i = 0; i < City.length; i++) {    
					var point = new GLatLng(parseFloat(City[i].getAttribute("Latitude")),parseFloat(City[i].getAttribute("Longitude")));   
				
					var code = City[i].getAttribute("Code");
					if (googlemapLang == "SC"){
						var name = City[i].getElementsByTagName("NameSC");
					}else if (googlemapLang == "TC"){
						var name = City[i].getElementsByTagName("NameTC");
					}else{
						var name = City[i].getElementsByTagName("NameEN");
					}

					markerOptions = { icon:baseIcon };

					hotelCities[i] = new GMarker(point,markerOptions);		
					bounds.extend(hotelCities[i].getPoint());
					hotelCities[i]["Code"] = code;
					hotelCities[i]["Name"] = name.item(0).firstChild.nodeValue;
					addClickevent(hotelCities[i],"hotel");
					map.addOverlay(hotelCities[i]);  
				}
				bestFit(map, bounds);
			}
		});
	}

	function buildMap(id) {
		// support multiple hotel start
		if ( (typeof(id) == "undefined") || (id == null) ) {
			id = '';
		}
		// support multiple hotel end
		if(GBrowserIsCompatible()) {
			var bounds = new GLatLngBounds();
			if (document.getElementById("GoogleMapComponent"+id) != null) {
				map = new GMap2(document.getElementById("GoogleMapComponent"+id));
				map.setCenter(new GLatLng(22.38944415548136,114.1204833984375),2);
				map.addControl(new GMapTypeControl());
				map.enableKeyDragZoom(
					{	key: "shift", 
						boxStyle: {border: "thin dashed black", backgroundColor: "transparent", opacity: 1},
						paneStyle: { backgroundColor: "gray", opacity: 0.1 }
					}
				);
				var boundaries = new GLatLngBounds(new GLatLng(22.382377738524088,114.11574675802708), new GLatLng(22.428350969375863,114.16334100139117));
				//map.setMapType(G_HYBRID_MAP);
				var customUI=map.getDefaultUI();
				// Remove MapType.G_HYBRID_MAP
				customUI.maptypes.hybrid = false;
				map.setUI(customUI);

				GEvent.addListener(map, "zoomend", function() {
					zoom = map.getZoom();
				});

				var baseIcon = new GIcon(G_DEFAULT_ICON);
				baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
				baseIcon.iconSize = new GSize(21, 34);
				baseIcon.shadowSize = new GSize(37, 34);
				baseIcon.iconAnchor = new GPoint(24, 17);
				baseIcon.infoWindowAnchor = new GPoint(9, 2);
				var hotelURL = "/hotelSummary.php"
				
				// support multiple hotel start
				if (id != '') {
					hotelURL += "?hotelSearchResultID=" + id + "&";
				}
				// support multiple hotel end

				if (propertyID != "") {
					hotelURL += "?id=" + propertyID;
				} else {
					if(document.getElementById('googleScript')){
						var $isFavorite = document.getElementById('googleScript').getAttribute('isFavorite');
						if($isFavorite == "true"){
							hotelURL += "?isFavorite=" + $isFavorite;
						}
					}
				}
				GDownloadUrl(hotelURL, function(data, responseCode) {  
					if (responseCode == "200") {					
						var xml = GXml.parse(data);  
						var markers = xml.documentElement.getElementsByTagName("Property"); 
						var j = 0;
						var increment = 1;
						for (var i = 0; i < markers.length; i++) {    
							points[i] = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));  
							var letteredIcon = new GIcon(baseIcon);
							var imageID = i+1;
							if (markers.length == 1)
							{
								imageID = 0;
							}
							letteredIcon.image = "/templates/images/google/"+imageID+"_new.png" ;
							gmarkers[i] = new GMarker(points[i],{draggable:false, autoPan:false,icon:letteredIcon} );
							gmarkers[i]["ID"] = markers[i].getAttribute("code");
							bounds.extend(gmarkers[i].getPoint());
							addClickevent(gmarkers[i],"property");
							map.addOverlay(gmarkers[i]);
						}
						bestFit(map, bounds);
					}
				});
			} 
		}
		// support multiple google map start
		multipleMaps[id] = map;
		// support multiple google map end
	} 

	function addClickevent(marker,markerType) { // Add a click listener to the markers
		if (markerType == "property") {
			GEvent.addListener(marker, "click", function() {
				var maxContentDiv = document.createElement('div');
				GDownloadUrl("/showMapMessage.php?id="+marker["ID"], function(data) {
					maxContentDiv.innerHTML = data;
					marker.openInfoWindowHtml(maxContentDiv);
				});
			});
		} else if (markerType == "landmark") {
			GEvent.addListener(marker, "click", function() {
				var maxContentDiv = document.createElement('div');
				maxContentDiv.innerHTML = marker["Name"];
				marker.openInfoWindowHtml(maxContentDiv);
			});
		} else if (markerType == "hotel") {
			GEvent.addListener(marker, "click", function() {
				var maxContentDiv = document.createElement('div');
				maxContentDiv.innerHTML = marker["Name"];
				marker.openInfoWindowHtml(maxContentDiv);
			});
		}
		return marker;
	}

	function bestFit(map, bounds) {
		var zoomLevel = map.getBoundsZoomLevel(bounds);
		if (zoomLevel > maxZoomLevel){
			zoomLevel = maxZoomLevel;
		}
	   map.setZoom(zoomLevel);
	   map.setCenter(bounds.getCenter());
       if(document.getElementById("searchSAP")){
           map.setCenter(new GLatLng(40.002364,116.389375),11);
       }
	}

	function toggleGroup(groupID,type,id) {
		if (type == "station") {
			for (var i = 0; i < stationGroups[groupID].length; i++) {
				var marker = stationGroups[groupID][i];
				if (document.getElementById(id).checked == true) {
				//if (marker.isHidden()) {
				  marker.show();
				} else {
				  marker.hide();
				}
			} 
		} else if (type == "landmark") {
			for (var i = 0; i < landmarkGroups[groupID].length; i++) {
				var marker = landmarkGroups[groupID][i];
				if (document.getElementById(id).checked == true) {
				//if (marker.isHidden()) {
				  marker.show();
				} else {
				  marker.hide();
				}
			} 
		}
	}

	function getclose(obj,id) {
		// support multiple hotel start
		if ( (typeof(id) == "undefined") || (id == null) ) {
			id = '';
		} else {
			map = multipleMaps[id];
		}
		
		// support multiple hotel end
		if(map!=null) {
			var centerarray=obj.split(",");		
			document.getElementById('map'+id).style.display='';
			document.getElementById('closemap'+id).style.display=''; 
			document.getElementById('openmap'+id).style.display='none';
			map.setCenter(new GLatLng(centerarray[0], centerarray[1]),parseInt(centerarray[2]));	
			map.closeInfoWindow();
		} else {
			document.getElementById('closemap'+id).style.display=''; 
			document.getElementById('openmap'+id).style.display='none';
			togglemap('',id);
			var centerarray=obj.split(",");
			map.setCenter(new GLatLng(centerarray[0], centerarray[1]),parseInt(centerarray[2]));
			map.closeInfoWindow();		
		}
	}

	function hideWindowTip() {		
		if(!windowTip)
			return;
		windowTip.style.display="none";
		windowTip.mkOffset=0;
		if(tipTimer){
			window.clearTimeout(tipTimer);
			tipTimer=0;
		}
		windowTip.onmouseover=null;
		if(maplock){
			maplock=false;
			var close=document.getElementById('PopUpClose');
			close.onclick=null;
			close.style.display='none';
		}
		showFormSelects();
	}
