var AttractionsFront = Class.create({
    initialize: function() {
        console.log('AttractionsFront::initialize');
        
        this.searchDetails = {};
        
		this.sortType = 'default';
		this.sortDirection = 'none';
		
        this.selectedActivityId = $('results').getAttribute('activityId');
        
		this.itemsPerPage = 10;
		this.curPage = 1;
		
        this.timer = 0;
        this.maxExecutionTime = 60;
        this.showResultsAfterTime = 20;
        
        this.attractionsStorage = new AttractionsStorage();
		this.attractionsView = new AttractionsView();
        
		$('sortType').observe('change', this.changeSortType.bindAsEventListener(this));
		$('sortDirection').observe('change', this.changeSortDirection.bindAsEventListener(this));
        
        this.startSearch();
    },
	getStorage: function() {
		return this.attractionsStorage;
	},
	getView: function() {
		return this.attractionsView;
	},
    startSearch: function() {
        console.log('AttractionsFront::startSearch');
        
        this._startTimer();
        this._doRequestForStartSearch();
    
        this.getView().showResults.delay(this.showResultsAfterTime);
        
    },
	setPage: function(pageNum) {
		this.curPage = pageNum;
		this.redrawList();
	},
	redrawList: function() {
		console.log('AttractionsFront::redrawList');

		var index = this.getStorage().getIndex(this.getIndexAlias());
        
        try {
        
        var activities = $H({});
        this.getStorage().availabilityActivitiesIds.each(function(activityId) {
            var activityName = this.getStorage().activities.get(activityId);
            activities.set(activityId, activityName);
        }, this); 
        
		this.getView().assign('numItems', index.length)
                      .assign('activities', activities)
                      .assign('currencySymbol', this.searchDetails.currencySymbol)
                      .assign('selectedActivityId', this.selectedActivityId)
                      .assign('selectedActivityName', this.selectedActivityName)
		              .assign('location', $('results').getAttribute('locationName'))
		              .updateHeader()
					  .clearPage();

		
		var pages = index.inGroupsOf(this.itemsPerPage);
        
		this.getView().assign('numPages', pages.length)
					  .assign('itemsPerPage', this.itemsPerPage)
					  .assign('curPage', this.curPage)
					  .updatePaging();

        this.getView().assign('curItemTypeFlag', false);
        
		pages.size() && pages[this.curPage - 1].compact().each(function(id) {
            var item = window.atFront.attractionsStorage.data[id];
            
            var isCommercial = this.getStorage().isDirectVendor(item.vendorId) ||
                               this.getStorage().isCommercialVendor(item.vendorId);

            if (this.getStorage().isCommercialVendor(item.vendorId)) {
                var vendor = this.getStorage().getVendorById(item.vendorId);
                this.getView().assign('vendor', vendor);
            } else {
                this.getView().assign('vendor', null);
            }
            
            try {               
			this.getView().assign('name', item.name)
			              .assign('vendorId', item.vendorId)
			              .assign('url', item.url)
			              .assign('isCommercial', isCommercial) 
						  .assign('price', item.price)
			              .assign('image', item.image && item.image.url || '')
			              .assign('description', item.description)
                          .buildItem();
            } catch (e) {
                console.log(e);
            }
		}, this);
        
        this.getView().drawPage();
        } catch (e) {
            console.log(e);
        }
	},
    _startGrabResults: function(response) {
        console.log('AttractionsFront::_startGrabResults');
		
        this.searchDetails = response.responseJSON;
        
        this.getStorage().setVendors(this.searchDetails.vendors);
        this.getStorage().setActivities($H(this.searchDetails.activities));
        
        var vendorAliases = this.getStorage().getVendors().collect(
            function(vendor) { return vendor.alias.toLowerCase() }
        ).without('atdw');
        
        this.getView().assign('vendorAliases', vendorAliases)
                      .assign('currentVendorLogoId', 0)
                      .switchLogo();
        
        this._getNewResults();
    },
    _getNewResults: function() {
        console.log('AttractionsFront::_getNewResults');
        
        this._doRequestForGetResults();
    },
    _stopSearch: function() {
        console.log('AttractionsFront::_stopSearch');
        this.getView().hideSearchIndicator();
        this._stopTimer();
    },
    _startTimer: function() {
        this.timerUpdater = setInterval(function() { this.timer++; }.bind(this), 1000);
    },
    _stopTimer: function() {
        clearInterval(this.timerUpdater);
    },
    _proccessResults: function(response) {
        console.log('AttractionsFront::_proccessResults');
		if (response.responseJSON.attractions.length != 0) {
			this.getStorage().update(response.responseJSON.attractions);
			console.log(this.getStorage());
			this.redrawList();
            this.getView().showResults();
		}
        
		if (response.responseJSON.activeVendors.length == 0) {
			console.info('No active vendors');
            this._stopSearch();
			this.getView().showResults();
			return;
		}

        try {         
        if (this.timer < this.maxExecutionTime) {
            this._getNewResults.bind(this).delay(5);
        } else {
			console.warn('client timeout');
            this._stopSearch();
			this.getView().showResults();
			return;
        }
        } catch (e) {
            console.log(e);
        }
    },
    _doRequestForStartSearch: function() {
        console.log('AttractionsFront::_doRequestForStartSearch');
        var params = {locationId: $('results').getAttribute('locationId'),
                      activityId: $('results').getAttribute('activityId')};
        new Ajax.Request('/attractions-search/start/', 
            { method: 'post', 
              parameters: $H(params).toQueryString(), 
              onComplete: this._startGrabResults.bind(this) }
        );
    },
    _doRequestForGetResults: function() {
        console.log('AttractionsFront::_doRequestForGetResults');
        params = { searchId: this.searchDetails.searchId, 
                   sessionId: this.searchDetails.sessionId };
        new Ajax.Request('/attractions-search/get-results/', 
            { method: 'post', 
              parameters: new Hash(params).toQueryString(), 
              onComplete: this._proccessResults.bind(this) }
        );
    },
	changeSortType: function(event) {
		console.log('AttractionsFront::changeSortType');
		this.sortType = $F(event.element());
        if (['name', 'price'].include(this.sortType)) {
            if (this.sortDirection == 'none') {
                this.sortDirection = 'asc';
                this.getView().showSortDirectionDropdown();
            }
        } else {
            this.sortDirection = 'none';
            this.getView().hideSortDirectionDropdown();
        }
		this.redrawList();
		
	},
	changeSortDirection: function(event) {
		console.log('AttractionsFront::changeSortDirection');
		this.sortDirection = $F(event.element());
		this.redrawList();
	},
    changeActivityFilter: function(event) {
        console.log('AttractionsFront::changeActivityFilter');
        this.curPage = 1;
        this.selectedActivityId = $F(event.element());
        this.redrawList();
    },
	getIndexAlias: function() {
		return [this.selectedActivityId, '_', this.sortType, '_', this.sortDirection].join('');
	}

	
});
