DynamicHotelList = Class.create();


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

    initialize: function(hotelArray) 
    {
	this.staticHotelArray  = hotelArray;
	this.currentHotelArray = Utils.copyArray(this.staticHotelArray);
	this.currentStep = 1;
	this.hotelsPerStep = config.hotelsPerStep;
	this.filterMode = 'all';
	this.steps         = '';
	this.currentStep = 1;
	this.stepsHasBeenInit = '';
	this.filterHasBeenInit = '';
	this.sortMode = 'sortByPreferred';
	this.hotelShortListState = 'minimized';

	this.hotelTemplate = hotelManager.hotelTemplate;
	this.hotelShortListTemplate = hotelManager.hotelShortListTemplate;

	// If steps is used - get the template and remove it from the document
	
	if(/*config.useSteps == 'yes' &&*/ $('hotelListStep') != null)
	{
	    this.hotelStepTemplate = $('hotelListStep');
	    this.hotelStepParent   = /*$('hotelListStepParent');*/this.hotelStepTemplate.parentNode;
	    this.hotelStepParent.removeChild(this.hotelStepTemplate);
	}

	if($('sortByPreferred')!= null)
        {
	   Event.observe($('sortByPreferred'),           'click', this.sortHotels.bindAsEventListener(this));
	}

	if($('sortByPrice')!= null)
        {
	   Event.observe($('sortByPrice'),           'click', this.sortHotels.bindAsEventListener(this));
	}

	if($('sortByName') != null)
        {
	   Event.observe($('sortByName'),            'click', this.sortHotels.bindAsEventListener(this));
	}

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

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

	if($('hotelShortListShowMore'))
	    {	    
		Event.observe($('hotelShortListShowMore'), 'click', this.buildHotelShortList.bindAsEventListener(this));
	    }
    },

    buildFilteredHotelObjects : function(dhCityPartId, ratings, category)
    {
	var filteredHotelArray = new Array();
	for (var i = 0; i < this.staticHotelArray.length; i++)
	    {
		var prospectHotel = this.staticHotelArray[i];
		var matchCityPartId = false;
		var matchRating = false;
		var matchCategory = false;

		if(dhCityPartId != null)
		    {
			for(var j = 0; j < prospectHotel.cityPartIds.length; j++)
			    {
				//console.log(prospectHotel.cityPartIds[j] + dhCityPartId);
				if(prospectHotel.cityPartIds[j] == dhCityPartId)
				    {
					//console.log('match!!');
					matchCityPartId = true;
				    }
			    }
		   }
		if (ratings != null)
		    {
			for (var k = 0; k < ratings.length; k++)
			    {
				if(prospectHotel.rating == ratings[k])
				    {
					matchRating = true;
				    }
			    }
		    }

		if (category != null && prospectHotel.category == category)
		    {
			//console.log(category + ' ' + prospectHotel.category);
			matchCategory = true;
		    }

		if ((matchCityPartId == true && matchRating == true) || (matchCityPartId == true && ratings == null) || (dhCityPartId == null && matchRating == true) || matchCategory == true)
		    {
			filteredHotelArray.push(prospectHotel);
		    }
	    }
	this.currentHotelArray = filteredHotelArray;
    },

    buildHotelHtml : function()
    {
	var hotelObjects = this.currentHotelArray;
	var numHotels = hotelObjects.length;
	var cheapestHotel;
	var selected = null;
	var wantedExists = false;
	var cheapestSelected = 0;
	var hotelsPerStep = this.hotelsPerStep;
	var currentStep = this.currentStep;
	var stepLastHotel = currentStep * hotelsPerStep;
	var stepFirstHotel = stepLastHotel-hotelsPerStep+1;

// 	['hotelShortList', 'sorting'].each(Element.show);
	$('hotelListSearch').style.display = 'block';
	TNGui.activate('hotelShortList', document, false);
	TNGui.showHide('sorting', false);
        Utils.setInnerHTML('numHotels', numHotels);
	TNGui.showHide('numberProductItemsFound', false);
	Utils.setInnerHTML('stepInfoTotal', numHotels);
	this.hotelShortListState = 'minimized';

	if (this.filterMode == 'all' && this.sortMode == 'sortByPreferred' && currentStep == 1)
	    {
		TNGui.showHide('hotelsIn3', false);
	    }
	else
	    {
		TNGui.showHide('hotelsIn3', true);
	    }

	if (this.filterMode == 'topsecret')
	    {
		TNGui.showHide('topSecretHotelsIn3', false);
	    }
	else
	    {
		TNGui.showHide('topSecretHotelsIn3', true);
	    }

	hotelManager.removeHotelList();
// 	hotelList.hotelShortListParent.innerHTML = '';

// 	hotelList.hotelParent.innerHTML = '';

	var hotelListHtml = document.createDocumentFragment();
	
	if (stepLastHotel>hotelObjects.length)
	    {
		stepLastHotel = hotelObjects.length;
	    }

	for (var i=(stepFirstHotel-1); i<(stepLastHotel); i++)
	    {
		var hotelHtml = this.hotelTemplate.cloneNode(true);
		hotelListHtml.appendChild(hotelHtml);
		var hotelCache = new IdCache(hotelHtml);
		hotelObjects[i].buildHtml(hotelCache);

		hotelHtml.removeAttribute('id');
		hotelHtml.setAttribute('id', 'hotel_' + hotelObjects[i].id);
		hotelHtml.style.display = 'block';

		var showPrice = hotelObjects[i].cheapestPrice;
		    
		if(hotelManager.method == "show_all_hotels")
		    {
			showPrice = hotelObjects[i].windowShopperPrice;
		    }
		
		if(!cheapestHotel || cheapestHotel.Price > showPrice)
		    {
			cheapestHotel =
			    { 
				HotelId:        hotelObjects[i].id,
				Name:           hotelObjects[i].name,
				Price:          showPrice,
				RatingUrl:      hotelObjects[i].ratingUrl || 'https://statics.travelinspiration.info/media/images/rf/misc/pxl.gif',
				PriceFormatted: TNText.replaceHash(config.priceFormatting, { price: showPrice } ) || showPrice
			    };
 		    }
		//Add categoryData
		this.categoryData = categoryDataManager.getCategoryData(hotelObjects[i].category);

		//Add Gmap markers
		if (window.GMap && mapManager)
		    {
			mapManager.addCustomMarker(hotelObjects[i].latitude, hotelObjects[i].longitude, hotelObjects[i].name, hotelObjects[i].rating, this.categoryData, hotelObjects[i].id, showPrice, config.site, config.ratingPath, null, this.categoryIcons, config.priceFormatting, (numHotels<2));
		    }    

	    }

	if (this.hotelShortListTemplate)
	    {
		this.buildHotelShortList();
	    }

	hotelManager.addHotelList(hotelListHtml);
	if (this.hotelShortListTemplate)
	    Element.show('hotelShortList');
	Element.hide('hotelListSearch');

	if (mapManager.mapIsLoaded())
	    {
		mapManager.addMarkersToMap();
	    }

	//Take out the number of hotels and if more then allowed create tabs.

	if(/*hotelList.useSteps == 'yes' &&*/ $('hotelListStepParent') != null)
	    {
		if(numHotels > hotelsPerStep)
		    {
			//start with removing the old tabs
			var numberOfHotels = numHotels;
			var numberOfTabs   = parseInt(numberOfHotels/hotelsPerStep);
				
			if((numberOfTabs * hotelsPerStep) < numberOfHotels)
			    {
				numberOfTabs ++;
			    }
				
// 			hotelList.tabs = numberOfTabs;
				
			if(this.stepsHasBeenInit != 'yes'){
			    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);
		    }
	    }

	//If no hotels with hotel name found.
	if(hotelList.errorMsg != '' && hotelList.errorMsg == 'no_hotels_with_name_found')
	    {
		$('hotelListErrorNoHotelName').style.display = 'block';
	    }
	if(hotelList.errorMsg != '' && hotelList.errorMsg == 'selected_hotel_not_available')
	    {
		$('hotelListErrorSelectedNotAvailable').style.display = 'block';
	    }
	CreateSearchLinks();
    },

    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.currentStep = step;
	hotelManager.removeHotelList();
	window.scroll(($('tnStandardSearchArea')).offsetWidth, ($('tnStandardSearchArea')).offsetTop);
	this.buildHotelHtml();
    },
    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;
    },

    buildHotelShortList: function(event)
    {
	//Clear any previous short list
	if (hotelList.hotelShortListParentLeft.innerHTML)
	    {
		hotelList.hotelShortListParentLeft.innerHTML = '';
		hotelList.hotelShortListParentRight.innerHTML = '';
	    }

	//If called by maximize/minimize link; switch state
	if (event)
	    {
		if (this.hotelShortListState == 'minimized')
		    {
			this.hotelShortListState = 'maximized';
		    }
		else
		    {
			this.hotelShortListState = 'minimized';
		    }
	    }

	//Build Hotel Short List according to number of hotels on current page and current state
	var stepLastHotel = this.currentStep * this.hotelsPerStep;
	var stepFirstHotel = stepLastHotel-this.hotelsPerStep+1;
	var hotelsInShortList;
	var currentIndex = 1;
	var visibleHotelsInShortList;

	if(this.currentHotelArray.length < stepLastHotel)
	    stepLastHotel = this.currentHotelArray.length;

	hotelsInShortList = (stepLastHotel-stepFirstHotel+1);

	if (hotelsInShortList <= config.shortListInitMax)
	    {
		$('hotelShortListShowMore').hide();
		visibleHotelsInShortList = hotelsInShortList;
	    }
	else
	    {
		Utils.setInnerHTML('hotelShortListShownOnPageCount', hotelsInShortList);
		$('hotelShortListShowMore').show();

		if (this.hotelShortListState == 'minimized')
		    {
			$('hotelShortListShowText').show();
			$('hotelShortListHideText').hide();
			visibleHotelsInShortList = config.shortListInitMax;
		    }

		if (this.hotelShortListState == 'maximized')
		    {
			$('hotelShortListShowText').hide();
			$('hotelShortListHideText').show();
			visibleHotelsInShortList = hotelsInShortList;
		    }
	    }

	for (i=(stepFirstHotel-1); i<(stepFirstHotel+visibleHotelsInShortList-1); ++i)
	    {
		var shortListHotelNode = this.hotelShortListTemplate.cloneNode(true);
		var shortListHotelCache = new IdCache(shortListHotelNode);

		if (shortListHotelCache.get('hotelShortListIndex') != null)
		    {
			shortListHotelCache.get('hotelShortListIndex').innerHTML = currentIndex;
			shortListHotelCache.get('hotelShortListHotelName').innerHTML = this.currentHotelArray[i].name;
			shortListHotelCache.get('hotelShortListHotelName').setAttribute('id', this.currentHotelArray[i].id);	
			shortListHotelCache.get('hotelShortListPrice').innerHTML = this.currentHotelArray[i].cheapestPrice;
			shortListHotelNode.removeAttribute('id');
			shortListHotelNode.setAttribute('id', 'hotelShortList' + currentIndex);
			if(visibleHotelsInShortList == 1)
			    shortListHotelNode.setAttribute('class', 'hotelShortListHotelLeft');
			else if (currentIndex>((visibleHotelsInShortList+1)/2))
			    shortListHotelNode.setAttribute('class', 'hotelShortListHotelRight');   
			else
			    shortListHotelNode.setAttribute('class', 'hotelShortListHotelLeft');
			shortListHotelNode.show();
			currentIndex++;
			hotelManager.addHotelShortList(shortListHotelNode, visibleHotelsInShortList);
		    }
	    }
    },

    setFilterFromForm: function(mode)
    {
	this.stepsHasBeenInit = '';
	this.steps = 1;
	$('sortByPreferred').checked = 'checked';

	if (mode == 'all')
	    {
		//show shortlist
		TNGui.showHide($('hotelShortListings'), false);
		TNGui.showHide($('filterContainer'), false);
	
		if(hotelList.cityPartSelectBox) 
		    hotelList.cityPartSelectBox.selectedIndex = 0;
		if(hotelList.cityRatingsSelectBox)
		    hotelList.cityRatingsSelectBox.selectedIndex = 0;
		remove_childs(this.hotelStepParent);
		this.filterMode = 'all';
		this.currentStep = 1;
		this.currentHotelArray = Utils.copyArray(this.staticHotelArray);
		this.buildHotelHtml();
	    }

	if (mode == 'advanced')
	    {
		remove_childs(this.hotelStepParent);
		this.currentHotelArray = Utils.copyArray(this.staticHotelArray);
		this.filterMode = 'advanced';
		this.currentStep = 1;
		
		if (!($("formDhCityPartId")) || $("formDhCityPartId").value == '')
		    {
			dhCityPartId = null;
		    }	
		else
		    {
			var dhCityPartId = $("formDhCityPartId").value;
		    }

		var formRatings = $("formRatings").value;
		if (formRatings == '')
		    {
			ratings = null;
		    }
		else
		    {
			var ratings = new Array();
			for (i=formRatings; i<=5; i++)
			    {
				ratings.push(i);
			    }
		    }
		this.buildFilteredHotelObjects(dhCityPartId, ratings, null);
		this.buildHotelHtml();
	    }
	if (mode == 'topsecret')
	    {
		//Hide shortlist
		TNGui.showHide($('hotelShortListings'), true);
		TNGui.showHide($('filterContainer'), true);
		remove_childs(this.hotelStepParent);
		this.filterMode = 'topsecret';
		this.currentStep = 1;
		this.buildFilteredHotelObjects(null, null, 100);
		this.buildHotelHtml();
	    }
    },

    sortHotels: function(event)
    {
	var mode = hotelManager.getHotelIdFromEventElement(event);
	this.stepsHasBeenInit = '';
	this.steps = 1;
	this.currentStep = 1;
	this.sortMode = mode;
	remove_childs(this.hotelStepParent);
	if (mode == 'sortByPreferred')
	    {
		this.currentHotelArray = Utils.copyArray(this.staticHotelArray);
		if (this.filterMode != 'all')
		    {
			this.setFilterFromForm(this.filterMode);
		    }
		else
		    {
			this.buildHotelHtml();
		    }
	    }

	else if (mode == 'sortByPrice')
	    {
		this.currentHotelArray.sort(comparePrice);
		this.buildHotelHtml();
	    }

	else if (mode == 'sortByName')
	    {
		this.currentHotelArray.sort(compareName);
		this.buildHotelHtml();
	    }

	else if (mode == 'sortByCustomerRating')
	    {
		this.currentHotelArray.sort(compareCustomerRating);
		this.currentHotelArray.reverse();
		this.buildHotelHtml();
	    }
	
	else if (mode == 'sortByMostSold')
	    {
		this.currentHotelArray.sort(compareMostSold);
		this.currentHotelArray.reverse();
		this.buildHotelHtml();
	    }
	
	function comparePrice(a,b)
	{
	    return a.cheapestPrice - b.cheapestPrice;
	}

	function compareName(a,b)
	{

	    if(a.name == b.name){

		if(a.name == b.name){
		    return 0;
		}

		return (a.name < b.name) ? -1 : 1;
	    }

	    return (a.name < b.name) ? -1 : 1;
	}

	function compareCustomerRating(a,b)
	{
	    return a.customerRating - b.customerRating;
	}

	function compareMostSold(a,b)
	{
	    return a.sold - b.sold;
	}
    }
};