// Metroseeq namespace
var mesq = mesq || {};



/**
 * The "what"/"where" form that triggers
 * results on the map after a page-refresh
 * (no ajax-integration for now).
 * 
 * Used for both "Deal Hunt" and normal "Place Search"
 * (PlaceSearchForm.php and DealSearchForm.php on the serverside).
 */
mesq.SearchForm = Class.create();
Object.extend(mesq.SearchForm.prototype, {
	
	// objects
	container: null,
	carousel: null,
	
	// strings
	strValidationAddWhere: 'Please tell us where you\'re searching',
	
	initialize: function(domContainer) {
		if(window.app.debugprofile) console.time('mesq.SearchForm.initialize()');
		
		this.container = $(domContainer);
		if(!this.container) return false;
		
		this.container.focusFirstElement();
		
		Event.observe(this.container,'submit',this.validate.bind(this));
		
		this.setupLists();
		
		if($('Choose')) {
			var carouselItems = $('Choose').select('li');
			this.carousel = new Carousel(
				'Choose', 
				{
					animParameters:{duration:0.5}, 
					buttonStateHandler:this.carouselButtonStateHandler, 
					size:carouselItems.length,
					scrollInc: 4
				}
			);
			// handling click events
			carouselItems.each(function(el) {
				Event.observe(el, 'click', function(e) {
					var el = Event.findElement(e, 'a');
					var params = el.href.toQueryParams();
					
					this.container.down('input[name=what]').value = params.what.urldecode().stripTags();
					
					// if "where" is populated, we can fire off the query
					if($F(this.container.down('input[name=where]'))) {
						document.location.href = 'place/?' + this.container.serialize() + "&foodonly=1";
					}						

					e.stop();
				}.bind(this));
			}.bind(this));
		}
		
		if(window.app.debugprofile) console.timeEnd('mesq.SearchForm.initialize()');
	},
	
	setupLists: function() {
		if($('ListCuisines')) {
			$$('#ListCuisines a').each(function(el) {
				Event.observe(el, 'click', function(e) {
					var params = el.href.toQueryParams();
					// if "where" is populated, we can fire off the query
					this.container.down('input[name=what]').value = params.what.urldecode().stripTags();
					
					if($F(this.container.down('input[name=where]'))) {
						document.location.href = 'place/?' + this.container.serialize() + "&foodonly=1";
					}	
					Event.stop(e);
					return false;
				});
			});
			new Tip(
				'ListCuisinesLink',
				$('ListCuisines'),
				Object.extend(PROTOTIP_OPTIONS, {
					hideOn: {element: '.close', event: 'click'}, 
					hook:{target: 'bottomLeft', tip: 'topLeft'}
				})
			);
			//el = null;
		}
		if($('ListCities')) {
			$$('#ListCities a').each(function(el) {
				Event.observe(el, 'click', function(e) {
					var params = el.href.toQueryParams();
					$('UserSearch').down('input[name=where]').value = params.where.urldecode().stripTags();
					Event.stop(e);
					//var form_el=Event.findElement(e, 'form');
					//if(form_el!='document'){
					//	form_el.submit();
					//}
					var form_el=$('DealSearchForm_DealSearchForm');
					if(form_el)
						form_el.submit();
						
					return false;
				});
			});
			new Tip(
				'ListCitiesLink',
				$('ListCities'),
				Object.extend(PROTOTIP_OPTIONS, {
					hideOn: {element: '.close', event: 'click'}, 
					hook:{target: 'bottomLeft', tip: 'topLeft'}
				})
			);
			//el = null;
		}		
	},
	
	validate: function(e) {
		this.reset();
		
		if(!$F($$('#where input').first())) {
			this.addError('where', this.strValidationAddWhere);
			Event.stop(e);
		}
	},
	
	carouselButtonStateHandler: function(button, enabled) {
		$$('#' + button).invoke("addClassName", enabled ? 'enabled' : 'disabled').invoke("removeClassName", enabled ? 'disabled' : 'enabled');
	},
	
	addError: function(fieldID, errorMsg) {
		var field = $(fieldID);
		field.addClassName('error');
		var errorNode = new Element('span', {'class':'message required'});
		field.appendChild(errorNode);
		errorNode.appendChild(new Element('span').update(errorMsg.stripScripts()));
	},
	
	reset: function() {
		this.container.select('field').each(function(el) {
			el.removeClassName('error');
		});
		this.container.select('span.message').each(function(el) {
			el.remove();
		});
		
	}
});







mesq.WheelOfMeals = Class.create();
Object.extend(mesq.WheelOfMeals.prototype, {
	
	// objects
	container: null,
	swfContainer: null,
	so: null,
	localSearch: null,
	
	// config
	swfURL: 'mesq/images/wheelofmeals/wheelofmeals.swf',
	xiURL: 'mesq/javascript/swfobject2/expressinstall.swf',
	width: 335,
	height: 345, 
	backgroundColor: '#fff',
	minFlashPlayerVersion: "8.0.0",
	
	initialize: function(domContainer) {
		this.container = $(domContainer);
		this.swfContainer = $(this.container.identify() + 'Flash');
		
		if(this.swfContainer) {
			swfobject.embedSWF(
				this.swfURL,
				this.swfContainer.identify(),
				this.width,
				this.height,
				this.minFlashPlayerVersion,
				this.xiURL,
				false,
				{
					bgcolor: this.backgroundColor,
					wmode: 'transparent'
				} 
			);
		}

   		this.localSearch = new GlocalSearch();
		this.localSearch.setNoHtmlGeneration();
		this.localSearch.setResultSetSize(GSearch.LARGE_RESULTSET);
		//this.localSearch.setAddressLookupMode(GlocalSearch.ADDRESS_LOOKUP_DISABLED);
		this.localSearch.setSearchCompleteCallback(this, this.localSearch_onComplete.bind(this,this.localSearch));
	},
	
	getRandomPlace: function(what, where) {
		if(!what || !where) return false;
		this.localSearch.setCenterPoint(where);
		this.localSearch.execute(what + ' ' + mesq.PlaceMap.prototype.queryAddition);
	},
	
	getLocation: function() {
		if(window.app.debug) console.debug('WheelOfMeals:getLocation()');
		return $F('PlaceSearchForm_PlaceSearchForm_where');
	},
	
	localSearch_onComplete:function(searcher) {
		if(!searcher || searcher.results.length == 0) {
			if(window.app.debug) console.debug("WheelOfMeals.localSearch_onComplete: No GLocal results");
			this.sendToFlash(false);
			return false;
		}
		
		var randomPlace = searcher.results[Math.floor(Math.random()*searcher.results.length)];
		if(!randomPlace) {
			if(window.app.debug) console.debug("WheelOfMeals.localSearch_onComplete: Randomizer failed");
			this.sendToFlash(false);
			return false;
		}
		var phoneNumber = (randomPlace.phoneNumbers) ? randomPlace.phoneNumbers[0].number : false;
		if(!phoneNumber) {
			if(window.app.debug) console.debug("WheelOfMeals.localSearch_onComplete: No phonenumber (needed for identification)");
			this.sendToFlash(false);
			return false;
		}
		new Ajax.Request(
			'place/getwheelofmealsdata',
			{
				method:'post',
				parameters: {
					phoneNumber: phoneNumber,
					titleNoFormatting: randomPlace.titleNoFormatting,
					glocalresult: Object.toJSON(randomPlace)
				},		
				onSuccess: this.yelp_onComplete.bind(this),
				onFailure: window.app.ajaxErrorHandler
			}
		);
		
		this.localSearch.clearResults();
		
	},
	
	yelp_onComplete: function(response) {
		this.sendToFlash(response.responseText);
	},
	
	sendToFlash: function(result) {
		var success = $('WheelOfMealsFlash').getRandomPlace_onComplete(result);
		result = null;
	}
});