
////
// Populates a list of hotels with room combinations and prices
// Requires prototype and Google Maps
//
// @version $Id: hotel-list.js,v 1.86 2008/04/25 11:57:16 raptor Exp $
//

var storeHotelSelectIndex = 0;
var storeHotelSelects;

function storeHotelSelect ()
{
    var id = 'flightSelectIndex' + storeHotelSelectIndex;
    storeHotelSelectIndex++;
    storeHotelSelects.push(id);
    return id;
}


IdCache = Class.create();

IdCache.prototype = {
    initialize: function(current_element)
    {
	this.cache = Object();
	var all = current_element.getElementsByTagName("*");
	for (var g=0; g<all.length; g++)
	{
	    if (all[g].getAttribute && all[g].getAttribute("id"))
	    {			 
		this.cache[all[g].getAttribute("id")] = all[g];
	    }
	}
    },
    set: function(id, new_id)
    {
	this.cache[new_id] = this.cache[id];
	delete this.cache[id];
    },
    get: function(id)
    {
	return this.cache[id];
    }
};

HotelList = Class.create();


HotelList.prototype = {
    
    /**
     * Construct a new HotelList object
     *
     */
   

    initialize: function(method, data) 
    {
	this.method        = method;
	this.data          = data;
	this.url           = '/services/hotel/get_hotels.cgi';
	
	//data needed for internal use - not ajax call
	if(method == 'show_all_hotels')
	{
	  this.url           = '/services/hotel/get_all_hotels.cgi';
	}

	this.data['hotels_per_step'] = this.data['hotels_per_step'] ? Number(this.data['hotels_per_step']) : 20;

	this.maxHotels         = this.data['max_hotels'] || '';
        this.hotelId           = this.data['hotel_id'] || '';
	this.useSteps          = this.data['use_steps'] && this.data['use_steps'] != '' ? this.data['use_steps'] : '';
	this.hotelsPerStep     = this.data['hotels_per_step'];
	this.site              = this.data['site'];
	this.partner           = this.data['partner'];
	this.ratingPath        = this.data['rating_path'];
	this.buttonPath        = this.data['button_path'];
	this.shortListInitMax  = this.data['shortListInitMax'] || 12;
	this.shortListColumns  = this.data['shortListInitColumns'] || 2;
	this.priceFormatting   = this.data['priceFormatting'] || '';
	this.alwaysShowPager   = this.data['alwaysShowPager'] || 'yes';
	this.sortBy            = this.data['sort_by_default'] || '';
    this.useRoomCombinationStripes = this.data['use_room_combination_stripes'] || 'no';

	this.preferedHotelName     = this.data['hotel_name'];
	this.reload_url    = this.data.reload_url;
	delete this.data.reload_url;
        this.filter        = new Array();
	this.categoryData = new Object();
	this.categoryIcons = new Object();
	this.ratings       = new Object();
	
	this.cacheId       = '';
	this.selectedHotel = '';
	this.saveMaxPrice  = '';
	this.saveSliderPrice = '';
	this.steps         = '';
	this.tabs          = 0;
	this.filterHasBeenInit = '';
	this.stepsHasBeenInit = '';
        this.categoriesHasBeenInit = '';
	this.filterOn = '0';
	this.topSecret = '0';
	this.onlyTopSecret = this.data['onlyTopSecret'] || '0';
	this.selectedHotelId  = '';
	this.selectedMinPrice = '';
	this.showCheapest = this.data.show_cheapest;
        this.cheapestHotelId = '';
	this.mouseovertooltip = undefined;
	this.markerArray   = {};
	this.map = undefined;
	if(this.hotelId != '')
        {
	    this.addFilter('hotel:'+this.hotelId);
	    if($('allHotelsUrl') != null && this.onlyTopSecret == '0')
		{
		    Element.show('allHotelsUrl');
		}
	}
	
	if(this.onlyTopSecret == '1')
	    this.toggleTopSecretHeaders(true);
	    
	// Bind filter listeners
	if($('filterRating0'))
	  Event.observe($('filterRating0'),            'click', this.onFilter.bindAsEventListener(this));
	if($('filterRating1'))
	  Event.observe($('filterRating1'),            'click', this.onFilter.bindAsEventListener(this));
	if($('filterRating2'))
	  Event.observe($('filterRating2'),            'click', this.onFilter.bindAsEventListener(this));
	if($('filterRating3'))
	  Event.observe($('filterRating3'),            'click', this.onFilter.bindAsEventListener(this));
	if($('filterRating4'))
	  Event.observe($('filterRating4'),            'click', this.onFilter.bindAsEventListener(this));
	if($('filterRating5'))
	  Event.observe($('filterRating5'),            'click', this.onFilter.bindAsEventListener(this));

	// Bind sort listeners
	if($('sortByDropDown') != null)
        {
	   Event.observe($('sortByDropDown'),        'change', this.onFilter.bindAsEventListener(this));
	}
	if($('sortByName') != null)
        {
	   Event.observe($('sortByName'),            'click', this.onFilter.bindAsEventListener(this));
	}
	if($('sortByPrice')!= null)
        {
	   Event.observe($('sortByPrice'),            'click', this.onFilter.bindAsEventListener(this));
	}
	if($('sortByPreferred')!= null)
        {
	   Event.observe($('sortByPreferred'),            'click', this.onFilter.bindAsEventListener(this));
	}


	if($('sortByCustomerRating')!= null)
        {
	   Event.observe($('sortByCustomerRating'),            'click', this.onFilter.bindAsEventListener(this));
	}
	
	if($('sortByMostSold')!= null)
        {
	   Event.observe($('sortByMostSold'),            'click', this.onFilter.bindAsEventListener(this));
	}	
	

	if($('allHotelsUrl')!= null)
        {
	   Event.observe($('allHotelsUrl'),            'click', this.askForAllHotels.bindAsEventListener(this));
	}
	
	// Remove hotelInfo if it exists.
	if($('hotelListHotelInfo') != null)
	{
	    this.hotelInfoTemplate = $('hotelListHotelInfo');
	    $('hotelListHotelInfo').parentNode.removeChild($('hotelListHotelInfo'));
	}

	// Remove hotelInfo if it exists.
	if($('hotelListHotelInfoSearch') != null)
	{
	    this.hotelInfoSearchTemplate = $('hotelListHotelInfoSearch');
	    $('hotelListHotelInfoSearch').parentNode.removeChild($('hotelListHotelInfoSearch'));
	}
	// Remove combination template from document
	if($('hotelListCombination') != null)
	{
	    this.combinationTemplate = $('hotelListCombination');
	    this.combinationTemplate.removeAttribute('id');
	    Element.remove(this.combinationTemplate);
	    	    		
	    this.combinationSecondChoiseTemplate = $('hotelListCombinationSecondChoise');
	    this.combinationSecondChoiseTemplate.removeAttribute('id');
	    Element.remove(this.combinationSecondChoiseTemplate);
	}

	// Separator for unrecommeded hotels
	if ($('hotelUnrecommended') != null)
	{
	    this.unrecommendedSeparator = $('hotelUnrecommended');
	    Element.remove(this.unrecommendedSeparator);
	}

	// Get hotel template and its parent
	
	this.hotelTemplate = $('hotelList');
	this.hotelParent   = $('hotelListParent');
	
	// Remove template from document
	if(this.hotelParent && this.hotelTemplate)	
	  this.hotelParent.removeChild(this.hotelTemplate);

	// If steps is used - get the template and remove it from the document
	
	if(this.useSteps == 'yes' && $('hotelListStep') != null)
	{
	    this.hotelStepTemplate = $('hotelListStep');
	    this.hotelStepParent   = this.hotelStepTemplate.parentNode;
	    this.hotelStepParent.removeChild(this.hotelStepTemplate);
	}
	
	
	// Get hotel template and its parent
	if($('categoryFilters') != null)
	{
	    this.categoryFiltersTemplate = $('categoryFilters');
	    this.categoryFiltersParent   = this.categoryFiltersTemplate.parentNode;
	    // Remove template from document
	
	    this.categoryFiltersParent.removeChild(this.categoryFiltersTemplate);
	    	}
	if($('categoryDesc') != null)
	{
	    this.categoryDescTemplate    = $('categoryDesc');
	    this.categoryDescParent   = this.categoryDescTemplate.parentNode;
	    // Remove template from document
	
	    this.categoryDescParent.removeChild(this.categoryDescTemplate);
	}

//        TNDocument.hideAllActivates();
	if($('hotelShortListShowMore'))
	  Event.observe($('hotelShortListShowMore'), 'click', this.toggleAllShortList.bindAsEventListener(this));

	// Get hotels from web service and populate hotel list
	this.getHotelList();
	
    },
    
    /*
     * 
     */
    getHotelInfo : function(hotelId)
    {
	new Ajax.Request('/' + this.site + '/hotel/cgi-bin/show_hotel_info.cgi', 
	    {
	    parameters:  
			 'hotel_id=' + hotelId + '&'+
			 'other_template=simple_show_hotel.html&'+
			 'window_shopper=yes',
		            
		onSuccess: this.addHotelInfo.bind(this),
		onFailure: this.showError.bind(this)
	    });
    },
    
    /*
     * 
     */
    getHotelList : function()
    {
	if(this.useSteps == 'yes' && $('hotelListStepParent') != null)
	{
	    Element.addClassName($('hotelListStepParent'), 'hidden');
	}
	if ($('foundHotels'))
	  Element.hide('foundHotels');

	new Ajax.Request(this.url, 
	    {
	    parameters:  $H(this.data).toQueryString() +
		         '&max_hotels='+this.maxHotels +
			 '&filter='+this.getFilterAsString() +
			 '&cache_id='+this.cacheId+
			 '&steps='+this.steps+'&'+
			 'sort_by=' + this.sortBy+'&'+
			 'only_top_secret=' + this.onlyTopSecret,
		            
		onSuccess: this.populate.bind(this),
		onFailure: this.showError.bind(this)
	    });
    },

    addHotelInfo : function(transport)
    {
	var hotelInfo = transport.responseText;

	var hotelInfoNode = this.hotelInfoTemplate.cloneNode(true);
	this.hotelParent.appendChild(hotelInfoNode);

	hotelInfoNode.innerHTML = hotelInfo;

	var hotelInfoSearch = this.hotelInfoSearchTemplate.cloneNode(true);
	this.hotelParent.appendChild(hotelInfoSearch);

	if($('hotelListInfoSearchLink') != null)
	{
	    var searchLink   = '/'+this.site+'/hotel/cgi-bin/hotel_search_box.cgi?dh_dest_id='+this.data['dh_dest_id'];
	    searchLink += '&hotel_id=' + this.selectedHotelId;
	    searchLink += '&adults=' + this.data['adults'];
	    searchLink += '&children=' + this.data['children'];
	    searchLink += '&children_age=' + this.data['children_age'];
	    $('hotelListInfoSearchLink').href = searchLink;
	}

	//Added because of all_hotels when only oen hotel_id is set
	if($('hotelListSearchLink') != null)
	    {
		var searchLink   = '/'+this.site+'/hotel/cgi-bin/hotel_search_box.cgi?dh_dest_id='+this.data['dh_dest_id'];
		searchLink += '&hotel_id=' + this.data['hotel_id'];
		searchLink += '&adults=' + this.data['adults'];
		searchLink += '&children=' + this.data['children'];
		searchLink += '&children_age=' + this.data['children_age'];
		searchLink += '&rooms=' + this.data['rooms'];
		searchLink += '&partner=' + this.data['partner'];
		var searchLinkId = "hotelListSearchLink"+this.data['hotel_id'];;
		$('hotelListSearchLink').href = searchLink;
		$('hotelListSearchLink').id   = searchLinkId;
	    }
	CreateSearchLinks();
	if (this.selectedMinPrice == '')
	{
	    //Remove from price if it exists
	    if($('hotelListInfoPrice') != null)
	    {
		Element.hide($('hotelListInfoPrice'));
	    }
	}
	else
	{
	    if($('hotelListInfoMinPrice') != null)
	    {
		$('hotelListInfoMinPrice').innerHTML = this.selectedMinPrice;
	    }
	}
	//Hide categories and activate link to all hotels in destination

	if($('sortHotels') != null)
	{
	    Element.hide('sortHotels');
	}	
	if($('sorting') != null)
	{
	    Element.hide('sorting');
	}	
    },
    
    populate : function(transport)
    {
	try {
	var hotels           = transport.responseXML.getElementsByTagName('hotel');
	var status           = transport.responseXML.getElementsByTagName('status')[0].firstChild.nodeValue;
	var filterCategories = transport.responseXML.getElementsByTagName('filterCategory');
        var ratingsNode      = transport.responseXML.getElementsByTagName('ratings');
	var numHotelsNodes   = transport.responseXML.getElementsByTagName('numHotels');
      	var numHotels        = (numHotelsNodes.length == 0) ? 0 : numHotelsNodes[0].firstChild.nodeValue;
	var currentStepNodes  = transport.responseXML.getElementsByTagName('steps');
	var currentStep      = (currentStepNodes.length == 0) ? '1-?' : currentStepNodes[0].firstChild.nodeValue;
	storeHotelSelects =  new Array();
	if (numHotels < 2)
	{
	    if($('sorting') != null)
		{
		    Element.hide('sorting');
		}
	    if($('ratings') != null)
		{
		    Element.hide('ratings');
		}
	}
	else
	    {
		if($('sorting') != null)
		{
		    Element.show('sorting');
		}
		if($('ratings') != null)
		{
		    Element.show('ratings');
		}
	    }
	this.cheapestHotelId = '';
	var cheapestHotelIdElements = transport.responseXML.getElementsByTagName('cheapestHotelId');
                                                                                 
	if (cheapestHotelIdElements != null && cheapestHotelIdElements.length > 0 && cheapestHotelIdElements[0].hasChildNodes() )
	{
	    this.cheapestHotelId = cheapestHotelIdElements[0].firstChild.nodeValue;
	}

	var isPackage = 0;
	var isPackageElements = transport.responseXML.getElementsByTagName('isPackage');
                                                                                 
	if (isPackageElements != null && isPackageElements.length > 0 && isPackageElements[0].hasChildNodes() )
	{
	    isPackage = isPackageElements[0].firstChild.nodeValue;
	}
	
	var hasTopSecretElements = transport.responseXML.getElementsByTagName('hasTopSecret');

	if (hasTopSecretElements != null && hasTopSecretElements.length > 0 && hasTopSecretElements[0].childNodes.length > 0)
	{
	    this.topSecret = hasTopSecretElements[0].firstChild.nodeValue;
	}

	var oneHotelMode = 0;
	var errorMsg ='';

	var aErrorMsg = transport.responseXML.getElementsByTagName('message');
	if (aErrorMsg.length > 0 && aErrorMsg[0].hasChildNodes())
	{
	    errorMsg = aErrorMsg[0].firstChild.nodeValue;
	}

	// Remove old loops
	TNGui.activate('hotelShortList', document, true);
        TNDocument.clearLoop('hotelShortListRow');
        var shownInShortList = 0;

	if(numHotels == 1 && this.method == 'show_all_hotels')
	{
	    oneHotelMode = 1;
	    if($('allHotelsUrl') != null)
	   {
	       Element.show('allHotelsUrl');
	   }
	}

	// Update num hotels
        this.setInnerHTML('numHotels', numHotels);
	this.setInnerHTML('stepInfoTotal', numHotels);
	this.setInnerHTML('stepInfoCurrent', currentStep);
	//If no hotels with hotel name found.

	if(errorMsg != '' && errorMsg == 'no_hotels_with_name_found')
	{
	    $('hotelListErrorNoHotelName').style.display = 'block';
	}
	if(errorMsg != '' && errorMsg == 'selected_hotel_not_available')
	{
	    $('hotelListErrorSelectedNotAvailable').style.display = 'block';
	}
	if(this.preferedHotelName != '' && errorMsg == '')
	{
	    if ($('allHotelsUrl') && this.onlyTopSecret == '0')
	    {
	    Element.show('allHotelsUrl');
	    }
	}

	if(status == 'error')
	{
	    // If error because no hotels returned.
	    if ($('hotelListError'))
	    {
		$('hotelListError').style.display = 'block';
	    }
	    if ($('allHotelsUrl'))
	    {
		Element.show('allHotelsUrl');
	    }
	}
	else if (status == 'unfinished')
	{
	    var activates = transport.responseXML.getElementsByTagName('activates')[0].firstChild.nodeValue;
	    var search_id = transport.responseXML.getElementsByTagName('search_id')[0].firstChild.nodeValue;
	    
	    location.href = this.reload_url + '&activates=' + activates + '&search_id=' + search_id;
	}
	
	// else show the hotels

	else
	{
	    if ($('foundHotels'))
	      Element.show('foundHotels');
	    
	    this.cacheId = transport.responseXML.getElementsByTagName('cache_id')[0].firstChild.nodeValue;
	    
	    var minPrice = 0;
	    var maxPrice = 0;
	    // Add all the categories
	    if(1) //Activate if we add categories
	    {
		for (var z = 0; z < filterCategories.length; z ++)
		{
		    var category     = filterCategories[z];
		    var categoryId   = this.getNodeValue(category, 'id', '0');

		    // Add category to the filter and check the box
		    this.addFilter("category:"+categoryId); 
			    
		    var categoryData =
		    {
                      id:   categoryId,
	   	      key:  this.getNodeValue(category, 'key', ''),
		      name: this.getNodeValue(category, 'categoryName', ''),
		      desc: this.getNodeValue(category, 'categoryDescription', '')				
		    };
		    
                    // Store for later use for the individual hotels
		    this.categoryData[categoryId] = categoryData;
		    
		    // Create icon for category
		    this.categoryIcons[categoryId] = createIcon(this.site,categoryId,this.partner);

		    if(this.categoriesHasBeenInit != 'yes' && 
		       this.categoryFiltersTemplate != null)
		    {
			// Clone the hotel node and put it in the document
			var categoryFilter = this.categoryFiltersTemplate.cloneNode(true);
			var categoryFilterIds = new IdCache(categoryFilter);

			setElementContent(categoryFilterIds, 'categoryFilterLabel', categoryData.name);
			setElementContent(categoryFilterIds, 'categoryFilterDesc',  categoryData.desc);
			var i = setElementContent(categoryFilterIds, 'categoryFilter',      'category:'+categoryData.id);
			i.id = 'filterCategory'+categoryData.id;
			i.checked = true;
			this.categoryFiltersParent.appendChild(categoryFilter);
		       
			Event.observe(i, 'click', this.onFilter.bindAsEventListener(this));

			Element.show(this.categoryFiltersParent);
		    }
		    if(this.categoriesHasBeenInit != 'yes' && 
		       this.categoryDescTemplate != null && categoryData.key != 'not_classified')
		    {
			var categoryDesc = this.categoryDescTemplate.cloneNode(true);
			var categoryDescIds = new IdCache(categoryDesc);
			var label = setElementContent(categoryDescIds, 'categoryDescLabel', categoryData.name);
			label.setAttribute('class', 'tabheadgrey preferred_'+categoryData.id);
			label.setAttribute('className', 'tabheadgrey preferred_'+categoryData.id);
	
			setElementContent(categoryDescIds, 'categoryDescText',  categoryData.desc);
			setElementContent(categoryDescIds, 'categoryDescLink', "javascript:dynpop('/"+this.site+"/hotel/hotel_classes_popup_info.html#"+ categoryData.id+"');",'href' );
			categoryDesc.removeAttribute('id');
			this.categoryDescParent.appendChild(categoryDesc);
			Element.show(this.categoryDescParent);
		    }
		}
		this.categoriesHasBeenInit = 'yes';    
	    }

	    //Take out the number of hotels and if more then allowed create tabs.
	    if(this.useSteps == 'yes' && $('hotelListStepParent') != null)
            {
		if(numHotels > this.hotelsPerStep)
		{
		    if (this.stepsHasBeenInit == '')
		    {	
			//start with removing the old tabs
			var numberOfHotels = numHotels;
			var numberOfTabs   = parseInt(numberOfHotels/this.hotelsPerStep);
			
			if((numberOfTabs * this.hotelsPerStep) < numberOfHotels)
			{
			    numberOfTabs ++;
			}
			
			this.tabs = numberOfTabs;

			this.addStep('First', 1, numHotels);
                        this.addStep('Prev', 0, numHotels);
			
			for(var i = 1; i <= numberOfTabs; i++)
			{
			    if(this.steps == '')
				this.steps = i;

			    this.addStep('SelectPage', i, numHotels);
			}
			
			this.addStep('Next', 0, numHotels);
			this.addStep('Last',numberOfTabs, numHotels);

			this.stepsHasBeenInit = 'yes';
		    }
		    Element.removeClassName($('hotelListStepParent'), 'hidden');
		    this.showNonPageSteppers();
		    TNGui.showHide('hotelListStepsHolder');

		    this.markStep(true);
		}
	    }

	    var onlyTopSecretInResult = 1;

	    if(numHotels == 1 && this.method == 'show_all_hotels')
	    {
		var hotelNode   = hotels[0];
		this.selectedHotelId     = hotelNode.getElementsByTagName('hotel_id')[0].firstChild.nodeValue;		
		var aWindowShopperPrice  = hotelNode.getElementsByTagName('min_price');
		    
		if (aWindowShopperPrice.length > 0 && aWindowShopperPrice[0].hasChildNodes())
		    {		  
			this.selectedMinPrice = aWindowShopperPrice[0].firstChild.nodeValue;
		    }
		if ($('hotelListMinPrice'))
			{
				$('hotelListMinPrice').innerHTML = this.selectedMinPrice;
			}
		this.getHotelInfo(this.selectedHotelId);
		var rating  = '';
		var aRating = hotelNode.getElementsByTagName('rating');
		
		if (aRating.length > 0 && aRating[0].hasChildNodes())
		    {
			rating = aRating[0].firstChild.nodeValue;
		    }
		var longitude  = '';
		var aLongitude = hotelNode.getElementsByTagName('longitude');
		
		var latitude  = '';
		var aLatitude = hotelNode.getElementsByTagName('latitude');
		
		if (aLongitude.length > 0 && aLongitude[0].hasChildNodes())
		    {
			longitude = aLongitude[0].firstChild.nodeValue;
		    }
		
		if (aLatitude.length > 0 && aLatitude[0].hasChildNodes())
		    {
			latitude = aLatitude[0].firstChild.nodeValue;
		    }
		var aCategory = hotelNode.getElementsByTagName('category');
		var hotelIsTopSecret = false;
		if (aCategory.length > 0 && aCategory[0].hasChildNodes())
		    {
			category = aCategory[0].firstChild.nodeValue;
			
			if (category == '100')
			    {
				hotelIsTopSecret = true;
			    }
		    }
		
		var name        = hotelNode.getElementsByTagName('name')[0].firstChild.nodeValue;
		//if (!hotelIsTopSecret)
		if(window.GMap)
		    {
		addCustomMarker(latitude, longitude, name, rating, this.categoryData[category], hotelId, this.selectedMinPrice, this.site, this.ratingPath, this.markerArray,this.categoryIcons[category], this.priceFormatting,true);
		if (this.mapIsLoaded() )
		    this.map.setCenter(new GLatLng(latitude,longitude));
		    }
	    }
	    else
	    {
		// Don't show hotel categories, removed 2006-09-18 Men
		// block => none
		if($('categories') != null)
		{
		    Element.show('categories');
		}

		var hotelFragment = document.createDocumentFragment();
                var hotelShortListRow = TNDocument.getLoop('hotelShortListRow');
                var cheapestHotel;
		for (var i = 0; i < hotels.length; i++)
		{
		    // Get hotel data from XML
		    var hotelNode   = hotels[i];
		    var hotelId     = hotelNode.getElementsByTagName('hotel_id')[0].firstChild.nodeValue;
		    var bookingAgent= '';
		    var name        = hotelNode.getElementsByTagName('name')[0].firstChild.nodeValue;
		    var address     = '';
		    var category    = '';
		    var description = '';
		    var windowShopperPrice    = '';
		    var availability = '';
		    var customerRating = 0;
		    var customerComment = '';
		    var descriptionUrl = '';
		    var descriptionType = '';
		    var hotelIsTopSecret = false;
		    var cheapestPrice = 0;
		    
		    if ($(hotelId)) continue;

		    if (hotelNode.getElementsByTagName('first_unrecommended').length > 0
			&& this.unrecommendedSeparator != null)
			{
			    hotelFragment.appendChild(this.unrecommendedSeparator);
			}

		    var aAddress    = hotelNode.getElementsByTagName('address');
		    if (aAddress.length > 0 && aAddress[0].hasChildNodes())
			{
			    address = aAddress[0].firstChild.nodeValue;
			}
			
		    var aBookingAgent    = hotelNode.getElementsByTagName('booking_agent');
		    if (aBookingAgent.length > 0 && aBookingAgent[0].hasChildNodes())
			{
			    bookingAgent = aBookingAgent[0].firstChild.nodeValue;
			}

		    var aCustomerComment    = hotelNode.getElementsByTagName('customer_comment');
		    if (aCustomerComment.length > 0 && aCustomerComment[0].hasChildNodes())
			{
			    customerComment = aCustomerComment[0].firstChild.nodeValue;
			}
			
		    var aCustomerRating    = hotelNode.getElementsByTagName('customer_rating');
		    if (aCustomerRating.length > 0 && aCustomerRating[0].hasChildNodes())
			{
			    customerRating = this.getNumber(aCustomerRating[0].firstChild.nodeValue, 0);
			}
			
		    var aAvailability    = hotelNode.getElementsByTagName('availability');
	    		
		    if (aAvailability.length > 0 && aAvailability[0].hasChildNodes())
			{
			
			    availability = aAvailability[0].firstChild.nodeValue;
			}

		    var aBookingAgent    = hotelNode.getElementsByTagName('booking_agent');
	    		
		    if (aBookingAgent.length > 0 && aBookingAgent[0].hasChildNodes())
			{
			
			    bookingAgent = aBookingAgent[0].firstChild.nodeValue;
			}

		    var aWindowShopperPrice    = hotelNode.getElementsByTagName('min_price');
	    		
		    if (aWindowShopperPrice.length > 0 && aWindowShopperPrice[0].hasChildNodes())
			{
			    windowShopperPrice = aWindowShopperPrice[0].firstChild.nodeValue;
			}

			
		    var aCategory = hotelNode.getElementsByTagName('category');
		    if (aCategory.length > 0 && aCategory[0].hasChildNodes())
			{
			    category = aCategory[0].firstChild.nodeValue;

			    if (category == '100')
				{
				    hotelIsTopSecret = true;
				}
			}

		    if (! hotelIsTopSecret)
			{
			    onlyTopSecretInResult = 0;
			}
			
		    var aDescriptionType = hotelNode.getElementsByTagName('description_type');
		    if (aDescriptionType.length > 0 && aDescriptionType[0].hasChildNodes())
			{
                           
			    descriptionType = aDescriptionType[0].firstChild.nodeValue;
			}

		    var aDescriptionValue = hotelNode.getElementsByTagName('description_value');
		    
		    if (aDescriptionValue.length > 0 && aDescriptionValue[0].hasChildNodes())
			{
			    var value = aDescriptionValue[0].firstChild.nodeValue;
			
			    description = value;
			
			    if(descriptionType == 'url')
				{
				    var aDescriptionUrl = hotelNode.getElementsByTagName('description_url');
				    if (aDescriptionUrl.length > 0 && aDescriptionUrl[0].hasChildNodes())
					{
					    descriptionUrl = aDescriptionUrl[0].firstChild.nodeValue;;
					}
				}
			   
			}
                       
		    var imageUrl = '';
		    var aUrls = hotelNode.getElementsByTagName('image_url');

		    if (aUrls.length > 0 && aUrls[0].hasChildNodes())
			{
			    imageUrl = aUrls[0].firstChild.nodeValue;
			}

		    var rating  = '';
		    var aRating = hotelNode.getElementsByTagName('rating');

		    if (aRating.length > 0 && aRating[0].hasChildNodes())
			{
			    rating = aRating[0].firstChild.nodeValue;
			}
			
		    // Hotel longitude and latitude
		    var longitude  = '';
		    var aLongitude = hotelNode.getElementsByTagName('longitude');

		    var latitude  = '';
		    var aLatitude = hotelNode.getElementsByTagName('latitude');

		    if (aLongitude.length > 0 && aLongitude[0].hasChildNodes())
			{
			    longitude = aLongitude[0].firstChild.nodeValue;
			}

		    if (aLatitude.length > 0 && aLatitude[0].hasChildNodes())
			{
			    latitude = aLatitude[0].firstChild.nodeValue;
			}

		    // Add this rating to the list of ratings

		    var ratingUrl = this.ratingPath+rating+'_star.png';
			
		    // Clone the hotel node and put it in a document fragment
		    var hotel = this.hotelTemplate.cloneNode(true);
		    hotelFragment.appendChild(hotel);
		    var hotelIds = new IdCache(hotel);
			
		    // Insert hotel data in document
			
		    if(hotelIds.get('hotelListName') != null)
			{
			    hotelIds.get('hotelListName').innerHTML = name;
			    hotelIds.get('hotelListName').setAttribute('id', 'hotelListName'+hotelId);
			}
			
		    if(hotelIds.get('hotelListAddress') != null)
			{
			    if (hotelIsTopSecret)
				{
				    if(hotelIds.get('hotelListAddressDisplay') != null)
					Element.hide(hotelIds.get('hotelListAddressDisplay'));
				}
			    else
				{
				    hotelIds.get('hotelListAddress').innerHTML = address;
				}
			}
			
		    if(hotelIds.get('hotelListDescription') != null)
			{
			    hotelIds.get('hotelListDescription').innerHTML = description;
			}

			
		    if (imageUrl != '')
			{
			    hotelIds.get('hotelListImageUrl').src = imageUrl;
			}
		    
		    hotelIds.get('hotelListRating').src = ratingUrl;

		    var descUrl = "/"+this.site + "/hotel/cgi-bin/show_hotel_info.cgi?booking_agent="+bookingAgent+"&site="+this.site+"&hotel_id="+hotelId;

	            if(this.data['partner'] && this.data['partner'] != '')
			{
			    descUrl += '&partner=' + this.data['partner'];
			}
	
		    if(descriptionType == 'url')
			{
			    descUrl = descriptionUrl;
			}
		   
		    if(hotelIds.get('hotelListLinkPictures') != null)
			{
			    if (hotelIsTopSecret)
				{
				    Element.hide(hotelIds.get('hotelListLinkPictures'));
				}
			    else
				{
				    var linkId = "hotelListLinkPictures"+hotelId;
				    hotelIds.get('hotelListLinkPictures').href = descUrl + "&tab=2";
				    hotelIds.get('hotelListLinkPictures').id = linkId;
				}
			}
		    if(hotelIds.get('hotelListLinkMap') != null)
			{
			    if(window.GMap && GBrowserIsCompatible() &&! hotelIsTopSecret && longitude != null && longitude != 0 && latitude != null && latitude != 0)
				{
				    var linkId = "hotelListLinkMap"+hotelId;
				    hotelIds.get('hotelListLinkMap').href = descUrl + "&tab=3";
				    hotelIds.get('hotelListLinkMap').id = linkId;
				}
			    else
				{
				    Element.hide(hotelIds.get('hotelListLinkMap'));
				}
			}

		    if(hotelIds.get('hotelListLink') != null)
			{
			    var linkId = "hotelListLink"+hotelId;
			    hotelIds.get('hotelListLink').href = descUrl;
			    hotelIds.get('hotelListLink').id = linkId;
			}

		    if(hotelIds.get('hotelListHotelId') != null)
			{
			    hotelIds.get('hotelListHotelId').value = hotelId;
			    hotelIds.get('hotelListHotelId').removeAttribute('id');
			}

		    if(hotelIds.get('hotelListBookingAgent') != null)
			{
			    hotelIds.get('hotelListBookingAgent').value = bookingAgent;
			    hotelIds.get('hotelListBookingAgent').removeAttribute('id');
			}

		    var foundBlocks = TNGui.activate('supplierIs'+bookingAgent, hotel);
		    if(foundBlocks > 0)
			{
			    TNGui.deactivate('supplierIs'+bookingAgent, hotel);

			    TNGui.activate('supplierFoundInTemplate', hotel);
			    TNGui.deactivate('supplierFoundInTemplate', hotel);
			}

		    if(hotelIds.get('hotelIdListForm') != null)
			{
			    hotelIds.get('hotelIdListForm').name = hotelId;
			}

		    if(hotelIds.get('hotelListSearchLink') != null)
			{
			    var searchLink   = '/'+this.site+'/hotel/cgi-bin/hotel_search_box.cgi?dh_dest_id='+this.data['dh_dest_id'];
			    searchLink += '&hotel_id=' + hotelId;
			    searchLink += '&adults=' + this.data['adults'];
			    searchLink += '&children=' + this.data['children'];
			    searchLink += '&children_age=' + this.data['children_age'];
			    searchLink += '&rooms=' + this.data['rooms'];
				searchLink += '&partner=' + this.data['partner'];
			    var searchLinkId = "hotelListSearchLink"+hotelId;
			    hotelIds.get('hotelListSearchLink').href = searchLink;
			    hotelIds.get('hotelListSearchLink').id   = searchLinkId;
			}
		    
		    if (! hotelIsTopSecret && hotelIds.get('hotelListTopSecret') != null)
			{
			    Element.hide(hotelIds.get('hotelListTopSecret'));
			}

		    //Set the correct name for the category.

		    if(hotelIds.get('hotelListCat') != null && this.categoryData[category] != null && this.categoryData[category].key != 'not_classified' )
			{
			    var categoryData =  this.categoryData[category];
			    hotelIds.get('hotelListCat').innerHTML = categoryData.name;
			    hotelIds.get('hotelListCat').setAttribute('class',     'hotelCategory preferred_'+categoryData.id);
			    hotelIds.get('hotelListCat').setAttribute('className', 'hotelCategory preferred_'+categoryData.id);
			}
		   
		    var availNode = hotelIds.get('hotelListAvail');
		    var requestNode = hotelIds.get('hotelListRequest');
		     
		    if(availability != '')
			{
			    if(availNode != null && requestNode != null)
				{
				    if(availability == 'AV')
					{
					    Element.show(availNode);
					}
				    else
					{
					    Element.show(requestNode);
					}
				    availNode.removeAttribute('id');
				    requestNode.removeAttribute('id');
				}
			    
			}
		   
		    
		    if(hotelIds.get('hotelListCustomerRating') && hotelIds.get('hotelListCustomerRatingHeader') && customerRating > 0 )
			{
			    hotelIds.get('hotelListCustomerRating').innerHTML = customerRating + "/5";
			}
		    else
			{
			    if(hotelIds.get('hotelListCustomerRatingHeader'))
				{
				    Element.hide(hotelIds.get('hotelListCustomerRatingHeader'));
				}
			}
		    if(hotelIds.get('hotelListCustomerComment') &&  customerComment != '')
			{
			    hotelIds.get('hotelListCustomerComment').innerHTML = customerComment;
			    
			    var customerLink = "/" + this.site + "/hotel/cgi-bin/show_hotel_info.cgi?tab=4&hotel_id=" + hotelId ;
			    if(hotelIds.get('hotelListLinkComment') != null)
				{
				    hotelIds.get('hotelListLinkComment').href = customerLink;
				    hotelIds.get('hotelListLinkComment').id   = "hotelListLinkComment"+hotelId;
				}
			}
		    else
			{
			    if(hotelIds.get('hotelListLinkComment') != null)
				{
				    Element.hide(hotelIds.get('hotelListLinkComment'));
				    hotelIds.get('hotelListLinkComment').id   = "hotelListLinkComment"+hotelId;
				}
			}
			
		    //Set windowShopper min price
		    if(hotelIds.get('hotelListMinPrice') != null)
			{
			    hotelIds.get('hotelListMinPrice').innerHTML = windowShopperPrice;
			    hotelIds.get('hotelListMinPrice').id = 'hotelListMinPrice_'+hotelId;
			}
		    
		    var combinations = hotelNode.getElementsByTagName('combination');
		    //Check for combination and if no combination for windowshopper price
		    if(combinations.length < 1 && windowShopperPrice == '')
			{
			    //Remove from price if it exists
			    if(hotelIds.get('hotelListPrice') != null)
				{
				    Element.hide(hotelIds.get('hotelListPrice'));
				}
			}
		    if(hotelIds.get('hotelListPrice') != null)
			{
			    //hotelIds.get('hotelListPrice').setAttribute('id', 'hotelListPrice_'+hotelId);
			}

		    if(this.combinationTemplate != null)
			{	    		
			    // Get the table for secondChose and replace id
			    hotelIds.get('secondChoise').setAttribute('id', 'secondChoise_'+hotelId);

			    //Get the form and replace id
			    hotelIds.get('hotelIdListForm').setAttribute('id', 'form_'+hotelId);
	    
			    // Add combinations from XML
			
			    var selected = null;
			    var wanted_exists = false;
			    var cheapest_selected = 0;
			    var secondChoiseExists = 0;
			    for (var j=0; j<combinations.length; j++)
				{
				    // Get room combination data from XML
		
				    var combinationNode  = combinations[j];
				    var combinationType  = combinationNode.getAttribute('type');
				    var combinationName  = combinationNode.getElementsByTagName('name')[0].firstChild.nodeValue.unescapeHTML();
				    var combinationPrice = parseInt(combinationNode.getElementsByTagName('price')[0].firstChild.nodeValue);
				    var roomTypes        = combinationNode.getElementsByTagName('room_type');
				
				    if(minPrice == 0 || minPrice > combinationPrice)
					{
					    minPrice = combinationPrice;
				   
					}
				
				
				    if(cheapestPrice == 0 || combinationPrice < cheapestPrice)
					{
					    cheapestPrice     = combinationPrice;
					}

				    // Add cheapeast combination to the shown div
				    if((combinationType == 'wanted' && cheapest_selected == 0)||
				       (combinationType != 'wanted' && (cheapest_selected == 0 || combinationPrice < cheapest_selected)))
					{
					    if(maxPrice == 0 || combinationPrice > maxPrice)
						{
						    maxPrice = combinationPrice;
						}
				
					    var combination = this.combinationTemplate.cloneNode(true);
					    hotelIds.get('combinationsList').tBodies[0].appendChild(combination);

					    var combinationIds = new IdCache(combination);
					    // Insert combination information
					    combination.setAttribute('class', combinationType);
					    combination.setAttribute('className', combinationType);
					    combinationIds.get('hotelListCombinationName').innerHTML = combinationName;
					    combinationIds.get('hotelListCombinationPrice').innerHTML = combinationPrice;
				
					    // Remove ids
					    combinationIds.get('hotelListCombinationName').removeAttribute('id');
					    combinationIds.get('hotelListCombinationPrice').removeAttribute('id');
				
					    var roomType = combinationIds.get('hotelListRoomType');

					    roomType.removeAttribute('id');
					    if (combinationType == 'wanted')
						{
						    selected = roomType;
						    wanted_exists = true;
						}
					    if (! wanted_exists 
						&& (cheapest_selected == 0 || combinationPrice < cheapest_selected))
						{
						    selected = roomType;
						}

					    var roomTypeValue = '';
				    
					    for (var k=0; k<roomTypes.length; k++)
						{
						    var roomTypeNode = roomTypes[k];
						    // Take out the values
						    var roomId        = roomTypeNode.getElementsByTagName('id')[0].firstChild.nodeValue;
						    var numberOfRooms = roomTypeNode.getElementsByTagName('number')[0].firstChild.nodeValue;
						    var paramString   = roomId + '@' + numberOfRooms + ';';
						    roomTypeValue    = roomTypeValue + paramString; 
		    			
						}
					    roomTypeValue = roomTypeValue.substring(0, roomTypeValue.length -1);
					    roomType.value = roomTypeValue;
					    cheapest_selected = combinationPrice;
					}
				    else
					{
					    secondChoiseExists = 1;
					    // Clone the combination node and put it in the document
					    var combinationSecondChoise = this.combinationSecondChoiseTemplate.cloneNode(true);

					    hotelIds.get('secondChoise').tBodies[0].appendChild(combinationSecondChoise);
					    var combinationIds = new IdCache(combinationSecondChoise);

					    // Insert combination information
					    combinationIds.get('hotelListCombinationNameSecondChoise').innerHTML = combinationName;
					    combinationIds.get('hotelListCombinationPriceSecondChoise').innerHTML = combinationPrice;                        
				    
					    // Remove ids
					    combinationIds.get('hotelListCombinationNameSecondChoise').removeAttribute('id');
					    combinationIds.get('hotelListCombinationPriceSecondChoise').removeAttribute('id');

					    var roomTypeSecondChoise = combinationIds.get('hotelListRoomTypeSecondChoise');
					    roomTypeSecondChoise.removeAttribute('id');
				    
					    var roomTypeValueSecondChoise = '';
					    for (var k=0; k<roomTypes.length; k++)
						{
						    var roomTypeNodeSecondChoise = roomTypes[k];
						    // Take out the values
						    var roomIdSecondChoise        = roomTypeNodeSecondChoise.getElementsByTagName('id')[0].firstChild.nodeValue;
						    var numberOfRoomsSecondChoise = roomTypeNodeSecondChoise.getElementsByTagName('number')[0].firstChild.nodeValue;
						    var paramStringSecondChoise   = roomIdSecondChoise + '@' + numberOfRoomsSecondChoise + ';';
						    roomTypeValueSecondChoise     = roomTypeValueSecondChoise + paramStringSecondChoise; 
		    			
						}
					    roomTypeValueSecondChoise = roomTypeValueSecondChoise.substring( 0, roomTypeValueSecondChoise.length-1);
					    roomTypeSecondChoise.value = roomTypeValueSecondChoise;
					}
				}
			    if (selected != null)
				{
				    selected.id = storeHotelSelect();
				}
			    hotelIds.get('hotelListShowMore').value = hotelId;
			
			    // If no secondChoice remove link to show more alternatives.
			    if(secondChoiseExists == 0)
				{
				    Element.remove(hotelIds.get('hotelListShowMore'));
				}
			    else
				{
				    hotelIds.get('hotelListShowMore').setAttribute('id', 'hotelListShowMore,'+hotelId);
				}
                                
			}
		    // Placed here because it also needs price

		    var showPrice = cheapestPrice;
		    
		    if(this.method == "show_all_hotels")
			{
			    showPrice = windowShopperPrice;
			}

                    if(!cheapestHotel || cheapestHotel.Price > showPrice)
		    {
		       cheapestHotel =
                       { 
                         HotelId:        hotelId,
			 Name:           name,
	   		 Price:          showPrice,
                         RatingUrl:      ratingUrl,
                         PriceFormatted: TNText.replaceHash(this.priceFormatting, { price: showPrice } ) || showPrice
                       };
 		    }
		    if (window.GMap)
			{
			    
			    addCustomMarker(latitude, longitude, name, rating, this.categoryData[category], hotelId, showPrice, this.site, this.ratingPath, this.markerArray,this.categoryIcons[category], this.priceFormatting,(numHotels<2));
		    
			}
			
			
		    // Remove IDs
		    hotel.removeAttribute('id');
		    hotel.setAttribute('id', 'hotel_' + hotelId);
		    if(hotelIds.get('hotelListPrice') != null)
			{
			    hotelIds.get('hotelListPrice').removeAttribute('id');
			}
		    hotelIds.get('hotelListAddress').removeAttribute('id');
		    hotelIds.get('hotelListRating').removeAttribute('id');
		    hotelIds.get('hotelListImageUrl').removeAttribute('id');
		    if(hotelIds.get('hotelListDescription') != null)
			{
			    hotelIds.get('hotelListDescription').removeAttribute('id');
			}
		    if(hotelIds.get('hotelListCustomerRating') != null)
			{
			    hotelIds.get('hotelListCustomerRating').removeAttribute('id');
			}
		    // Toggle visibility
                    hotel.style.display = 'block';
		    //Element.show(hotel);

		    /*
		      Add hotel short list
		    */
		    if(hotelShortListRow)
			{
			    var colLoop = hotelShortListRow.getLoop('hotelShortListCol');
			    if(colLoop)
				{
				    var h = {
					Index:     i + 1,
					HotelName: name,
					Price:     TNText.replaceHash(this.priceFormatting, { price: showPrice } ) || showPrice 
				    };

				    var elements = colLoop.updateHash(h, 'hotelShortList');
				    if(elements.HotelName)
					{
					    elements.HotelName.id = 'hotelShortListName__'+hotelId;

					    Event.observe(elements.HotelName, 'click', this.showTooltip.bindAsEventListener(this));
					}
				    hotelShortListRow.addLoop(colLoop);

				    // We have X columns
				    if((i % this.shortListColumns) == 1 || i + 1 == hotels.length)
					{
					    TNDocument.addLoop(hotelShortListRow);

					    if(i + 1 > this.shortListInitMax)
						{
						    var row = hotelShortListRow.getParents();
						    row[0].style.display = 'none';
						}
					    else
						{
						    shownInShortList = i + 1;
						}
					    hotelShortListRow = TNDocument.getLoop('hotelShortListRow');
					}
				}
			}
		}
		this.hotelParent.appendChild(hotelFragment);
		storeHotelSelects.each(
				       function (id) {
		    $(id).checked = true;
		});

	    }

	    //Add topSecrets

	    if (this.topSecret == '1' || this.onlyTopSecret == '1')
            {
		var topSecretLinkBlock  = $('hasTopSecret');
		var filterTopSecretLink = $('filterTopSecret');
		var clearTopSecretLink  = $('clearTopSecret');
		var prevSearchLink      = $('prevSearchUrl');
	        if (topSecretLinkBlock != null && filterTopSecretLink != null && clearTopSecretLink != null)
		{
		    topSecretLinkBlock.style.display = 'block';

		    if (this.onlyTopSecret == '1')
			{
			    if (numHotels == 0 && $('TopSecretFound') && $('noTopSecretFound'))
				{
				    $('TopSecretFound').style.display = 'none';
				    $('noTopSecretFound').style.display = 'block';
				    this.onlyTopSecret == '0';
				}
			    else
				$('TopSecretFound').style.display = 'block';
			    filterTopSecretLink.style.display = 'none';
			    clearTopSecretLink.style.display  = 'block';
			    Event.observe(clearTopSecretLink, 'click', this.clearTopSecret.bindAsEventListener(this));
			    if(prevSearchLink)
				{
				    if(this.hotelId != '' || this.preferedHotelName != '' )
					{
					    prevSearchLink.style.display = 'block';
					    Event.observe(prevSearchLink, 'click', this.prevSearch.bindAsEventListener(this));
					}
				    else
					{
					   prevSearchLink.style.display = 'none'; 
					}
				}
				
			}
		    else
			{
			    filterTopSecretLink.style.display = 'block';
			    clearTopSecretLink.style.display  = 'none';
			    prevSearchLink.style.display = 'none';
			    Event.observe($('filterTopSecret'), 'click', this.filterTopSecret.bindAsEventListener(this));
			}
		    
		}
	    }
	    else
		{
		    if($('hasTopSecret'))
			$('hasTopSecret').style.display = 'none';
		}
	    
	    // Create the rating options
	    if(this.filterHasBeenInit == '' && ratingsNode && ratingsNode.length > 0 && ratingsNode[0].firstChild)
	    {
		var ratingsArray = ratingsNode[0].firstChild.nodeValue.split(',');
		for (var j = 0; j < ratingsArray.length; j++)
		{
		    this.ratings[ratingsArray[j]] = 'yes';
		}
		for (var i=0; i<=5; i++)
		{
			if($('filterRating'))
			{
		    if(this.ratings[i] != 'yes')
		    {
			$('filterRating'+i).disabled = true;
		    }
		    else
		    { 
			// Add to filter
			$('filterRating'+i).checked = true;
			this.addFilter("rating:"+i);
			//this.filter += ("|rating:"+i);
			$('filterRating'+i).disabled = false;
		    }
			}
		}
	    }
	    //Make sure categories are only added once
	    this.filterHasBeenInit = 'yes';

	    this.setInnerHTML('filterView',this.getFilterAsString());
	}

	if(this.method == "show_all_hotels")
	{
	    CreateSearchLinks();
	}

        var showBlock = false;
	if(cheapestHotel && this.showCheapest == 'yes' && 
	   this.cheapestHotelId != '' && this.cheapestHotelId == cheapestHotel.HotelId &&
	   isPackage == 1)
	{
	   var elements = TNGui.setElementContentHash(cheapestHotel, 'cheapestHotel');
	   var activateHotelElement = $('cheapestHotelShowLink');
           if(activateHotelElement)
           {
	       //Event.observe(activateHotelElement, 'mouseover', this.showTooltip.bindAsEventListener(this));
	       //Event.observe(activateHotelElement, 'mouseout', this.hideTooltip.bindAsEventListener(this));
	     Event.observe(activateHotelElement, 'click', this.onSelectOneHotel.bindAsEventListener(this));

             showBlock = true;
           }
	}

        TNGui.showHide('cheapestHotelTitle', !showBlock);

	// Render loops
	TNDocument.render();

        // show list if we have any data
	if(shownInShortList > 0)
	{
	    TNGui.setElementContent('hotelShortListShownOnPageCount', hotels.length, undefined, 'hotelShortListShownOnPageCount');

	    TNGui.showHide('hotelShortListShowText', hotels.length <= shownInShortList);
	    TNGui.showHide('hotelShortListHideText', hotels.length > shownInShortList);
	    TNGui.activate('hotelShortListShowMore', document, hotels.length <= shownInShortList);
	   
	    TNGui.activate('hotelShortList', document);
        }

        if(this.alwaysShowPager == 'yes' && numHotels > 1)
          TNGui.showHide('hotelListPagerHolder');

	if($('hotelListSearch'))
	Element.hide('hotelListSearch');
	
	if (this.mapIsLoaded())
	    {
		this.addMarkersToMap();
	    }

        // START ADDED BY MARTIN 2008-02-13
        // Add zebra stripes
        if(this.useRoomCombinationStripes == 'yes') {
            var zebraCount=0;
            var tables = $$('table.hotelListItemsRooms');
            for ( x in tables ) {
                if (typeof(tables[x]) != "object")
                    continue;        
                if( tables[x].id == 'combinationsList' ) {
                    zebraCount=0;
                }
                var rows = tables[x].getElementsBySelector('tr');
                for ( y in rows ) {
                    if (typeof(rows[y]) != "object")
                        continue;
                    if(zebraCount % 2 == 1) {
                        rows[y].setAttribute('class', 'roomCombinationOddRow');
                        rows[y].setAttribute('className', 'roomCombinationOddRow');                    
                    }
                    zebraCount++;
                }
            }
        }
        // END ADDED BY MARTIN 2008-02-13
        
	} catch(e) {
    var msg = "Error: "+e.description;
        //alert(e);
    };
	
},

    // remove steps

    removeSteps : function()
    {
	if (this.useSteps == 'yes')
	{
	    this.stepsHasBeenInit = '';
	    remove_childs(this.hotelStepParent);
	}
    },

    // set search box visible and remove hotels and map markers
    
    removeHotelList : function()
    {
        this.removeSelectedHotel();

	// Remove old hotel list
	this.hotelParent.innerHTML = '';
	// show search
	Element.show('hotelListSearch');

	// block errors
        Element.hide('hotelListError');
	Element.hide('hotelListErrorNoHotelName');
	TNGui.showHide('cheapestHotelTitle', true);
	TNGui.showHide('hotelListStepsHolder', true);
        TNGui.showHide('hotelListPagerHolder', true);
	TNGui.activate('hotelShortList', document, true);

	//remove map markers

	if(this.map)
	{
	    this.map.closeInfoWindow();
	    this.map.clearOverlays();
	    
	}

	this.markerArray  = {};
     },
    
    onFilter : function(event)
    {
	var element = Event.element(event);
	var filterPart = element.value;
	var filterId = element.id;	
	var isChecked = element.checked;
	
	if(filterId.match('sortByName'))
	{
	    this.sortBy = 'name';
        }
	else if(filterId.match('sortByPrice'))
	{
	    this.sortBy = 'price';
        }
        else if(filterId.match('sortByCustomerRating'))
	{
	    this.sortBy = 'customer_rating';
        }
        else if(filterId.match('sortByMostSold'))
	{
	    this.sortBy = 'most_sold';
        }
		
        else if(filterId.match('sortByDropDown'))
	{
	    this.sortBy = filterPart;
	}
	else if(filterId.match('sortByPreferred'))
	{
	    this.sortBy = filterPart;
	}
        else
        {
	    if(isChecked)
	    {
		this.addFilter(filterPart);
	    }
	    else
	    {
		this.removeFilter(filterPart);
	    }
        }
	// Remove value of hotel_id if it was set
        this.hotelId = '';
	this.steps = '';
	this.removeSteps();
	this.removeHotelList();
	this.getHotelList();
    },
    onStep : function(event)
    {
	var element = Event.element(event);
	if (!element.getAttribute("value"))
	  element = element.parentNode;
	  
        var step = parseInt(element.getAttribute("value"));
        if(Number(step) < 1 || step == this.steps)
	{
           step = 0;

           if(element.id == 'hotelStepPrev0')
              step = parseInt(this.steps) - 1;

           if(element.id == 'hotelStepNext0')
              step = parseInt(this.steps) + 1;

	  if(step == 0)
	    return;
	}
	this.markStep(false);
	this.steps = step;	
	this.markStep(true);

	// Update prev,next first etc.
	this.showNonPageSteppers();

	// Remove value of hotel_id if it was set
        this.hotelId = '';
	this.removeHotelList();
	this.getHotelList();
    },
    showNonPageSteppers: function()
    {
       if(this.steps == '')
	 return;

       var currentStep = parseInt(this.steps);
       TNGui.showHide('hotelStepFirst1', currentStep == 1); 
       TNGui.showHide('hotelStepPrev0',  currentStep == 1); 
       TNGui.showHide('hotelStepNext0',  currentStep == this.tabs); 
       TNGui.showHide('hotelStepLast'+this.tabs,  currentStep == this.tabs);        
    },
    markStep: function(doMark)
    {
       if(this.steps != '')
         TNGui.addRemoveClassName('hotelStepSelectPage'+this.steps, 'hotelListStepSelected', !doMark);
    },
    addStep : function(id, pageNo, numHotels)
    {
        var stepElementClone = $('hotelStep'+id);
        if(!stepElementClone)
          return;

        stepElementClone = stepElementClone.cloneNode(true);

	var hotelStep = this.hotelStepTemplate.cloneNode(true);
	hotelStep.removeAttribute('id');
	this.hotelStepParent.appendChild(hotelStep);

	var hotelStepValue       = $('hotelListStepValue');
	hotelStepValue.setAttribute('value', pageNo);

        if(hotelStepValue.tagName == 'A')
        {
          var lastShown = pageNo*this.hotelsPerStep;
          if(lastShown > numHotels)
             lastShown = numHotels;

	  var titleToShow = '';
          if(stepElementClone.title && stepElementClone.title != '')
            titleToShow = TNText.replaceHash(stepElementClone.title, 
                            { 
				shownhotels: ((pageNo-1)*this.hotelsPerStep + 1) + ' - ' + lastShown, 
				numhotels:   numHotels 
			    } 
			  );

          stepElementClone.setAttribute('title', titleToShow);
          hotelStepValue.setAttribute('title', titleToShow);
        }

        if(stepElementClone.tagName != 'IMG')
           stepElementClone.innerHTML = pageNo;
 
        stepElementClone.removeAttribute('id');
        hotelStepValue.setAttribute('id', 'hotelStep'+ id + pageNo);

        hotelStepValue.appendChild(stepElementClone);

	Event.observe(hotelStepValue,'click', this.onStep.bindAsEventListener(this));

	return hotelStepValue;
    },
    toggleTopSecretHeaders : function(topsecret)
    {
	var i = 1;
	while ($('hotelsIn'+i) && $('topSecretHotelsIn'+i))
	    {
		if (topsecret)
		    {
			$('hotelsIn'+i).style.display = 'none';
			$('topSecretHotelsIn'+i).style.display = 'block';
		    }
		else
		    {
			$('hotelsIn'+i).style.display = 'block';
			$('topSecretHotelsIn'+i).style.display = 'none';
		    }
		i++;
	    }
    },
    filterTopSecret : function(event)
    {
	if (this.filterOn == '0') {
	this.data['hotel_id'] = '';
	this.data['hotel_name'] = '';
	this.setFilterFromString('');
	this.onlyTopSecret = '1';
	this.toggleTopSecretHeaders(true);
	if($('allHotelsUrl') != null)
	{
	  Element.hide('allHotelsUrl');
	}
	this.removeHotelList();
	this.getHotelList();
	this.filterOn = '1';
	}
	
    },
    
    clearTopSecret : function(event)
    {
	if (this.filterOn == '1') {
	this.onlyTopSecret = '0';
	this.toggleTopSecretHeaders(false);
	this.askForAllHotels();
	this.filterOn = '0';
	}
    },
    prevSearch : function(event)
    {
	this.data['hotel_name'] = this.preferedHotelName;
	this.data['hotel_id'] = this.hotelId;
	this.onlyTopSecret = '0';
	this.toggleTopSecretHeaders(false);
	this.setFilterFromString('');
	this.filterHasBeenInit = '';
	this.stepsHasBeenInit = '';
	this.removeHotelList();
	this.getHotelList();
    },
    
    askForAllHotels: function(event)
    {
	this.data['hotel_id'] = '';
	this.data['hotel_name'] = '';
	this.preferedHotelName = '';
	this.setFilterFromString('');
	this.filterHasBeenInit = '';
	this.stepsHasBeenInit = '';
	this.removeHotelList();
	this.getHotelList();

	if($('allHotelsUrl') != null)
	{
	  Element.hide('allHotelsUrl');
	}

	if($('sortHotels') != null)
	{
	  Element.show('sortHotels');
	}	
	if($('sorting') != null)
	{
	  Element.show('sorting');
	}	

    },
    
    showError : function(transport)
    {
	alert('Could not get hotel info: ' + transport.statusText);
    },
    getHotelIdFromEventElement: function(event)
    {
	var element = Event.element(event);
        if(element && element.id)
	{
           if(element.id == 'cheapestHotelShowLink')
             return this.cheapestHotelId;

	   var hotelId = element.id.replace(/.*__/, '');
	   return hotelId;
	}
	return '';
    },
   onSelectOneHotel: function(event)
   {
	hotelId = this.getHotelIdFromEventElement(event);
	if(hotelId != '')
	   this.selectOneHotel(hotelId);
   },  
   selectOneHotel: function(hotelId)
   {
       this.removeSelectedHotel();

       var hotelToClone        = $('hotel_'+hotelId);
       if(!hotelToClone || !$('selectedHotel'))
         return;

	this.selectedHotel = hotelId;

	var selectedHotel       = hotelToClone.cloneNode(true);
	selectedHotel.setAttribute('id', 'selected_'+hotelId);

	walkTree(selectedHotel, 'selected_'+hotelId);

        var selectedHotelParent =  $('selectedHotel');
 	selectedHotelParent.appendChild(selectedHotel);
	
	if($('destroyImg') != null)	
	  Element.show('destroyImg');
    },

    removeSelectedHotel: function()
    {
       var selectedHotel =  $('selected_' + this.selectedHotel);
       if(this.selectedHotel != '' && selectedHotel)
       {
	 selectedHotel.parentNode.removeChild(selectedHotel);
	 this.selectedHotel = '';
	 Element.hide('destroyImg');
       }
    },
    mapIsLoaded: function()
    {
	return (this.map != null && this.map.isLoaded());
    },
    addMarkersToMap: function ()
    {
	if(!window.GMap || !this.mapIsLoaded() || !this.markerArray)
	return;
	this.map.clearOverlays();
	for (var i in this.markerArray)
	{
	    this.map.addOverlay(this.markerArray[i]);
	}
    },
    setGoogleMap: function(map)
    {
	this.map = map;
    },
    toggleAllShortList: function()
    {
	var a = TNDocument.getRenderedLoopElements('hotelShortListRow');
        if(a && a.length && a.length > 0)        
        {
          var startRow = parseInt(this.shortListInitMax / this.shortListColumns);

	  var anyShown = !Element.visible(a[startRow]);
  
          for(var i = startRow; i < a.length; i++)
          {
	    Element.toggle(a[i]);
          }
         
          TNGui.showHide('hotelShortListShowText', anyShown); 
          TNGui.showHide('hotelShortListHideText', !anyShown); 
        }
    },
    setInnerHTML: function(element, content)
    {
       var e = $(element);
       if(e)
         e.innerHTML = content;

    },
    showTooltip: function(event)
    {
	return this._showHideTooltip(event, true);
    },
    hideTooltip: function(event)
    {
	return this._showHideTooltip(event, false);
    },
    _showHideTooltip: function(event, show)
    {
	hotelId = this.getHotelIdFromEventElement(event);
	if(this.map && this.map.isLoaded() && this.markerArray[hotelId])
        {
          var marker = this.markerArray[hotelId];
          if(show)
	     marker.openInfoWindow(marker.tooltip); 
          else
	     this.map.closeInfoWindow(); 
	}
	return false;
    },
    getNodeValue: function(node, tagName, defaultValue, offset)
    {
	offset |= 0;
	
	var tags = node.getElementsByTagName(tagName);

	if(tags && tags.length > offset)
          return tags[offset].firstChild.nodeValue;

	return defaultValue;       

    },
    addFilter: function(filterValue)
    {
      if(!this.filter.include(filterValue))
	this.filter.push(filterValue);
    },
    removeFilter: function(filterValue)
    {
	 this.filter = this.filter.without(filterValue);
    },
    getFilterAsString: function()
    {
	return this.filter.join('|');
    },
    setFilterFromString: function(filterString)
    {
	this.filter = filterString.split('|');
    },
    isNumber: function(x)
    {
       return !isNaN(Number(x));
    },
    getNumber: function(x, defaultValue)
    {
       if(this.isNumber(x)) return Number(x);

       // safety for ',' as sep
       var y=x.replace(/,/, '.');
       var y=x.replace(/[^\d\.]/g, '');
       y=Number(y);
       return this.isNumber(y) ? y : defaultValue;
     } 

}

function walkTree(node, selectedId) {
   if (node == null) // 
      return;
   // do something with node
   if(node.id && node.id != selectedId)
   {
      node.id = 'selectedHotel' + node.id;
   };
   for (var i = 0; i < node.childNodes.length; i++) {
      walkTree(node.childNodes[i], selectedId);
   }
}
function  createIcon(site, categoryid, partner)
{
    if(!window.GIcon)
	return;

var icon = new GIcon();
if (categoryid)
    icon.image = "http://static.resfeber.se/media/images/"+site+"/"+partner+"/hotel/markers/marker_"+categoryid+".png";
else
    icon.image = "http://static.resfeber.se/media/images/"+site+"/"+partner+"/hotel/markers/marker_20.png";
icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
icon.transparent= "http://www.google.com/intl/en_ALL/mapfiles/markerTransparent.png";
icon.iconSize = new GSize(21, 35);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(10, 35);
icon.infoWindowAnchor = new GPoint(10, 1);
return icon;
}


function setElementContent(cacheIds, id, content, attribute)
{
	var o = cacheIds && cacheIds.get ? cacheIds.get(id) : null;
	if(o != null)
	{	
		// Find what attribute to set
		var setAttribute = 'innerHTML';
		if(attribute && o[attribute])
			setAttribute = attribute;
		else if(o.tagName == 'IMG')
			setAttribute = 'src';
		else if(o.tagName == 'INPUT')
			setAttribute = 'value';

		o.id = '';
		o[setAttribute] = content;

		return o;
	}

	return;
}

function createMarker(GeoPoint, icon, hotelName, ratingUrl, hotelId, price, categorydata, priceFormatting,onehotel)
{
    if(!GMarker)
	return;

    var marker = new GMarker(GeoPoint,icon);
    if(onehotel)
	{
	    return marker;
	}
    else
	{
	    GEvent.addListener(marker, "click", function()
	    {
		hotelList.selectOneHotel(hotelId);
	    });
	    if ($('toolTipMarker'))
		{
		    var markerTemplate = $('toolTipMarker');
		    var newMarker = markerTemplate.cloneNode(true);
		    var markerIds = new IdCache(newMarker);
		    setElementContent(markerIds, 'tooltipHotelName', hotelName);
		    setElementContent(markerIds, 'tooltipRatingUrl', ratingUrl);
		    if (categorydata != null && categorydata.name != null && categorydata.key != 'not_classified'){
			setElementContent(markerIds, 'tooltipCategoryName', categorydata.name);
			
			var categoryId = markerIds.get('tooltipCategoryId');
			if(categoryId != null)
			    Element.addClassName(categoryId, 'preferred_'+categorydata.id);
		    }
		    if(price && price != '')
			{
			    var pF = setElementContent(markerIds, 'tooltipPriceFrom', TNText.replaceHash(priceFormatting, { price: price } ) || price );
			    var priceRow = markerIds.get('tooltipPriceFromText');
			    if(!pF && priceRow != null)
				priceRow.parentNode.removeChild(priceRow);
			}
		    if(markerIds.get('tooltipReadMoreLink'))
			{
			    setElementContent(markerIds, 'tooltipReadMoreLink', "javascript:hotelList.selectOneHotel('"+hotelId+"');",'href');
			}
		    
		    newMarker.style.display = 'block';
		    newMarker.id = 'tooltip_'+hotelId;
		    marker.infoWinShown = false;
		    marker.tooltip = newMarker;
		    if ($('mouseOverToolTip'))
			{
			    var mouseOverTemplate = $('mouseOverToolTip');
			    var newMouseOverTooltip = mouseOverTemplate.cloneNode(true);
			    var tooltipIds = new IdCache(newMouseOverTooltip);
			    setElementContent(tooltipIds, 'mouseOverTooltipHotelName', hotelName);
			    if(tooltipIds.get('mouseOverTooltipRatingUrl'))
				{
				    setElementContent(tooltipIds, 'mouseOverTooltipRatingUrl', ratingUrl);
				}
			    if(price && price != '')
				{
				    var pF = setElementContent(tooltipIds, 'mouseOverTooltipPriceFrom', TNText.replaceHash(priceFormatting, { price: price } ) || price );
				    var priceRow = tooltipIds.get('mouseOverTooltipPriceFromText');
				    if(!pF && priceRow != null)
					priceRow.parentNode.removeChild(priceRow);
				}
			    newMouseOverTooltip.style.display = 'block';
			    marker.mouseOverTooltip = newMouseOverTooltip;
			    
			    GEvent.addListener(marker, 'infowindowopen', function() {
				    marker.infoWinShown = true;
				    hotelList.mouseovertooltip.style.visibility="hidden";
				});
			    
			    GEvent.addListener(marker, 'infowindowclose', function() {
				    marker.infoWinShown = false;
				});
			    
			    GEvent.addListener(marker,"mouseover", function() {
				    if (!marker.infoWinShown)
					mouseOverTooltip(marker);
				});
			    
			    GEvent.addListener(marker,"mouseout", function() {
				    hotelList.mouseovertooltip.style.visibility="hidden";
				}); 
			}

		    GEvent.addListener(marker,"click", function() {
			    marker.openInfoWindow(marker.tooltip);
			});
		    
		    
		    
		    return marker;
	    
		}
	}
}




function showHiddenRoomOptions(hId)
{
    var isSelected = 0;
    
	
    var hotelIdArray = hId.split(",");
    var hotelId = hotelIdArray[1];
    var linkId  =  'secondChoise_'+hotelId;
    if(hId.match('selectedHotel'))
    {
	linkId  =  'selectedHotel'+linkId;
    }
    var link = $(linkId);
    Element.toggle(link);
}

function addCustomMarker(latitude, longitude,  hotelName, rating, categorydata, hotelId, price, site, ratingPath, markerArray,icon, priceFormatting,onehotel)
{
  // Placed here because it also needs price
  if(latitude != '' && latitude != 0 && longitude != '' && longitude != 0)
  {
    var ratingUrl = ratingPath + rating + "_star_ff.png";
    var geoPoint = new GLatLng(latitude, longitude);
    var marker   = createMarker(geoPoint, icon, hotelName, ratingUrl, hotelId, price, categorydata, priceFormatting,onehotel);
    if(marker != null && markerArray)
    {
      // Add to marker array if we have one (for remove or init later).
      markerArray[hotelId] = marker;
    }
    return marker;
  }
}

function mouseOverTooltip(marker) {
    hotelList.mouseovertooltip.innerHTML = marker.mouseOverTooltip.innerHTML;
    var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
    var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
    var anchor=marker.getIcon().iconAnchor;
    var width=marker.getIcon().iconSize.width;
    var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y));
    pos.apply(hotelList.mouseovertooltip);
    hotelList.mouseovertooltip.style.visibility="visible";
}

function remove_childs (element)
{
    while (element && element.firstChild)
    {
	element.removeChild(element.firstChild);
    }
}

