/* Copyright (c) 2007 In1 Solutions Inc.
 *
 * Author: Ruiqing Liang
 * July 2007
 * 
 * This version has only single level control.
 */
 	var loadingmessage = null;
 	var isIE = false;
	var isAll = true; // until region marker has been clicked
    var map = null; // map object
	var mgr = null; // marker manager for Region/County level, used for control zoom level etc.
	var mgrOption = {borderPadding: 50, maxZoom: 15, trackMarkers: false};
	var myXHR; // XMLHttpRequest for getting XML data of Hotels 
	var defaultPath = "/default-ear/default-war/"; // for Spainin1
	var imagePath = "http://www.spainin1.com/images/hotels/img_"; //"/1.jpg"
	var buttonLink = "http://www.bookin1.com/portal/in1.jsp?id=";
	var dispWin = null;
	
	var markersInMgr = []; // hold currenty markers in the mgr
	var infoHtmls = []; // hold all information window html for currenty markers
	var hotels = []; // hotel objects holder

	function load() {
		if (navigator.appName == "Microsoft Internet Explorer") 
			isIE = true;
		
		goGetIt(); // prepare data before initialise map
		resizeMap();
		setupMap();
	}
	
	function setupMap() {
      	if (GBrowserIsCompatible()) {
        	map = new GMap2(document.getElementById("map"));
			map.addControl(new GLargeMapControl()); 
			map.addControl(new GMapTypeControl());
			map.addControl(new GScaleControl());
			map.addControl(new GOverviewMapControl()); // the small map down the conorn
			//map.setCenter(new GLatLng(40.396764305572056, -3.71337890625), 5);
			map.setCenter(new GLatLng(34.52466147177172, -9.5361328125), 5);
			map.enableDoubleClickZoom();
			var helpText = 
				"Please click a red icon to<br> view the hotels in that region.";
			map.openInfoWindowHtml(new GLatLng(36.52729481454624, -17.0486), helpText); 	
		} else {
			alert("Your browser is not able to display the map, please use others!");
		}
	}
/**************************************************
	Display markers methods below
**************************************************/		
	function setupHotelMarkerManager() {
		mgr = new MarkerManager(map, mgrOption);			
		mgr.addMarkers(getHotelMarkers(), 4);
		mgr.refresh();	
	}
	
	function getHotelMarkers() {
		var hotelMarkers = [];
		for(var i = 0; i < hotels.length; i++) {
			hotelMarkers.push(getHotelMarker(new GLatLng(hotels[i].hotelLat, hotels[i].hotelLng), i));
		}
		if(markersInMgr.length != 0) {
			markersInMgr.length = 0;
		}
		markersInMgr = hotelMarkers.slice(0);

		return hotelMarkers;
	}
	/**
	 * Get customized hotel marker; define the marker click event;
	 * contructing each single marker
	 */
	function getHotelMarker(point, index) {
		var i = index + 1;
		var hotelIcon = new GIcon(getHotelBaseIcon());
		if(isAll)
			hotelIcon.image = defaultPath + "google/markers/marker.png";
		else
			hotelIcon.image = defaultPath + "google/markers/marker" + i + ".png";
		
		var markerOption = {icon: hotelIcon, title: hotels[index].hotelName};
		var marker = new GMarker(point, markerOption); 
		// var marker = new GMarker(point, hotelIcon);
		setInfoHtml(index);
		GEvent.addListener(marker, "click", function() {
			if(dispWin != null) {
				if(!dispWin.closed)
				dispWin.window.close(); // for display image window
				dispWin = null;
			}
			var latOfCenter = map.getCenter().lat();
			var latOfMarker = hotels[index].hotelLat;
			if(latOfMarker >= ((latOfMarker + latOfCenter) / 2))
				map.panTo(new GLatLng(hotels[index].hotelLat, hotels[index].hotelLng));
				
			marker.openInfoWindowHtml(infoHtmls[index]);
		});
		return marker;
	}
	/**
	 * This method used to be inside of getHotelMarker, which is designed to
	 * construct the html for information window displayed for each property.
	 */
	function setInfoHtml(index) {
		var link = hotels[index].hotelLink;
		var image = imagePath + hotels[index].hotelCode;
		var starImg = defaultPath + "google/markers/" + hotels[index].hotelStarRate + ".gif";
		var button = buttonLink + hotels[index].hotelCode + hotels[index].hotelSrcRef;

/* 		if(hotels[index].hotelAL1 === "-")
			hotels[index].hotelAL1 = " ";
		else if(hotels[index].hotelAL2 === "-")
			hotels[index].hotelAL2 = " "; */

		var html = "<table border=0 style=font-family:Verdana>" + 
			//"<tr><td><img src='" + defaultPath + "google/markers/marker" + i + ".png'>" + "</td>" +
			// next statement is used for numbering marker dynamically
			"<tr>" + 
				"<td background='" + defaultPath + "google/markers/icon.png' width=33 height=33 align=center>" + 
					"<a title='This number references to the marker number in map.'>" + (index+1) + "</a></td>" +
				"<td>&nbsp;<a href='" + hotels[index].hotelLink + "' title='Click to open this link in a new window.' target='_blank' ><b>" + hotels[index].hotelName + "</b></a></td>" +
				"<td width=85>&nbsp;<a href='#' title='Star Rating'><img border=0 src='" + starImg + "'></a></td>" +
			"</tr></table><table style=font-family:Verdana><tr>" +
				"<td width=15></td><td colspan=2>" + hotels[index].hotelAL1 + "</td>" +
			"</tr><tr>" +
				"<td width=15></td><td colspan=2>" + hotels[index].hotelAL2 + "</td>" +
			"</tr><tr>" +
				"<td width=15></td><td width=100><a href='" + hotels[index].hotelLink + "' title='Click here to view more about this property' target='_blank' ><img border=0 src='" + defaultPath + "google/markers/btn-readmore.gif'/></a></td>" +
				"<td width=150>" + 
					"<a href='" + button + "' title='Click here to check availability and book online'target='_blank' ><img border=0 src='" + defaultPath + "google/markers/btn-booknow.gif'/></a></a></td>" +
			"</tr></table><table style=font-family:Verdana>" +
			"<tr><td width=15 height=81></td>" + 
				"<td><a href='#' title='Click image to enlarge.'><img border=0 src='" + image + "/1.jpg' onError=loadImageFailed(); width=120 height=81 onclick=displayImgs('" + image + "'); /></a></td>" +
				"<td><a href='#' title='Click image to enlarge.'><img border=0 src='" + image + "/2.jpg' onError=loadImageFailed(); width=120 height=81 onclick=displayImgs('" + image + "'); /></a></td>" + 
				"<td width=15></td>" + 
			"</tr><tr><td width=15 height=81></td>" + 
				"<td><a href='#' title='Click image to enlarge.'><img border=0 src='" + image + "/3.jpg' onError=loadImageFailed(); width=120 height=81 onclick=displayImgs('" + image + "'); /></a></td>" +
				"<td><a href='#' title='Click image to enlarge.'><img border=0 src='" + image + "/4.jpg' onError=loadImageFailed(); width=120 height=81 onclick=displayImgs('" + image + "'); /></a></td><td width=15></td>" +
			"</tr><tr style=font-style:italic height=15><td></td><td colspan=2 align=left style=font-size:12px>* Click images to enlarge.</td>" + 
			"</tr><tr style=font-style:italic height=15><td></td><td colspan=2 align=left style=font-size:12px>* Click X to close this window.</td><td></td></tr><tr><td>&nbsp;</td></tr></table>";
		
		infoHtmls.push(html);
	}

	/**
	 * Create a base icon for all of our markers that specifies the shadow, icon dimensions, etc.
	 */
	function getHotelBaseIcon() {
		var baseIcon = new GIcon();
		baseIcon.shadow = defaultPath + "google/markers/shadow.png";
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);
		
		return baseIcon;
	}

/**************************************************
	Get Data methods below
**************************************************/	
	// get hotels located in the selected region
	function goGetIt(){
		myXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
		//var url = "google/mapDataFeeder?"; this line is using Servlet
		var url = "http://www.spainin1.com/google/mapDataFeeder.jsp?town=all&county=all";
		url += "&country=ES"; // only modify here for changing country
		
		myXHR.onreadystatechange = function() {
			if(myXHR.readyState == 4){
				hotels.length = 0; // clear hotel object holder
				parseAllHotels(myXHR.responseXML);
				//window.setTimeout(setupHotelMarkerManager, 0);
				setupHotelMarkerManager();
			}
		};
		myXHR.open("GET", url, true);
		myXHR.send(null);
	}
	/**
	 * Get all search result from servlet output XML.
	 * Independent method for map search.
	 */
	function parseAllHotels(responseXML) {
		if(responseXML) {
			try {
				var x = responseXML.documentElement.getElementsByTagName("Property");
				for(var i = 0; i < x.length; i++) {
					var hotel = new Object();
					hotel.hotelID = x[i].getElementsByTagName("HotelID")[0].firstChild.data;
					hotel.hotelName = x[i].getElementsByTagName("HotelName")[0].firstChild.data;
					hotel.hotelCode = x[i].getElementsByTagName("HotelCode")[0].firstChild.data;
					hotel.hotelSrcRef = x[i].getElementsByTagName("SrcRef")[0].firstChild.data;
					hotel.hotelStarRate = x[i].getElementsByTagName("StarRate")[0].firstChild.data;
					hotel.hotelLink = x[i].getElementsByTagName("HotelInformationLink")[0].firstChild.data;
					hotel.hotelAL1 = x[i].getElementsByTagName("AddressLine1")[0].firstChild.data;
					hotel.hotelAL2 = x[i].getElementsByTagName("AddressLine2")[0].firstChild.data;
					hotel.hotelLat = parseFloat(x[i].getElementsByTagName("Latitude")[0].firstChild.data);
					hotel.hotelLng = parseFloat(x[i].getElementsByTagName("Longitude")[0].firstChild.data);
					
					hotels.push(hotel);
				}
			} catch(err) {
				// Shouldn't do nothing, but that has been done in Servlet
				//alert(err); 
			}
		} else { 
			alert("Application Server Error(No Data To Display)! ");
		}
    }
   
/**************************************************
	ResizeMap, Display images
**************************************************/	
	// JavaScript Document
	function getElement(id){
		return document.getElementById(id);
	}
	function resizeMap(){
		var width = 905;
		var height = 720;
		if(height >= 0){
			getElement("map").style.height = height + "px";
			getElement("map").style.width = width + "px";
		}
		if(map) map.checkResize();
	}
	function getWindowHeight(){
		if(window.self && self.innerHeight){
			return self.innerHeight;
		}
		if(document.documentElement && document.documentElement.clientHeight){
			return document.documentElement.clientHeight;
		}
		return 0;
	}	
	function getWindowWidth(){
		if(window.self && self.innerWidth){
			return self.innerWidth;
		}
		if(document.documentElement && document.documentElement.clientWidth){
			return document.documentElement.clientWidth;
		}
		return 0;
	}
	/**
	 * Construct the images popup window.
	 */
	function displayImgs(path) {
		if(dispWin == null || dispWin.closed) {
			dispWin = window.open('', '', 'height=360,width=490,directories=no,resizable=no,status=no,titlebar=no,toolbar=no,menubar=no,location=no,left=0,top=50');
			dispWin.document.writeln("<html><head>");
			dispWin.document.writeln("<script type='text/javascript'>");
			dispWin.document.writeln("function loadImageFailed(index){");
			dispWin.document.writeln("if(navigator.appName=='Microsoft Internet Explorer') window.event.srcElement.style.display='None'; else { this.document.getElementById(index).innerHTML='';}}");
			dispWin.document.writeln("</script>");
			dispWin.document.writeln("</head><body>");
			var message = "<table><tr><td><div id='1'><img src='" + path + "/1.jpg' onError=loadImageFailed(1); /></div></td>";
			message += "<td><div id='2'><img src='" + path + "/2.jpg' onError=loadImageFailed(2); /></div></td></tr>";
			message += "<tr><td><div id='3'><img src='" + path + "/3.jpg' onError=loadImageFailed(3); /></div></td>";
			message += "<td><div id='4'><img src='" + path + "/4.jpg' onError=loadImageFailed(4); /></div></td></tr>";
			message += "<tr><td></td><td align=right><input type=button value='Close Window' onclick=window.close(); ></td></tr></table></body></html>";
			dispWin.document.write(message);
		} 
	}
	function loadImageFailed() {
		if(isIE)
			window.event.srcElement.style.display = "None";
	}
	
/**************************************************
	Custom Overlay Loading Message Box
**************************************************/	
	function getLMBounds() {
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var latDelta = (northEast.lat() - southWest.lat()) / 2.2;
		var lngDelta = (northEast.lng() - southWest.lng()) / 2.8;
		var rectBounds = new GLatLngBounds(
								new GLatLng(southWest.lat() + latDelta, southWest.lng() + lngDelta),
								new GLatLng(northEast.lat() - latDelta, northEast.lng() - lngDelta));
		return rectBounds;
	}

	function LoadingMessage(bounds, html, opt_weight, opt_color) {
		this.bounds_ = bounds;
		this.html_ = html
		this.weight_ = opt_weight;
		this.color_ = opt_color;
	}
	LoadingMessage.prototype = new GOverlay();
	
	LoadingMessage.prototype.initialize = function(map) {
		// Create the DIV representing our LM
		var div = document.createElement("div");
		div.style.border = this.weight_ + "px solid " + this.color_;
		div.style.position = "absolute";
		div.innerHTML = this.html_;
	
		// Our rectangle is flat against the map, so we add our selves to the
	    // MAP_PANE pane, which is at the same z-index as the map itself (i.e.,
	    // front of everything else on the map)
	    map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
	
	    this.map_ = map;
	  	this.div_ = div;
	}
	
	// Remove the main DIV from the map pane
	LoadingMessage.prototype.remove = function() {
	  this.div_.parentNode.removeChild(this.div_);
	}
	// Copy our data to a new LoadingMessage
	LoadingMessage.prototype.copy = function() {
	  return new LoadingMessage(this.bounds_, this.weight_, this.color_,
						   this.backgroundColor_, this.opacity_);
	}
	// Redraw the rectangle based on the current projection and zoom level
	LoadingMessage.prototype.redraw = function(force) {
	  // We only need to redraw if the coordinate system has changed
	  if (!force) return;
	
	  // Calculate the DIV coordinates of two opposite corners of our bounds to
	  // get the size and position of our rectangle
	  var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest());
	  var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast());
	
	  // Now position our DIV based on the DIV coordinates of our bounds
	  this.div_.style.width = Math.abs(c2.x - c1.x) + "px";
	  this.div_.style.height = Math.abs(c2.y - c1.y) + "px";
	  this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_) + "px";
	  this.div_.style.top = (Math.min(c2.y, c1.y) - this.weight_) + "px";
	}
/**************************************************
	Ends Custom Overlay Loading Message Box
**************************************************/
