//<![CDATA[

var Hotelguide = (function(){
		var Browser = {
		    IE:     !!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1),
		    Opera:  navigator.userAgent.indexOf('Opera') > -1,
		    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
		    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') === -1,
		    MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
		}
	
		function getViewportDimensions() { 
	    	var B = Browser; 
	    	var width = (B.WebKit && !document.evaluate) ? self['innerWidth'] : 
	    	(B.Opera) ? document.body['clientWidth'] : document.documentElement['clientWidth']; 
	    	var height = (B.WebKit && !document.evaluate) ? self['innerHeight'] : 
		    	(B.Opera) ? document.body['clientHeight'] : document.documentElement['clientHeight']; 
	    	return {width: width, height: height}; 
	    }

	    function cumulativeOffset(element) {
	        var valueT = 0, valueL = 0;
	        do {
	          valueT += element.offsetTop  || 0;
	          valueL += element.offsetLeft || 0;
	          element = element.offsetParent;
	        } while (element);
	        return {left: valueL, top: valueT};
        }

	    function viewportOffset(forElement) {
            var valueT = 0, valueL = 0;

            var element = forElement;
            do {
              valueT += element.offsetTop  || 0;
              valueL += element.offsetLeft || 0;

              // Safari fix
              if (element.offsetParent == document.body &&
                element.style.position == 'absolute') break;

            } while (element = element.offsetParent);

            element = forElement;
            do {
              if (!Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == 'BODY'))) {
                valueT -= element.scrollTop  || 0;
                valueL -= element.scrollLeft || 0;
              }
            } while (element = element.parentNode);

            return {left: valueL, top: valueT};
          }

	    function HotelLayer(map, opts) {
	    	if (opts && opts.legend)
				map.addControl(new HotelsLegend(opts));
				
	    	if (opts && opts.search) {
				var search = new HotelsSearch(opts);
				//map.addControl(search);
				opts.search = search;
			}
			opts.openInNewWindow = true;
			map.addOverlay(new Hotels(opts));
	    }

		HotelsLegend.priceTranslation = {en: "Price", de: "Preis", fr: "Tarif", it: "Prezzo", ru: "Цена"}
		
	    function HotelsLegend(opts) {
			var language = opts && opts.language ? opts.language : "en";
			this.priceLabel = HotelsLegend.priceTranslation[language];
			if (this.priceLabel == null)
				this.priceLabel = "Price";
	    }
	
	    HotelsLegend.prototype = new GControl();

	    HotelsLegend.prototype.initialize = function(map) {
	    	  var container = document.createElement("div");
	    	  container.innerHTML = '<div style="font-size: 10px; text-align: center; background-color: #fff;">'+this.priceLabel+':<br /><img src="http://www.hotelguide.com/img/mapicons/legend.gif" /></div>';
	    	  map.getContainer().appendChild(container);
	    	  return container;
	    }

	    HotelsLegend.prototype.getDefaultPosition = function() {
	    	  return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(5, 20));
	    }

	    function HotelsSearch(opts) {
			var language = opts && opts.language ? opts.language : "en";
	    }
	
	    HotelsSearch.prototype = new GControl();

	    HotelsSearch.prototype.initialize = function(map) {
	    	  this.container = document.createElement("div");
	    	  this.container.style.width = 100 + "px";
	    	  this.container.style.height = 30 + "px";
	    	  this.container.style.backgroundColor = "#fff";
	    	  this.container.innerHTML = '';
	    	  map.getContainer().appendChild(this.container);
	    	  return this.container;
	    }

	    HotelsSearch.prototype.getDefaultPosition = function() {
	    	  return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(5, 100));
	    }

	    function Hotels(opts) {
		    if (opts && opts.tooltip) {
		        this.tooltip = opts.tooltip;
		    }
		    else {
	    	    this.tooltip = document.createElement("div");
	    	    this.tooltip.style.fontSize = 'x-small';
	    	    this.tooltip.style.fontFamily = 'Tahoma, Arial, Helvetica, sans-serif';
	    	    this.tooltip.style.color = '#000';
	    	    this.tooltip.style.backgroundColor = '#FFF';
	    	    this.tooltip.style.border = '1px solid #CCC';
	    	    this.tooltip.style.width = '200px';
	    	    this.tooltip.style.padding = '2px';
	    	    
	    	    this.tooltip.style.visibility = 'hidden';
	    	    this.tooltip.style.position = 'absolute';
	    	    this.tooltip.style.zIndex = 2;
	    	    this.tooltip.style.left = '0px';
	    	    this.tooltip.style.top = '0px';
				document.body.appendChild(this.tooltip);
		    }
			if (opts && opts.openInNewWindow)
				this.openInNewWindow = true;
			if (opts && opts.openInfoWindow)
				this.openInfoWindow = true;
			this.max = opts && opts.max ? opts.max : 50;
			this.iconWidth = opts && opts.clusterWidth ? opts.clusterWidth : 60;
			this.iconHeight = opts && opts.clusterHeight ? opts.clusterHeight : 60;
			this.popupTitle = opts && opts.popupTitle != null ? opts.popupTitle : true;
			this.currency = opts && opts.currency ? opts.currency : "USD";
			this.type = opts && opts.group ? "group" : "hotel";
			if (opts && opts.type)
				this.type = opts.type;
			if (opts && opts.language)
				this.language = opts.language;
			if (opts && opts.user)
				this.user = opts.user;
			if (opts && opts.subaffiliate)
				this.subaffiliate = opts.subaffiliate;
			if (opts && opts.icon) {
	            this.icon = opts.icon;
			}
			else {
	    	   	var baseIcon = new GIcon();
	    		baseIcon.image = "http://www.hotelguide.com/img/mapicons/iconhotelr.png";
	    		baseIcon.shadow = "http://www.hotelguide.com/img/mapicons/sm-shadow.png";
	    		baseIcon.iconSize = new GSize(14, 23);
	    		baseIcon.shadowSize = new GSize(27, 23);
	    		baseIcon.iconAnchor = new GPoint(7, 23);
	    		baseIcon.infoWindowAnchor = new GPoint(9, 5);
	    		baseIcon.infoShadowAnchor = new GPoint(18, 25);
	            this.baseIcon = baseIcon;
			}
			if (opts && opts.search)
	            this.search = opts.search;
	            
			this.availabilityDelay = opts && opts.availabilityDelay ? Math.max(opts.availabilityDelay, 1000) : 2000;
	    }
	
	    Hotels.prototype = new GOverlay();
	
	    Hotels.prototype.initialize = function(map) {
	        this.map = map;
	        this.moveEndH_ = GEvent.bind(this.map, "moveend", this, this.load);
	        //this.loadH_ = GEvent.bind(this.map, "load", this, this.load);
	
	        this.jstag = null;
			this.hotels = [];
            this.hotelIcons = {};
            this.hotelGroups = [];
            this.hotelIconsAvailable = {};
			this.postActions = {};
           	this.offset = 0;
           	this.hotelsOnMap = 0;
			this.found = 0;
	    	window.loadHotelsCallback = GEvent.callback(this, this.load);
	    	window.hotelsCallback = GEvent.callback(this, this.callback);
	    	window.resultsCallback = GEvent.callback(this, this.results);
	    	this.load();

	    	if (this.search) {
	    		//Get references to the search panel elements
		    	this.mapPanel = document.getElementById('mapPanel');
		    	this.mapPanelControl = document.getElementById('mapPanelControl');
		    	this.hotelsFoundMessage = document.getElementById('hotelsFoundMessage');
		    	this.searchInProgress = document.getElementById('searchInProgress');
		    	this.resultList = document.getElementById('resultList');
		    	this.sortBar = document.getElementById('sortBar');
		    	this.hotelsToSearchMessage = document.getElementById('hotelsToSearchMessage');
		    	this.searchRow = document.getElementById('searchRow');
		    	this.hotelsToSearch = document.getElementById('hotelsToSearch');
		    	this.availabilityForm = document.getElementById('availabilityForm');
		    	this.zoomInMessage = document.getElementById('zoomInMessage');
		    	this.availabilitySearchButton = document.getElementById('availabilitySearchButton');
		    	
		    	//Search form setup
	    		GEvent.bindDom(this.availabilitySearchButton, "click", this, this.availability);
			    var arrivalDate = new Date();
			    arrivalDate.setDate(arrivalDate.getDate() + 1);
			    var departureDate = new Date();
			    departureDate.setTime(arrivalDate.getTime());
			    departureDate.setDate(departureDate.getDate() + getNights());
				getCalendar('arrival').selectDate(arrivalDate);
				getCalendar('departure').selectDate(departureDate);

				//Sort bar setup	
	    		GEvent.bindDom(document.getElementById('sortByPrice'), "click", this, this.sortByPrice);
	    		GEvent.bindDom(document.getElementById('sortByName'), "click", this, this.sortByName);
	    		GEvent.bindDom(document.getElementById('sortByRate'), "click", this, this.sortByRate);
	    		GEvent.bindDom(document.getElementById('sortByDiscount'), "click", this, this.sortByDiscount);
       			this.currentsort = "Discount";
	    		this.sortByDiscount();

	    		window.formChanged = GEvent.callback(this, this.formChanged);
	    		this.showPanel();
    		}
	    }

	    Hotels.prototype.formChanged = function() {
            var arrivalDate = getCalendar('arrival').getSelectedDate();
            var departureDate = getCalendar('departure').getSelectedDate();
			var guestQuantityComponent = $('availabilitySearchForm:guestsQuantityDecoration:guestQuantityEdit');
			var guestQuantity = parseInt(guestQuantityComponent.firstChild.value);
			var roomQuantityComponent = $('availabilitySearchForm:roomQuantityDecoration:roomQuantityEdit');
			var roomQuantity = parseInt(roomQuantityComponent.firstChild.value);
			//if (!arrivalDate || !departureDate || roomQuantity == 0 || guestQuantity == 0)
				//return;
			
			if (arrivalDate != this.arrivalDate || departureDate != this.departureDate || roomQuantity != this.roomQuantity || guestQuantity != this.guestQuantity) {
				this.resetSearch();
			}
		}
		
	    Hotels.prototype.resetSearch = function() {
	    	var clear = false;
       		for (var i in this.hotelIconsAvailable) {
       			clear = true;
       			break;
			}			
			
			if (clear) {
				this.hotelIconsAvailable = {};
				
	           	for (var i in this.hotelIcons) {
	       			this.hotelsOnMap--;
	       			this.map.removeOverlay(this.hotelIcons[i]);
	           	}
				this.hotelIcons = {};
	           	
	           	for (var i = 0; i < this.hotelGroups.length; ++i) {
	    			this.map.removeOverlay(this.hotelGroups[i]);
	          		this.hotelsOnMap -= this.hotelGroups[i].size;
	           	}
				this.hotelGroups = [];
				
				this.hotels = [];
				this.updateResults();
				this.load();
			}
	    }
	    
	    Hotels.prototype.remove = function() {
	       	for (var i in this.webcams) {
	   			this.map.removeOverlay(this.hotels[i]);
	       	}
	  		GEvent.removeListener(this.moveEndH_);
	  		//GEvent.removeListener(this.loadH_);
	    }
	
	    Hotels.prototype.redraw = function(force) {
	      if (!force) return;
	      
	      //this.load();
	    }
	    
	    Hotels.prototype.load = function ()
		{
			if (this.wait) {
				this.postActions['load'] = true;
				return;
			}
			var bounds = this.map.getBounds();
	        var sw = bounds.getSouthWest();
	        var ne = bounds.getNorthEast();
	        if (this.mapPanel && ne.lng() - sw.lng() < 360) {
		        var offset = this.mapPanel.offsetLeft + this.mapPanel.offsetWidth;
		        //GLog.write("Load: " + sw + ", " + ne);
		        sw = this.map.fromContainerPixelToLatLng(new GPoint(offset, this.map.getSize().height));
		        //GLog.write("Load: " + sw);
	        }
			this.refreshMap(sw.lng(), sw.lat(), ne.lng(), ne.lat());
		}

	    Hotels.prototype.refreshMap = function (longitudeLeft, latitudeLow, longitudeRight, latitudeUp)
		{
            var size = this.map.getSize();
	    	var URL = "http://maps.hotelguide.com/seam/resource/hotelfeed?type=" + this.type + "&max=" + this.max + "&iw=" + this.iconWidth + "&ih=" + this.iconHeight + "&mw=" + size.width + "&mh=" + size.height + "&bbox="+longitudeLeft+","+latitudeLow+","+longitudeRight+","+latitudeUp + "&cur=" + this.currency + (this.language ? "&lang=" + this.language : "") + (this.user ? "&u=" + this.user : "") + (this.subaffiliate ? "&s=" + this.subaffiliate : "") + "&callback=hotelsCallback";
	        if (this.jstag && this.jstag.parentNode)
	        	this.jstag.parentNode.removeChild(this.jstag);
	        this.jstag = document.createElement('script');
	        //this.jstag.id = 'uploadScript';
	        this.jstag.type = 'text/javascript';
	        this.jstag.src = URL;
			document.getElementsByTagName("head")[0].appendChild(this.jstag);
			this.wait = new Date();
		}

	    Hotels.prototype.showPanel = function () {
	    	new Effect.Move(this.mapPanel, {
	    			x: 0,
	    			y: 23,
	    			mode: 'absolute',
	                duration: 0.2});
	    	new Effect.Move(this.mapPanelControl, {
	    			x: 0,
	    			mode: 'absolute',
	                duration: 0.2});
//			this.mapPanel.style.left = "0px";
//			this.mapPanelControl.style.left = "0px";
	    	if (this.mapPanelControl) {
	    		this.mapPanelControl.style.backgroundPosition = "bottom right";
				GEvent.clearListeners(this.mapPanelControl, "click");  
	    		GEvent.bindDom(this.mapPanelControl, "click", this, this.hidePanel);
    		}
    		if (this.map.mapControl) {
	    		this.map.removeControl(this.map.mapControl);
	    		this.map.mapControl = new GLargeMapControl();
	    		var position = this.map.mapControl.getDefaultPosition();
	    		position.offset.width += this.mapPanel.offsetWidth; 
	    		this.map.addControl(this.map.mapControl, position);
    		}
    		setTimeout("loadHotelsCallback();", 500);
		}

	    Hotels.prototype.hidePanel = function () {
	    	new Effect.Move(this.mapPanel, {
	    			x: - this.mapPanel.offsetWidth,
	    			y: 23,
	    			mode: 'absolute',
	                duration: 0.2});
	    	new Effect.Move(this.mapPanelControl, {
	    			x: - this.mapPanel.offsetWidth,
	    			mode: 'absolute',
	                duration: 0.2});
//			this.mapPanel.style.left = "-" + this.mapPanel.offsetWidth + "px";
//			this.mapPanelControl.style.left = "-" + this.mapPanel.offsetWidth + "px";
	    	if (this.mapPanelControl) {
	    		this.mapPanelControl.style.backgroundPosition = "top right";
				GEvent.clearListeners(this.mapPanelControl, "click");  
	    		GEvent.bindDom(this.mapPanelControl, "click", this, this.showPanel);
    		}
    		if (this.map.mapControl) {
	    		this.map.removeControl(this.map.mapControl);
	    		this.map.mapControl = new GLargeMapControl();
	    		this.map.addControl(this.map.mapControl);
    		}
    		setTimeout("loadHotelsCallback();", 500);
		}

	    Hotels.prototype.availability = function ()
		{
			if (this.wait) {
				this.postActions['availability'] = true;
				return;
			}
            var arrivalDate = getCalendar('arrival').getSelectedDate();
            var departureDate = getCalendar('departure').getSelectedDate();
			var guestQuantityComponent = $('availabilitySearchForm:guestsQuantityDecoration:guestQuantityEdit');
			var guestQuantity = parseInt(guestQuantityComponent.firstChild.value);
			var roomQuantityComponent = $('availabilitySearchForm:roomQuantityDecoration:roomQuantityEdit');
			var roomQuantity = parseInt(roomQuantityComponent.firstChild.value);
			if (!arrivalDate || !departureDate || roomQuantity == 0 || guestQuantity == 0)
				return;
			
			var skippedHotels = [];			
			if (arrivalDate != this.arrivalDate || departureDate != this.departureDate || roomQuantity != this.roomQuantity || guestQuantity != this.guestQuantity) {
           		for (var i in this.hotelIconsAvailable) {
   					var hotelIcon = this.hotelIconsAvailable[i];
           			if (!hotelIcon.available)
						skippedHotels.push(i);
				}			
				this.hotelIconsAvailable = {};
			}

			try {
			if (this.resultList)
				this.resultList.innerHTML = '';
			} catch (e) {}
			
			this.arrivalDate = arrivalDate;
			this.departureDate = departureDate;
			this.roomQuantity = roomQuantity;
			this.guestQuantity = guestQuantity;

            var size = this.map.getSize();
   		 	this.offset = 0;
   		 	this.searchId = null;
   		 	
			var ids = '';
           	for (var i in this.hotelIcons) {
   				var hotelIcon = this.hotelIconsAvailable[i];
   				if (!hotelIcon || !hotelIcon.available) {
   					this.hotelIconsAvailable[i] = {};
		           	if (ids.length > 0)
		           		ids += ',';
	           		ids += i;
 				}
           	}
           	for (var i = 0; i < skippedHotels.length; ++i) {
           		var id = skippedHotels[i];
 				this.hotelIconsAvailable[id] = {};
	           	if (ids.length > 0)
	           		ids += ',';
           		ids += id;
           	}
           	
           	if (ids == '') {
           		this.updateResults();
                return;
            }
                
            var arrivalDateText = arrivalDate.getFullYear() + '-' + (arrivalDate.getMonth() + 1) + '-' + arrivalDate.getDate();    
            var departureDateText = departureDate.getFullYear() + '-' + (departureDate.getMonth() + 1) + '-' + departureDate.getDate();
	    	var URL = "http://www.hotelguide.com/seam/resource/hotelfeed?action=availability&type=" + this.type + "&max=" + this.max + "&ids=" + ids + "&arrival=" + arrivalDateText + "&departure=" + departureDateText + "&guests=" + guestQuantity + "&rooms=" + roomQuantity + "&cur=" + this.currency + (this.language ? "&lang=" + this.language : "") + (this.user ? "&u=" + this.user : "") + (this.subaffiliate ? "&s=" + this.subaffiliate : "") + "&callback=hotelsCallback";
			//GLog.write("Availability: " + URL);
	        if (this.jstag)
	        	this.jstag.parentNode.removeChild(this.jstag);
	        this.jstag = document.createElement('script');
	        //this.jstag.id = 'uploadScript';
	        this.jstag.type = 'text/javascript';
	        this.jstag.src = URL;
			document.getElementsByTagName("head")[0].appendChild(this.jstag);
			this.wait = new Date();
		}

	    Hotels.prototype.results = function ()
		{
			if (this.searchId) {
	            var size = this.map.getSize();
		    	var URL = "http://www.hotelguide.com/seam/resource/hotelfeed?action=resultsOnMap&type=" + this.type + "&offset=" + this.offset + "&searchId=" + this.searchId + "&cur=" + this.currency + (this.language ? "&lang=" + this.language : "") + (this.user ? "&u=" + this.user : "") + (this.subaffiliate ? "&s=" + this.subaffiliate : "") + "&callback=hotelsCallback";
				//GLog.write("Results: " + URL);
		        if (this.jstag)
		        	this.jstag.parentNode.removeChild(this.jstag);
		        this.jstag = document.createElement('script');
		        //this.jstag.id = 'uploadScript';
		        this.jstag.type = 'text/javascript';
		        this.jstag.src = URL;
				document.getElementsByTagName("head")[0].appendChild(this.jstag);
			}
		}
	    
	    Hotels.prototype.callback = function(data) {
	    	if (this.map) {
	    		try {
	            var add = [];
	            
           		var count = 0;
           		var available = 0;
           		var skipped = 0;
           		var hotelIconsNew = {};
				var updateResults = false;
           		
       			var availability = false;
            	var status = data.status;
	            if (status) {
		           	if (this.search) {
		           		//GLog.write('got ' + status.count + ' hotels, total ' + status.total + ', requested ' + status.requested + ', ' + (status.active?'active':'finished'));
		           		if (!this.searchId) {
		           			this.searchId = status.searchId;
		           			availability = true;
	           				this.hotelsFoundMessage.style.display = 'none';
	           				this.sortBar.style.display = 'none';
	           				this.searchInProgress.style.display = '';
				           	for (var i in this.hotelIcons) {
				   				var hotelIcon = this.hotelIconsAvailable[i];
   								if (hotelIcon && hotelIcon.available)
           							hotelIconsNew[i] = hotelIcon; 
         					}
         					//this.availabilitySearchButton.innerHTML = "Searching...";
         					this.searchRow.style.display = 'none';
	           			}
			            else {
			            	hotelIconsNew = this.hotelIcons;
			            	for (e in hotelIconsNew) { count++; }
			            }
	           		}
		           		
	           		if (data.results)
	            		data.hotels = data.results; 
	            }
	            if (data.groups) {
		           	for (var i = 0; i < data.groups.length; ++i) {
		           		var hotel = data.groups[i];
		           		
						var hotelGroup = new HotelGroup();
						hotelGroup.lat =  hotel.lat;
						hotelGroup.lng =  hotel.lng;
						hotelGroup.lngLeft =  hotel.lngLeft;
						hotelGroup.lngRight =  hotel.lngRight;
						hotelGroup.latLow =  hotel.latLow;
						hotelGroup.latUp =  hotel.latUp;
						hotelGroup.size =  hotel.size;
						
						hotelGroup.hotels = this;
		           		add.push(hotelGroup);
		                count += hotelGroup.size;
	                }
	            }
	            if (data.hotels) {
		           	for (var i = 0; i < data.hotels.length; ++i) {
		           		var hotel = data.hotels[i];
		           		
		           		if (hotel instanceof HotelIconBasic) {
		           			hotel.hotels = this;
			           		var hotelOnMap = this.hotelIcons[hotel.id]; 
			           		if (hotelOnMap == null)
				           		add.push(hotel);
			           		else
			           			hotel = hotelOnMap;
			                hotelIconsNew[hotel.id] = hotel;
		           			count++;
		           		}
		           		else {
							var hotelIcon = new HotelIconBasic();
							hotelIcon.id =  hotel.id;
							hotelIcon.lat =  hotel.lat;
							hotelIcon.lng =  hotel.lng;
							hotelIcon.title =  hotel.title;
							hotelIcon.address = hotel.address;
							hotelIcon.price = hotel.price;
							hotelIcon.min_price = hotel.min_price;
							hotelIcon.max_price = hotel.max_price;
							hotelIcon.discount = hotel.discount;
							hotelIcon.discount_price = hotel.discount_price;
			            	hotelIcon.rating =  hotel.rating;
		        		 	hotelIcon.url = hotel.url;
		        		 	hotelIcon.image = hotel.image;
		        		 	hotelIcon.available = hotel.available;
		        		 	hotelIcon.hotels = this;
		        		 	if (hotelIcon.available) {
		        		 		hotelIcon.searchId = this.searchId;
		                		this.offset++;
			                }
		           			var hotelOnMap = this.hotelIcons[hotelIcon.id]; 
		           			if (hotelOnMap == null) {
			           			hotelOnMap = this.hotelIconsAvailable[hotelIcon.id]; 
		           				if (hotelOnMap) {
		           					if (hotelOnMap.available)
			           					hotelIcon = hotelOnMap;
		           					else if (!hotelIcon.available) {
		           						skipped++;
			           					continue;
		           					}
		           					available++;
		           				}
		           				else {
			           				count++;
		           				}
			           			add.push(hotelIcon);
		           				if (hotelIcon.available)
		        					updateResults = true;
		           			}
			           		else {
			           			hotelIcon = hotelOnMap;
	           					if (!hotelOnMap.available)
			           				count++;
		           				else
		           					available++;
		           			}
		           			
		           			if (hotelIcon.available)
		           				this.hotelIconsAvailable[hotelIcon.id] = hotelIcon;
		        		 	
			                hotelIconsNew[hotelIcon.id] = hotelIcon;
		           		}
	           		}  
	            }
	
				if (!this.searchId || availability) {
		           	for (var i in this.hotelIcons) {
			           	if (hotelIconsNew[i] == null) {
	            			this.hotelsOnMap--;
		        			this.map.removeOverlay(this.hotelIcons[i]);
		           			if (this.hotelIcons[i].available)
		        				updateResults = true;
			           	}
		           	}
	           	}
	           	for (var i = 0; i < this.hotelGroups.length; ++i) {
	    			this.map.removeOverlay(this.hotelGroups[i]);
           			this.hotelsOnMap -= this.hotelGroups[i].size;
	           	}
				this.hotelGroups = [];
	           	for (var i = 0; i < add.length; ++i) {
		           	var hotelIcon = add[i];
	            	this.map.addOverlay(hotelIcon);
		           	if (hotelIcon.available)
        				updateResults = true;
	            	if (!hotelIcon.id) {
	            		this.hotelGroups.push(hotelIcon);
           				this.hotelsOnMap += hotelIcon.size;
          			}
          			else
           				this.hotelsOnMap++;
	           	}
	           	this.hotelIcons = hotelIconsNew;
				if (status) {           		
	           		if (status.active) {
	           			setTimeout("resultsCallback();", this.availabilityDelay);
	           		}
	           		else {
		           		this.wait = null;
		           		this.searchId = null;
                		this.offset = 0;
         				//this.availabilitySearchButton.innerHTML = "Search";
         				this.searchRow.style.display = '';
         				updateResults = true;
	           			this.callPostActions();
	           		}
           		}
           		else {
		           	this.wait = null;
           			this.callPostActions();
         		}
           		
				if (updateResults && !this.searchId && this.search) {
       				this.searchInProgress.style.display = 'none';
       				this.sortBar.style.display = '';
       				this.updateResults();
				}   
				if (this.search)           		
					this.updateCount();
	           	if (this.search && !this.searchId) {
	           		//GLog.write("Counts: " + count +", "+ available +", "+ skipped);
	           		if ((count > 0 || available > 0 || skipped > 0) && count < this.max) {
           				this.zoomInMessage.style.display = 'none';
           				this.availabilityForm.style.display = '';
       					this.availabilitySearchButton.disabled = this.hotelsOnMap <= this.found ? true : false;
       					this.hotelsToSearchMessage.style.display = this.hotelsOnMap <= this.found ? 'none' : ''; 
           				this.resultList.style.display = '';
           			}
           			else {
           				this.zoomInMessage.style.display = '';
           				this.availabilityForm.style.display = 'none';
           				this.resultList.style.display = 'none';
           			}
           		}
			    }
			    catch (e) {
					GLog.write("Error: " + e);
			    }
	    	}
		}

    	Hotels.prototype.callPostActions = function() {
    		if (this.postActions['load']) {
    			this.postActions['load'] = null;
    			this.load();
   			}
   			else if (this.postActions['availability']) {
    			this.postActions['availability'] = null;
    			this.availability();
   			}
		}

    	Hotels.prototype.updateCount = function() {
    		if (this.hotelsToSearch)
   				this.hotelsToSearch.innerHTML = this.hotelsOnMap > this.found ? this.hotelsOnMap - this.found : 0;  
    	}
		
    	Hotels.prototype.updateResults = function() {
			var even = true;
			this.found = 0;
			//Element.update(this.resultList);
			while(this.resultList.hasChildNodes())
				this.resultList.removeChild(this.resultList.childNodes[0]);
				
			this.hotels = [];
           	for (var i in this.hotelIcons) {
           		var hotel = this.hotelIcons[i];
           		if (hotel.available)
           			this.hotels.push(hotel);
           	}
				
			var tbody = document.createElement("tbody");
			this.resultList.appendChild(tbody);
			if (this.hotels.length == 0) {
     			this.sortBar.style.display = 'none';
  				var row = document.createElement("tr");
  				var cell1 = document.createElement("td");
     			cell1.innerHTML = ' Please use the calendar above to check availability and rates for the hotels located on the map,';
  				row.appendChild(cell1);
  				tbody.appendChild(row);
				this.hotelsFoundMessage.style.display = 'none';
     			return;
			}
       		this.sort();
           	for (var i = 0; i < this.hotels.length; ++i) {
           		var hotelIcon = this.hotels[i];
  				var row = document.createElement("tr");
		  		row.setAttribute('className', even?'even':'odd');
		  		row.setAttribute('class', even?'even':'odd');
		  		row.style.cursor = 'pointer';
  				var cell1 = document.createElement("td");
  				cell1.innerHTML = '<img src="' + hotelIcon.image + '" style="margin-right:5px;border:1px solid #fff" width="65" height="65" />'; 
  				row.appendChild(cell1);
  				var cell2 = document.createElement("td");
  				cell2.innerHTML = hotelIcon.title + '<img src="/img/star' + hotelIcon.rating + '.gif" class="rating" alt="rating"/><p class="descr">' + hotelIcon.address + '</p>'; 
  				row.appendChild(cell2);
  				var cell3 = document.createElement("td");
		  		cell3.setAttribute('className', 'hd r');
		  		cell3.setAttribute('class', 'hd r');
  				cell3.innerHTML = 'from:<br/>'; 
		  		if (hotelIcon.discount > 0)
  					cell3.innerHTML += '<strike style="color:red;">' + hotelIcon.discount_price + '</strike><br/>'
  				cell3.innerHTML += hotelIcon.min_price; 
  				row.appendChild(cell3);
  				//row.innerHTML = '<td><img src="' + hotelIcon.image + '" style="margin-right:5px;" /></td><td>' + hotelIcon.title  + 
				//'<img src="/img/star' + hotelIcon.rating + '.gif" class="rating" alt="rating"/><p class="descr">' + hotelIcon.address + '</p></td><td class="hd r">' + Math.round(hotelIcon.price) + '</td>';
          		GEvent.bindDom(row, 'click', hotelIcon, hotelIcon.openDetails); 
	      		GEvent.bindDom(row, 'mouseover', hotelIcon, hotelIcon.mouseover);
	      		GEvent.bindDom(row, 'mouseout', hotelIcon, hotelIcon.mouseout);
  				tbody.appendChild(row);
  				//Element.insert(this.resultList, row);
				this.found++;
				even = !even;
           	}
			this.hotelsFoundMessage.style.display = '';
			this.hotelsFoundMessage.innerHTML = this.found ? 'Hotels available: ' + this.found : 'mappanel.msg05';            			
		}		

        Hotels.prototype.sortByPrice = function() {
        	this.sortResults("Price");
        	return false;
        }

        Hotels.prototype.sortByName = function() {
        	this.sortResults("Name");
        	return false;
        }

        Hotels.prototype.sortByRate = function() {
        	this.sortResults("Rate");
        	return false;
        }

        Hotels.prototype.sortByDiscount = function() {
        	this.sortResults("Discount");
        	return false;
        }

        Hotels.prototype.sortResults = function(type) {
        	//if (type == this.currentsort)
        		//this.sortdirection = !this.sortdirection;
       		document.getElementById('sortBy' + this.currentsort).style.fontWeight = "";
       		document.getElementById('sortBy' + type).style.fontWeight = "bold";
	    		
       		this.currentsort = type;
       		this.updateResults();
        }

    	Hotels.prototype.sort = function() {
    		if (this.hotels.length == 0)
    			return;
        	//GLog.write("Sort: " + this.currentsort);
    		var sortfunction = discountcompare;
    		if (this.currentsort == "Price")
    			sortfunction = pricecompare;
    		else if (this.currentsort == "Name")
    			sortfunction = namecompare;
    		else if (this.currentsort == "Rate")
    			sortfunction = ratingcompare;
        	this.hotels.sort(sortfunction);
        	
    		if (this.currentsort == "Discount") {
   				var hotelsByPrice = [];
   				var hotelsBest = [];
	           	for (var i = 0; i < this.hotels.length; ++i) {
	           		var hotel = this.hotels[i];
	           		if (hotel.discount == 0) {
				    	hotelsByPrice.push(this.hotels[i]);
	           		}
           		}
        		hotelsByPrice.sort(pricecompare);
				for (var i = 0; i < hotelsByPrice.length || i < this.hotels.length; ++i) {
					if (i < this.hotels.length) {
						var hotel = this.hotels[i];
						if (hotel.discount > 0)
							hotelsBest.push(hotel);
					}
					if (i < hotelsByPrice.length) {
						var hotel = hotelsByPrice[i];
						hotelsBest.push(hotel);
					}
				}
				this.hotels = hotelsBest;
    		}
    	}
		
        function pricecompare(hotel1, hotel2) {
        	//GLog.write("Compare: " + hotel1.price + ", " + hotel2.price);
            var result = hotel1.price - hotel2.price;
            return result;
        }

        function namecompare(hotel1, hotel2) {
            var result = hotel1.title.localeCompare(hotel2.title);
			return result;
        }

        function ratingcompare(hotel1, hotel2) {
            var result = hotel1.rating - hotel2.rating;
            return 0 - result;
        }

        function discountcompare(hotel1, hotel2) {
            var result = hotel1.discount - hotel2.discount;
            return 0 - result;
        }
        
    	function HotelIcon() {
	    }
	    
	    HotelIcon.prototype = new GOverlay();
	
		// Create color matrix
		HotelIcon.colorArray = ["#7DBEFF", "#00FF00", "#00CC33", "#99CC00", "#E1E701", "#FFFF00", "#FF9900", "#FF6600", "#FF0000", "#D90000"];
	
	    HotelIcon.prototype.setColor = function(color) {
	        this.color_ = Math.min(color || 0, HotelIcon.colorArray.length - 1);
	    }
	
	    // Creates the DIV representing this rectangle.
	    HotelIcon.prototype.initialize = function(map) {
			if (this.available && this.price)
				this.setColor((this.price / 50 + 1) | 0);
			else 
				this.setColor(0);
	
		  var div = document.createElement("div");
		  div.style.background = HotelIcon.colorArray[this.color_];
		  div.style.cursor = "pointer";
		  div.style.position = "absolute";
		  div.style.zIndex = this.color_ == 0 ? 0 : HotelIcon.colorArray.length - this.color_;
	      map.getPane(G_MAP_MARKER_PANE).appendChild(div);
			
		  var priceDiv = document.createElement("div");
		  if (this.price)
			  priceDiv.innerHTML = this.min_price;
			  
		  var flagDiv = document.createElement("div");
		  flagDiv.setAttribute('class', 'flag');
		  flagDiv.appendChild(priceDiv);
		  div.appendChild(flagDiv);
		  
	      if (priceDiv.offsetWidth < 26) 
	  	  	  priceDiv.style.width = "26px";
	
	      var width = flagDiv.offsetWidth;
	      var height = flagDiv.offsetHeight; 
		  var divBlank = document.createElement("div");
		  divBlank.style.position = "absolute";
		  divBlank.style.top = "0";
		  divBlank.style.left = "0";
		  divBlank.innerHTML = '<img src="http://www.hotelguide.com/img/blank.gif" width="' + width + '" height="' + height +'"/>';
		  div.appendChild(divBlank);
	      
		  var div0 = document.createElement("div");
		  div0.setAttribute('class', 'flag');
		  div0.style.position = "absolute";
		  div0.style.zIndex = this.color_ == 0 ? 0 : HotelIcon.colorArray.length - this.color_;
	      map.getPane(G_MAP_MARKER_PANE).appendChild(div0);
	      
		  var div2 = document.createElement("div");
		  div2.setAttribute('class', 'prc');
		  div2.style.position = "absolute";
	      map.getPane(G_MAP_MARKER_SHADOW_PANE).appendChild(div2);
	      
	      this.map_ = map;
	      this.div0_ = div0;
	      this.div_ = div;
	      this.div2_ = div2;
	      this.geo_ = new GLatLng(this.lat, this.lng);
	
	      this.clickH_ = GEvent.bindDom(this.div_, "click", this, this.clicked);
	      this.mouseoverH_ = GEvent.bindDom(this.div_, "mouseover", this, this.mouseover);
	      this.mouseoutH_ = GEvent.bindDom(this.div_, "mouseout", this, this.mouseout);
	    }
	
	    HotelIcon.prototype.remove = function() {
	  		GEvent.removeListener(this.clickH_);
	  		GEvent.removeListener(this.mouseoverH_);
			GEvent.removeListener(this.mouseoutH_);
	    	this.div0_.parentNode.removeChild(this.div0_);
	      	this.div_.parentNode.removeChild(this.div_);
	    	this.div2_.parentNode.removeChild(this.div2_);
	    }
	
	    HotelIcon.prototype.copy = function() {
	      return new HotelIcon();
	    }
	
	    HotelIcon.prototype.clicked = function() {
	    	if (this.hotels.openInfoWindow) {
	    		this.map_.openInfoWindowHtml(this.getLatLng(), this.getPopupText(), {maxWidth: 300});
	    	}
	    	else {
	    		this.openDetails();
	        }
	      }

	    HotelIcon.prototype.openDetails = function() {
		       	var win = this.hotels.openInNewWindow ? window.open() : window;
		        win.location = this.getFullURL();
        }

	    HotelIcon.prototype.getFullURL = function() {
	       	var url = "http://www.hotelguide.com" + this.url;
	       	if (this.searchId)
	       		url += (url.indexOf('?') == -1 ? '?' : '&') + 'sid=' + this.searchId;
       		return url; 
	    }
	
	    HotelIcon.prototype.displayRating = function() {
	    	return '<img src="http://www.hotelguide.com/img/star' + this.rating + '.gif" width="60" height="10">';
	    }

	    HotelIcon.prototype.getPopupText = function() {
	  		var average = false;
	   		var tipText = '';
	  		if (this.image)
	  			tipText += '<a href="' + this.getFullURL() + '" target="_blank" style="text-decoration:none;"><img src="' + this.image + '"width="64" height="64" style="float:left; margin-right:5px;" />';
			tipText += '<p style="color:#174D82;font-weight:bold;margin:0">' + this.title + this.displayRating() + '</p>';
	  		tipText +='<p style="border-top:1px solid #999; font-size:11px; color:#999;">' + this.address + '</p></a>';
			if (this.available) {
	  			tipText += '<p style="width:100%;clear:left;float:left;font-size:11px;color:#000;font-weight:bold;background:#C8E4FF;padding:3px;">from: ' + this.min_price + '<span style="float:right;font-size:12px;"><a href="' + this.getFullURL() + '" target="_blank">details</a></span></p>';
			}
	  		else if (this.min_price != undefined) {
	  			average = true;
	  			tipText += '<p style="clear:left;font-size:11px;color:#000;font-weight:bold;background:#CCC;padding:3px;">' + this.min_price;
	          	if (this.max_price != this.min_price && this.max_price != undefined)
	      			tipText += ' - ' + this.max_price;
	  			tipText += '*<span style="float:right;font-size:12px;"><a href="' + this.getFullURL() + '" target="_blank">details</a></span></p>';
	  		}
	  		else { 
  				tipText += '<div style="float:right;"><a href="' + this.getFullURL() + '" target="_blank">details</a></div>';
			}
				  			

			if (average)
	  			tipText += '<p style="font-size:11px;color:#999;">* Average price range of past bookings</p>';
	
			return tipText;
	    } 
	    
	    HotelIcon.prototype.getTipText = function() {
	    	if (this.hotels.openInfoWindow) {
		   		var tipText = '<p style="color:#174D82;font-weight:bold;margin:0">' + this.title + this.displayRating() + '</p>';
				if (this.available) {
		  			tipText += '<p style="font-size:11px;color:#fff;font-weight:bold;background:#174D82;margin-top:2px;margin-bottom:0;text-align:center;">from: ' + this.min_price + '</p>';
				}
		  		else if (this.min_price != undefined) {
		  			average = true;
		  			tipText += '<p style="font-size:11px;color:#000;font-weight:bold;background:#CCC;margin-top:2px;margin-bottom:0;text-align:center;">' + this.min_price;
		          	if (this.max_price != this.min_price && this.max_price != undefined)
		      			tipText += ' - ' + this.max_price;
		  			tipText += '*</p>';
		  		} 
				if (average)
		  			tipText += '<p>* Average price range of past bookings</p>';
	    	}
	    	else {
		  		var average = false;
		   		var tipText = '<table style="width:100%">';
		   		if (this.hotels.popupTitle)
		   			tipText += '<tr><td colspan="2" style="background:#174D82;color:#fff;">hotelguide.com</td></tr>'
	   			tipText += '<tr valign="top">';
		  		if (this.image)
		  			tipText += '<td><img src="' + this.image + '"width="64" height="64" /></td>';
				tipText += '<td><p style="color:#174D82;font-weight:bold;margin:0">' + this.title + this.displayRating() + '</p>';
		  		tipText +='<p style="border-top:1px solid #999;">' + this.address + '</p>';
				if (this.available) {
		  			tipText += '<p style="font-size:11px;color:#000;font-weight:bold;background:#CCC;margin-top:2px;margin-bottom:0;text-align:center;">from: ' + this.min_price + '</p>';
				}
		  		else if (this.min_price != undefined) {
		  			average = true;
		  			tipText += '<p style="font-size:11px;color:#000;font-weight:bold;background:#CCC;margin-top:2px;margin-bottom:0;text-align:center;">' + this.min_price;
		          	if (this.max_price != this.min_price && this.max_price != undefined)
		      			tipText += ' - ' + this.max_price;
		  			tipText += '*</p>';
		  		} 
				tipText += '</td></tr>';
				if (average)
		  			tipText += '<tr><td colspan="2">* Average price range of past bookings</td></tr>';
				tipText += '</table>';
			}
	
			return tipText;
	    } 
	
	    HotelIcon.prototype.getLatLng = function() {
	        return new GLatLng(this.lat, this.lng);
	    }
	    
	    HotelIcon.prototype.mouseover = function() {
	        if (this.hotels.tooltip) {
	        	if (!this.map_.getBounds().containsLatLng(this.geo_)) {
	        		//this.map_.setCenter(this.geo_);
	        		return;
        		}
	        	this.hotels.tooltip.innerHTML = this.getTipText();
	      		var offset = this.map_.fromLatLngToContainerPixel(this.geo_);
	      		var viewportWidth = getViewportDimensions().width;
	      		var mapLeft = viewportOffset(this.map_.getContainer()).left; 
	      		
	      		var left = offset.x;
	      		if (left + this.hotels.tooltip.offsetWidth + mapLeft > viewportWidth)
	      			left -= this.hotels.tooltip.offsetWidth;
	      		var top = offset.y - this.height - this.hotels.tooltip.offsetHeight;
	      		var parentOffset = cumulativeOffset(this.map_.getContainer());
	      		left += parentOffset.left; 
	      		top += parentOffset.top;
	      		
	      		this.hotels.tooltip.style.visibility = 'visible';
	      		this.hotels.tooltip.style.left = '' + left + 'px';
	      		this.hotels.tooltip.style.top = '' + top + 'px';
	        }
	      }
	
	    HotelIcon.prototype.mouseout = function() {
	        if (this.hotels.tooltip) {
	        	this.hotels.tooltip.style.visibility = 'hidden';
	        	this.hotels.tooltip.style.left = '0px';
	        	this.hotels.tooltip.style.top = '0px';
	        }
	      }
	    
	    HotelIcon.prototype.redraw = function(force) {
	      // We only need to redraw if the coordinate system has changed
	      if (!force) return;
	
	      var offset = this.map_.fromLatLngToDivPixel(this.geo_);
	
		  this.height = this.div0_.clientHeight;
		  this.left = offset.x;
		  this.top = offset.y - this.height;
	
	      this.div0_.style.left = this.left + "px";
	      this.div0_.style.top = this.top + "px";
			  
	      this.div_.style.left = this.left + "px";
	      this.div_.style.top = this.top + "px";
	
	      this.div2_.style.left = this.left + "px";
	      this.div2_.style.top = this.top + "px";
	    }
	
	    function HotelGroup() {
	    }
	    
	    HotelGroup.prototype = new GOverlay();
	
	    // Creates the DIV representing this rectangle.
	    HotelGroup.prototype.initialize = function(map) {
	
		  var div = document.createElement("div");
		  div.style.cursor = "pointer";
		  div.style.position = "absolute";
		  //div.style.border = "1px solid red";
	      map.getPane(G_MAP_MARKER_PANE).appendChild(div);
	
	      var iconSize = 30;
	      if (this.size >= 1000 )
	          iconSize = 70;
	      else if (this.size >= 100 )
	          iconSize = 50;
	      else if (this.size >= 10 )
	          iconSize = 40;
	      
		  var icon = document.createElement("img");
		  if (Browser.IE) {
			  icon.src = 'http://www.hotelguide.com/img/blank.gif';
			  icon.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src = 'http://www.hotelguide.com/img/mapicons/halo3.png')";
		  }
		  else {
		  	icon.src = 'http://www.hotelguide.com/img/mapicons/halo3.png';
		  }
		  
		  icon.width = iconSize;
		  icon.height = iconSize;
		  icon.style.position = "relative";
		  div.appendChild(icon);
	      
		  var sizeDiv = document.createElement("div");
		  sizeDiv.style.color = "#fff";
		  sizeDiv.style.position = "absolute";
		  sizeDiv.style.fontSize = "9px";
		  sizeDiv.innerHTML = this.size;
		  div.appendChild(sizeDiv);
		  sizeDiv.style.left = "" + (icon.offsetWidth - sizeDiv.offsetWidth) / 2 + "px";
		  sizeDiv.style.top =  "" + (icon.offsetHeight - sizeDiv.offsetHeight) / 2 + "px";
		  
	      
	      this.map_ = map;
	      this.div_ = div;
	      this.geo_ = new GLatLng(this.lat, this.lng);
	
	      this.clickH_ = GEvent.bindDom(this.div_, "click", this, this.clicked);
	    }
	
	    HotelGroup.prototype.remove = function() {
	  		GEvent.removeListener(this.clickH_);
	      	this.div_.parentNode.removeChild(this.div_);
	    }
	
	    HotelGroup.prototype.copy = function() {
	      return new HotelGroup();
	    }
	
	    HotelGroup.prototype.clicked = function() {
	        var bounds = new GLatLngBounds(new GLatLng(this.latLow, this.lngLeft), new GLatLng(this.latUp, this.lngRight));
	       	this.map_.setCenter(bounds.getCenter(), this.map_.getBoundsZoomLevel(bounds));
	    }
	
	    HotelGroup.prototype.getLatLng = function() {
	        return new GLatLng(this.lat, this.lng);
	    }
	
	    HotelGroup.prototype.redraw = function(force) {
	      // We only need to redraw if the coordinate system has changed
	      if (!force) return;
	
	      var offset = this.map_.fromLatLngToDivPixel(this.geo_);
	
	      var height = this.div_.offsetHeight;
		  var width = this.div_.offsetWidth;
		  this.left = offset.x - width / 2;
		  this.top = offset.y - height / 2;
	
	      this.div_.style.left = this.left + "px";
	      this.div_.style.top = this.top + "px";
	    }
	    
	    function HotelIconBasic() {
	    }
	
	    HotelIconBasic.prototype = new HotelIcon();
	
	    // Creates the DIV representing this rectangle.
	    HotelIconBasic.prototype.initialize = function(map) {
			if (this.price)
				this.setColor((this.price / 50 + 1) | 0);
			else 
				this.setColor(0);
			
	        this.map_ = map;
	        this.geo_ = new GLatLng(this.lat, this.lng);
	        var icon;
	        if (this.hotels.icon) {
	            icon = this.hotels.icon;
	        }
	        else {
	    		icon = new GIcon(this.hotels.baseIcon);
	    		icon.image = "http://www.hotelguide.com/img/mapicons/bubble_" + this.color_ + (this.available || !this.hotels.search?'':'a') + ".png";
	        }                
	    	this.marker = new GMarker(this.geo_, {icon: icon});
	        GEvent.bind(this.marker, "click", this, this.clicked);
	        GEvent.bind(this.marker,"mouseover", this, this.mouseover);
	        GEvent.bind(this.marker,"mouseout", this, this.mouseout);
	        this.marker.initialize(map);
		    this.height = this.marker.getIcon().iconSize.height;
	    }
	
	    HotelIconBasic.prototype.remove = function() {
	        this.marker.remove();
	    }
	
	    HotelIconBasic.prototype.copy = function() {
	      return this.marker.copy();
	    }
	
	    HotelIconBasic.prototype.redraw = function(force) {
	        this.marker.redraw(force);
	    }
	    
		return {
			HotelLayer : HotelLayer,
			Hotels : Hotels,
			HotelsLegend : HotelsLegend,
			HotelIconBasic : HotelIconBasic,
			getViewportDimensions: getViewportDimensions,
			viewportOffset: viewportOffset
		}
})(); 
//]]>
