/**
 * A single deal (shown in either a map infowindow,
 * in the seeqdeals area, or on the restaurant-detail page)
 */

mesq.Deal = Class.create();
Object.extend(mesq.Deal.prototype, {
	
	// objects
	container: null,
	listItem: null, // Mesq.ListItem
	
	// data
	data: null,
	
	// strings
	strConfirmDealDelete: 'Do you really want to delete this deal?',
	
	// cache
	_cachedFunc_vote:null,
	
	initialize: function(domContainer, listItem) {
		this.container = $(domContainer);
		this.data = {};
		this.data.ID = Number(this.container.id.replace(/Deal/,''));
		this.listItem = listItem;
		
		this._cachedFunc_vote = this.vote.bind(this);
		
		this.setup();
	},
	
	setup: function() {
		this.container.select('.vote a.votelink').each(function(el) {
			Event.stopObserving(el, 'click', this._cachedFunc_vote);
			Event.observe(el, 'click', this._cachedFunc_vote);
		}.bind(this));
		
		this.container.select('a.delete').each(function(el) {
			Event.stopObserving(el, 'click');
			Event.observe(el, 'click', this.remove.bind(this));
		}.bind(this));

		this.container.select('a.linkInfoWindowMax').each(function(el) {
			Event.stopObserving(el, 'click');
			Event.observe(el, 'click', this.showWithInfoWindow.bind(this));
		}.bind(this));
	},
	
	vote:function(e) {
		var el = Event.findElement(e, 'a');
		new Ajax.Request(
			'deal/vote/' + this.data.ID + '?vote=' + $w(el.className)[0],
			{
				onComplete: this.vote_onSuccess.bind(this),
				onFailure: window.app.ajaxErrorHandler
			}
		);
		
		e.stop(); return false;
	},
	
	vote_onSuccess: function(response) {
		this.container.down('.vote').replace(response.responseText.stripScripts());

		this.setup();

		if(typeof this.listItem != 'undefined') this.listItem.refreshContent();
		
		this.container.fire('Deal:vote');
	},
	
	remove: function(e) {
		var confirmed = confirm(this.strConfirmDealDelete);
		
		if(confirmed) {
			var el = Event.element(e);
			new Ajax.Request(
				el.href,
				{
					onComplete: this.remove_onSuccess.bind(this),
					onFailure: window.app.ajaxErrorHandler
				}
			);
		}
		
		
		if(e) { Event.stop(e);return false; }
	},
	
	remove_onSuccess: function(response) {
		this.container.fire('Deal:remove');
		
		this.container.hide();	
	},
	
	showWithInfoWindow: function(e) {
		this.listItem.openInfoWindowMax();
		
		new Effect.ScrollTo('Map');
		
		if(e) { Event.stop(e);return false; }
	}
});





/**
 * Represents deals in a list-format under the map and links to restaurant-information
 * within the map infowindows.
 * Gets the data from ajax-results triggered by mesq.Map and mesq.List.
 */
mesq.DealList = Class.create();
Object.extend(mesq.DealList.prototype, {
	
	// objects
	container:null,
	listContainer:null,
	list:null, // mesq.List
	deals:null, // mesq.Deal collection
	map:null, // mesq.Maq
	items:null,
	
	// config
	previewItemCount: 3,
	breakItemCount: 2,
	
	// cache
	_cachedFunc_itemOnClick:null,
	
	// messages
	strNoFound: '<p class="note">No deals found</p>',
	strMore: 'Show more',
	strLess: 'Show less',
	
	initialize: function(domContainer, list, map) {
		this.container = $(domContainer);
		this.listContainer = this.container.down('.deals');
		this.list = list;
		this.map  = map;
		this.deals = $A([]);
		
		this._cachedFunc_itemOnClick = this.itemOnClick.bind(this);
		
		// toggle deal events
		Event.observe(this.container, 'Deal:remove', this.refresh.bind(this));
		//Event.observe(this.container, 'Deal:vote', this.refresh.bind(this));
		
		Event.observe(this.list.container, 'List:load', this.refresh.bind(this)); 
		Event.observe(this.container.down('.toggle'), 'click', this.toggle.bind(this)); 
		
		//if(!this.map.searchEnabled()) this.container.up('.box').hide();
	},
	
	refresh: function(e) {
		// don't apply if search is still in progress
		if(this.map.isSearching()) return false;
		
		if(window.app.debug) console.debug("DealList.refresh() called");
		if(window.app.debugprofile) console.time('mesq.DealList.refresh()');
		
		this.clear();
		
		this.container.down('.loading').show();
		
		if(this.list.items.length > 0) {
			this.listContainer.insert('<div class="firstItems"></div>');
			this.listContainer.insert('<div class="allItems"></div>');
			this.listContainer.down('.allItems').hide();
			var countPlacesWithDeals = 0;
			
			for(var i=0; i<this.list.items.length; i++) {
				var html = this.list.items[i].getDealHTML();
				
				if(html) {
					// PERFORMANCE
					//html = html.stripScripts();
					if(countPlacesWithDeals < this.previewItemCount) {
						var obj = this.listContainer.down('.firstItems').insert(html);
					} else {
						var obj = this.listContainer.down('.allItems').insert(html);
					}
					
					// HACK more solid dom traversal and attribute-setting
					var mapLink = obj.select('.mapLink').last();
					mapLink._mesqListItemID = this.list.items[i].data.ID; 
					Event.stopObserving(mapLink,'click', this._cachedFunc_itemOnClick);
					Event.observe(mapLink,'click', this._cachedFunc_itemOnClick);
					mapLink = null;
					
					// setup deals
					// TODO Performance: Add deals instead of re-initializing all the time
					obj.select('.deal').each(function(el) {
						this.deals.push(new mesq.Deal(el, this.list.items[i]));
					}.bind(this));
					
					countPlacesWithDeals++;
				}
			}
						
			this.listContainer.insert('<div class="moreLess"><a href="#">' + this.strMore + '</a></div>');
			Event.observe(this.container.down('.moreLess'), 'click', this.moreLess.bind(this));
		} else {
			this.listContainer.update(this.strNoFound);
		}
		
		this.container.down('.loading').hide();
		
		// if there are no more elements to show, hide the "more" link
		if(countPlacesWithDeals <= this.previewItemCount) this.container.down('.moreLess').hide();
		
		window.app.myLightWindow.ss_refreshLinks();
		
		if(window.app.debugprofile) console.timeEnd('mesq.DealList.refresh()');
	},
	
	itemOnClick: function(e, id) {
		var el = Event.element(e);
		new Effect.ScrollTo('Container');
		this.map.openInfoWindowByID(el._mesqListItemID);
		
		Event.stop(e); return false;
	},
	
	moreLess: function(e) {
		this.container.down('.allItems').toggle();
		this.container.down('.moreLess').down('a').update(this.container.down('.allItems').visible() ? this.strLess : this.strMore);
		
		Event.stop(e);
		return false;
	},
	
	toggle: function(e) {
		this.container.down('.toggle').toggleClassName('expanded');
		this.container.down('.deals').toggle();
		this.container.down('.toggle a').update((this.container.down('.deals').visible() ? "collapse" : "expand" ));
		
		if(e) e.stop();
	},
	
	clear: function() {
		this.listContainer.childElements().each(function(el) {
			//Event.stopObserving(el, 'ListItem:selected', this.cached_listItem_onSelectFunc);
			el.remove();
		}.bind(this));
		
		this.deals = $A([]);
	}
});




mesq.DealTypeSelection = Class.create();
Object.extend(mesq.DealTypeSelection.prototype, {
	
});