Element.addMethods({
	getValue: function(element) {
		if(document.all) {
			return $(element).innerText;
		} else {
			return $(element).textContent;
		}
	}
});

function Inspiration() {

	this.debug = false;
	this.peInterval = 1;
	this.pe = null;
	this.wsBase = '/ws/inspiration.svc/getitineraries/';
	this.imagePath = window.location.hostname == 'audleytravel' ? 'http://audleywebapp/imageresizehandler/' : 'http://images1.audleytravel.com/';	
	this.loadString = '<h2><img src="/images/home/inspiration/ajax-loader.gif" />Loading results...</h2>';
	this.data = [];
	this.requestData = false;
	this.qs = null;

	this.init = function() {
		
		// add the combo box to each dropdown
		$$('.dropdown .control').each(function(el){
			el.observe('click', this.toggleDropdown.bind(this));
		}.bind(this));
		
		// add hover states & clicks to all options
		$$('.option').each(function(option){
			option.observe('mouseover', function(ev){
				option.addClassName('hover');
			});
			option.observe('mouseout', function(ev){
				option.removeClassName('hover');
			});
			option.observe('click', this.selectOption.bind(this));
		}.bind(this));

		// add the clear form action
		$$('.clearForm a')[0].observe('click', this.clearForm.bind(this));
		
		// create the PE
		this.pe = new PeriodicalExecuter(this.fetch.bind(this), this.peInterval);
		
		this.updateFromHash();

	}

/* http://audleytravel/Inspiration/Itineraries.aspx#
type={F1A27324-B879-461E-8C30-5D50A4D72C4B}|
duration=14|
budget=2500|
continent={1B591514-3088-4D9F-B70D-666FCEB0714D}|
*/

	this.updateFromHash = function() {
		hash = window.location.hash;
		hash = hash.replace('#', '');
		if(hash != '' && hash != null) {
			pairs = hash.split('|');
			pairs.each(function(pair){
				parts = pair.split('=');
				key = parts[0];
				value = parts[1];
				value = value.replace('{', '');
				value = value.replace('}', '');
				switch(key) {
					case 'type':
					case 'duration':
					case 'budget':
					case 'continent': 
						li = $('id-' + value);
						if(li) {
							if(this.debug) console.log('Found element #' + li.identify());
							id = li.identify();
							this.selectOption(id);
						}
					break;
					default:
					break;
				};
			}.bind(this));
		}
	}
	
	this.toggleDropdown = function(ev) {
		box = (ev.element().hasClassName('box')) ? ev.element() : ev.element().up('.box');
		options = box.down('.options');
		if(options.visible()) {
			// hide the options
			options.hide()
		} else {
			// hide all other options and show the current option
			$$('.box .options').each(function(el){
				if(el.visible()) {
					el.hide();
				}
			})
			options.show();
		}
	}

	this.toggleClearForm = function() {
		if(this.qs == null || this.qs == '') {
			$$('.clearForm')[0].hide();
		} else {
			$$('.clearForm')[0].show();
		}
	}
	
	this.fetch = function() {
		if(this.requestData && this.qs != '' && Ajax.activeRequestCount == 0) {
			url = this.wsBase + this.qs;
			if(this.debug) console.log('Webservice URL: ', url);

			// create the ajax request
			request = new Ajax.Request(url, {
				method: 'get',
				onCreate: function(transport) {
					$$('.results')[0].update(this.loadString);
				}.bind(this),
				onSuccess: function(transport) {
					this.transport = transport;
					
					results = transport.responseXML.documentElement.firstChild.childNodes;
					
					this.parseResponse(results);
					this.formatResponse();
					
				}.bind(this),
				onFailure: function(transport) {
					this.transport = transport;					
					$$('.results')[0].update('<h2>No results found</h2>');
				}.bind(this),
				onComplete: function(transport) {
					// if(this.debug) console.log('Request returned: ', transport.status, transport.statusText);
					this.requestData = false;
				}.bind(this)
			});

			this.requestData = false;

		}
	}
	
	this.parseResponse = function(results) {
		
		// clear the data global var
		this.data = [];
		
		// count the results
		var numResults = results.length
		$$('.results')[0].update('<h2>We recommend (' + numResults + ' results):</h2>');
		
		for(var i = 0; i < numResults; i++) {
			result = results[i];
			
			var itinName = (result.getElementsByTagName('Name')[0].firstChild != null) ? result.getElementsByTagName('Name')[0].firstChild.data : null;
			var iconicImage = (result.getElementsByTagName('IconicImage')[0].firstChild != null) ? result.getElementsByTagName('IconicImage')[0].firstChild.data : null;
			var uri = (result.getElementsByTagName('Uri')[result.getElementsByTagName('Uri').length-1].firstChild != null) ? result.getElementsByTagName('Uri')[result.getElementsByTagName('Uri').length-1].firstChild.data : null;
			var days = (result.getElementsByTagName('Days')[0].firstChild != null) ? parseInt(result.getElementsByTagName('Days')[0].firstChild.data) : null;
			var fromPrice = (result.getElementsByTagName('FromPrice')[0].firstChild != null) ? parseInt(result.getElementsByTagName('FromPrice')[0].firstChild.data) : null;
			var excerpt = (result.getElementsByTagName('Excerpt')[0].firstChild != null) ? result.getElementsByTagName('Excerpt')[0].firstChild.data : null;
			
			if(this.debug) console.log('Pushing', i+1, 'of', numResults, '- ', itinName, ':', fromPrice);

			this.data.push({
				'name': itinName,
				'iconicImage': iconicImage,
				'uri': uri,
				'days': days,
				'fromPrice': fromPrice,
				'excerpt': excerpt
			});
			
		}
	}

	this.formatResponse = function() {

		if(this.debug) console.log('Showing results...');
		
		var pane = $$('.results')[0];
		pane.update('');
		
		switch(this.data.length) {
			case 0:
				pane.update('<h2>No results</h2>');
			break;
			case 1:
				pane.update('<h2>We recommend (one result):</h2>');
			break;
			default:
				pane.update('<h2>We recommend (' + this.data.length + ' results):</h2>');
			break;
		}
		
		container = new Element('div', {'class': 'resultsContainer'});
		
		this.data.each(function(itin){
			
			var result = new Element('div', {'class': 'result'});
			
			if(itin.iconicImage != null) {
				result.insert(
					new Element('a', {
						'class': 'iconic',
						'href': itin.uri,
						'title': 'Read more'
					}).insert(
						new Element('img', {
							'class': 'iconic',
							'src': this.imagePath + '?w=140&h=100&q=80&id=' + itin.iconicImage
						})
					)
				);
			} else {
				result.insert(
					new Element('a', {
						'class': 'iconic',
						'href': itin.uri,
						'title': 'Read more'
					}).insert(
						new Element('div', {
							'class': 'iconic fauxImage'
						})
					)
				);
			}
			result.insert(
				new Element('h3').insert(
					new Element('a', {
						href: itin.uri,
						title: 'Read more'
					}).update(itin.name)
				)
			);
/*
			if(itin.excerpt) {
				result.insert(
					new Element('p').update(itin.excerpt)
				);
			}
*/
			meta = new Element('p', {'class': 'meta'}); /* , {class: 'meta'}*/
			if(itin.fromPrice != null && itin.fromPrice != 0 && itin.days != null) {
				meta.update(itin.days + ' days from &pound;' + itin.fromPrice + 'pp');
			}
			if(itin.fromPrice != null && itin.fromPrice != 0 && itin.days == null) {
				meta.update('From &pound;' + itin.fromPrice + 'pp');
			}
			if((itin.fromPrice == null || itin.fromPrice == 0) && itin.days != null) {
				meta.update(itin.days + ' days');
			}
			
			result.insert(meta);
			
			container.insert(result);
		}.bind(this));
		
		pane.insert(container);
			
	}

	this.selectOption = function(ev) {
		
		if(typeof ev == 'object') {
			ev.stop();
			el = ev.element();
		} else {
			el = $(ev);
		}
		
		option = (el.tagName == 'LI') ? el : el.up('li');
		
		box = option.up('.box');
		
		// if the option is a filter and is selected, unselect it
		if(box.id == 'filter' && option.hasClassName('selected')) {
			option.removeClassName('selected');
		} else {
		
			// clear all other selected options
			box.select('.selected').each(function(el){
				el.removeClassName('selected');
			});
		
			// select the clicked option
			option.addClassName('selected');
		
			// if it's a dropdown, close it and update the value
			if(box.hasClassName('dropdown')) {
				box.down('.options').hide();
				box.down('.value').update(option.down('.title').getValue());
			}
		
		}
			
		this.updateForm();
		
	}

	this.clearForm = function(ev) {
		ev.stop();
		$$('.box').each(function(box){
			box.select('.selected').each(function(el){
				el.removeClassName('selected');
			})
			if(box.down('.value')) {
				box.down('.value').update();
			}
			if(box.select('ul').length > 1) {
				box.select('ul').map(Element.hide);
			}
		});
//		$('filter');
		$$('.results')[0].update();
		this.updateForm();
	}

	this.getQS = function() {
		var qs = '';
		if(this.typeID() != null) {
			qs = qs + 'type=' + this.typeID();
			qs = qs + '|';
		}
		if(this.duration() != null) {
			qs = qs + 'duration=' + this.duration();
			qs = qs + '|';
		}
		if(this.budget() != null) {
			qs = qs + 'budget=' + this.budget();
			qs = qs + '|';
		}
		if(this.filter() != null) {
			qs = qs + 'continent=' + this.filter();
			qs = qs + '|';
		}
		window.location.hash = qs;
		return qs;
	}
	
	this.getID = function(el) {
		if(el.down('.selected .id') && el.down('.selected .id').getValue() != 0) {
			return el.down('.selected .id').getValue();
		} else {
			return null;
		}
	}

	this.typeID = function() {
		return this.getID($('typeBox'));
	}

	this.duration = function() {
		return this.getID($('durationBox'));
	}

	this.budget = function() {
		return this.getID($('budgetBox'));
	}

	this.filter = function() {
		return this.getID($('filter'));
	}

	this.updateForm = function() {
		newQS = this.getQS()
		if(this.debug) {
			console.log('Old QS: ', this.qs);
			console.log('New QS: ', newQS);
		}
		if(newQS != this.qs) {
			if(this.debug) console.log('Query string: ', newQS);
			this.qs = newQS;
			this.requestData = true;
		}
		this.toggleClearForm();
	}

	this.init();
	
}

document.observe('dom:loaded', function(ev){
	i = new Inspiration();
});
