function initialize() {
	var ajax = new AjaxApp({ pageLoader: $('loading'), baseUrl: '/xml.php' });
	var app = new CoreWebApp($('content').readAttribute('type'), ajax);
	CoreWebApp.setInstance(app);

	app.classOptions = [
		// Global
		{cssClass: 'input[type=text]', action: initializeInputHint, attributes: {} },
		{cssClass: 'textarea', action: initializeInputHint, attributes: {} },
		{cssClass: 'input[type=password]', action: initializeInputHint, attributes: {} },
		{cssClass: 'input.date', onclick: actionSelectDate, attributes: { } },
		{cssClass: '.window .close', onclick: closeWindow, attributes: { href: '#', title: 'Sluit venster'} },
		{cssClass: 'ul.results .question a', onclick: actionFaqToggle },
		{cssClass: '#movie #player', action: embedFlash, attributes: {} },
		{cssClass: '#rotatebanner', action: initializeHomeBanner, attributes: {} },

		// name search
		{cssClass: '#sitesearch', action: initializeSiteSearch, attributes: {} },

		// login
		{cssClass: 'a.login', onclick: actionLoadLoginPopup, attributes: { title: 'Inloggen' } },
		{cssClass: 'input.login', onclick: actionLogin, attributes: { title: 'Inloggen' } },
		{cssClass: 'a.logout', onclick: actionLogout, attributes: { href: '#', title: 'Uitloggen' } },

		// signup
		{cssClass: 'a.signup', onclick: actionLoadSignupPopup, attributes: { href: '#' } },
		{cssClass: '.cardholder input', onblur: actionSetAccountInfo, attributes: {} },
		{cssClass: '.cardholder select', onchange: actionSetAccountInfo, attributes: {} },
		{cssClass: 'input.button.signup', onclick: actionSignUp, attributes: {} },
		{cssClass: 'input.button.activate', onclick: actionActivate, attributes: {} },

		// invite users
		// {cssClass: '.button.invite', onclick: actionSendInvites, attributes: {} },

		// request number
		{cssClass: 'a.requestlogin', onclick: actionLoadRequestLoginPopup, attributes: { href: '#', title: 'Login vergeten?' } },
		{cssClass: 'a.directrequestlogin', onclick: actionDirectRequestLogin, attributes: { href: '#', title: 'Login opvragen' } },
		{cssClass: 'input.requestlogin', onclick: actionRequestLogin, attributes: { title: 'Login opvragen' } },
		{cssClass: '#requestform #emailaddress', onkeydown: actionRequestLogin, attributes: { } },

		// selection options
		{cssClass: '.options select', onchange: actionAddCriteria, attributes: { } },
		{cssClass: '.selectionlist li a', onclick: actionRemoveCriteria, attributes: { href: '#' } },
		{cssClass: '.clear_selection', onclick: actionClearCriteria, attributes: { href: '#' } },

		// search results
		// {cssClass: '.select_price', onclick: actionStartBookSteps, attributes: {href: '#'} },

		// imagegallery
		{cssClass: '.imagegallery', action: initializeGallery },
		{cssClass: '.imagegallery ul', onclick: actionLoadImage },

		// Price table
		{cssClass: '.pricetable', onclick: actionSelectPrice, attributes: {href: '#'} },
		{cssClass: 'table a.pricetable_scroll', onclick: actionPriceTableScroll, attributes: { href: '#'} },
		{cssClass: '.priceoptions select', onchange: actionPriceTableUpdate, attributes: { } },
		{cssClass: 'div.dateslider', action: initializePriceTableSlider },
		// {cssClass: 'div.dateslider .months', onclick: actionSetPriceTableSlider },

		// Price breakdown
		// {cssClass: '#pickcompany select', onchange: actionPickCompany, attributes: { } },
		// {cssClass: '.pick_persons select', onchange: actionSetPersons, attributes: {title: 'Selecteer personen'} },
//		{cssClass: '.pick_persons input', action: initializePersonInfo, attributes: { } },
//		{cssClass: '.pick_persons .remove', onclick: actionRemovePerson, attributes: { } },
//		{cssClass: '.pick_persons .add', onclick: actionAddPerson, attributes: { } },

//		{cssClass: '.addroom', onclick: actionAddRoom, attributes: {href: '#', title: 'Kamer toevoegen'} },
//		{cssClass: '.setroom', onchange: actionSetRoom, attributes: {title: 'Kamer aantal kiezen'} },
//		{cssClass: '.removeroom', onclick: actionRemoveRoom, attributes: {href: '#', title: 'Kamer verwijderen'} },

		{cssClass: '.pick_persons_rooms', action: initializePersonRoomPicker, attributes: { } },

//		{cssClass: '.roomassigner input', onclick: actionAssignRoom, attributes: {title: 'Wijs persoon toe'} },
		{cssClass: '.changeroom', onclick: actionToggleRoom, attributes: { title: 'Wijzig verblijf' } },
		{cssClass: '.roomchanger .setroom', onclick: actionChangeRoom, attributes: { } },

		{cssClass: '.changeflight', onclick: actionToggleTransport, attributes: { title: 'Wijzig transport' } },

		// {cssClass: '#saveroom', onclick: actionSaveRoom, attributes: { } },
		// {cssClass: '#savetransport', onclick: actionSaveTransport, attributes: { } },

		{cssClass: '.showroomtransport', onclick: actionShowRoomTransport, attributes: { } },
		{cssClass: '#recalculate', onclick: actionRecalculate, attributes: { } },

		{cssClass: '.pick_to input', onclick: actionSetTransport.curry('to'), attributes: {title: 'Selecteer transport'} },
		{cssClass: '.pick_to select', onchange: actionSetTransport.curry('to'), attributes: {title: 'Selecteer klasse'} },
		{cssClass: '.pick_from input', onclick: actionSetTransport.curry('from'), attributes: {title: 'Selecteer transport'} },
		{cssClass: '.pick_from select', onchange: actionSetTransport.curry('from'), attributes: {title: 'Selecteer klasse'} },
		{cssClass: '.train .toggle a', onclick: actionToggleScheme.curry('toggled'), attributes: { } },

//		{cssClass: '.check_price', onclick: actionLoadPriceBreakdown, attributes: {title: 'Bekijk prijsspecificatie'} },
		{cssClass: '.booktrip', onclick: actionStartBookTrip, attributes: {title: 'Deze reis boeken'} },
//		{cssClass: '#checkavailable', onclick: actionStartBookSteps, attributes: { } },

		// invoice route
		{cssClass: '#pickinvoicecompany', onchange: actionPickInvoiceCompany, attributes: { } },
		{cssClass: 'select.touroperator_select', onchange: actionGetTouroperatorComment },
		{cssClass: 'select.transport_select', onchange: actionShowAirport },
		{cssClass: '#correct', onclick: actionShowBooksteps },
		{cssClass: '#incorrect', onclick: actionShowDenied },
		{cssClass: '#invoice_reject .back', onclick: actionShowQuestion },
		{cssClass: '#invoice_accept .back', onclick: actionShowQuestion },
		{cssClass: '#rejectoptions a', onclick: actionSelectRejectOption },
		{cssClass: '#rooms .remove_room', onclick: actionRemoveRoom },
		{cssClass: '#rooms .add_room', onclick: actionAddRoom },
		{cssClass: '#rooms input', onblur: actionSetRoomInfo, attributes: {} },
		{cssClass: '#rooms select', onchange: actionSetRoomInfo, attributes: {} },

		// book route
		{cssClass: '#traveldescription input, #traveldescription select, #comment textarea, #phonehome input', onblur: actionSetOffer, attributes: {} },
		{cssClass: '.personinfo input', onblur: actionSetTravelerInfo, attributes: {} },
		{cssClass: '.personinfo select', onchange: actionSetTravelerInfo, attributes: {} },
		{cssClass: '.add_traveler', onclick: actionAddTraveler, attributes: {} },
		{cssClass: '.remove_traveler', onclick: actionRemoveTraveler, attributes: {} },
		{cssClass: '.coupon select', onchange: actionSetCoupon, attributes: {} },
		{cssClass: 'input.travel', onclick: actionSetInsurance, attributes: {} },
		{cssClass: 'input.person', onclick: actionSetInsurancePerson, attributes: {} },
		{cssClass: 'input.cancel', onclick: actionSetInsurance, attributes: {} },

		// dossier
		{cssClass: 'tr.pick_invoice', onclick: actionPickInvoice },
		{cssClass: '#messagehistory li', onclick: toggleMessage },
		{cssClass: '#sendmessage .toggle', onclick: toggleSendMessage },
		{cssClass: '.profileattribute', onclick: setProfileAttribute },
		{cssClass: '.profileattributeinverse', onclick: setProfileAttributeInverse },
		{cssClass: '.favorite', onclick: actionToggleFavorite },


		// tip cycler
		{cssClass: '.tip', action: initializeTipCycler, attributes: {} }
	];

	cookieCheck();

	if (app.currentPage == 'search') {
		new PeriodicalExecuter(handleHashChange, 0.1); // check hash change
	}

	app.parseSelectors($('container').up());
	// app.parseSelectors($('dossier'));
	// app.parseSelectors($('mainmenu'));
	// app.parseSelectors($('popup_window'));
	// app.parseSelectors($('messages'));
	// loadCheckMyData.bind(app)();
}

function cookieCheck() {
	var app = CoreWebApp.getInstance();

	/*
	if (app.currentPage == 'search') {
		var jar = new CookieJar();
		var cached = jar.get('searchcached');

		if (cached == 1) {
			app.loadContent('selection', $('selection'));
			app.loadContent('searchresults', $('searchresults'));
			app.process();
		}

		jar.put('searchcached', 1);
	}
	*/

	if (app.currentPage == 'booktrip') {
		var jar = new CookieJar();
		var cached = jar.get('booktripcached');

		if (cached == 1) {
			location.reload();
		}

		jar.put('booktripcached', 1);
	}
}

var lastHash = null;
function handleHashChange() {
	var newHash = location.hash;

	if(newHash != lastHash) {
		var app = CoreWebApp.getInstance();
		if (app.currentPage == 'search') {
			if (newHash.indexOf('selection=') > -1) {
				app.deferAction('setSelection', null, { selection: newHash.split('selection=')[1]});
				app.loadContent('selection', $('selection'));
				app.loadContent('searchresults', $('searchresults'));
				app.process();
			}
		}

		lastHash = newHash;
	}
}

function setLocationHash(hash) {
	location.hash = hash;
	lastHash = location.hash;
}

function unloadAll() {
	googlemap = null;
	baseIcon = null;
	carousel = null;
	calendar = null;
	if (GUnload) {
		GUnload();
	}
}

document.observe('dom:loaded', initialize);

/* small section funcs */
var googlemap = null;
// var baseIcon = null;
var iconImage = null;
var highlightImage = null;
var shadowImage = null;
function initializeGoogleMapBase(element, center) {
	$(element).show();

	if (iconImage == null) {
		iconImage = new google.maps.MarkerImage('http://media.tjingo.nl/www/images/googlemap-icon.png', new google.maps.Size(31, 47), new google.maps.Point(0, 0), new google.maps.Point(16, 45));
		highlightImage = new google.maps.MarkerImage('http://media.tjingo.nl/www/images/googlemap-icon-highlight.png', new google.maps.Size(31, 47), new google.maps.Point(0, 0), new google.maps.Point(16, 45));
		shadowImage = new google.maps.MarkerImage('http://media.tjingo.nl/www/images/googlemap-icon-shadow.png', new google.maps.Size(52, 56), new google.maps.Point(0, 0), new google.maps.Point(16, 45));
	}

	var centerLL = new google.maps.LatLng(0,0);
	var centerZoom = 13;
	if (!Object.isUndefined(center)) {
		centerLL = new google.maps.LatLng(center.lat, center.lng);
		centerZoom = center.zoom;
	}

	var options = {
		zoom: centerZoom,
		scrollwheel: false,
		center: centerLL,
		mapTypeId: google.maps.MapTypeId.HYBRID,
		mapTypeControl: true,
		mapTypeControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT, style: google.maps.MapTypeControlStyle.DEFAULT, mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.HYBRID] },
		scaleControl: true,
		scaleControlOptions: { position: google.maps.ControlPosition.BOTTOM_LEFT, style: google.maps.ScaleControlStyle.DEFAULT },
		navigationControl: true,
		navigationControlOptions: { position: google.maps.ControlPosition.TOP_LEFT, style: google.maps.NavigationControlStyle.DEFAULT }
	};

	return new google.maps.Map(element, options);
}

function initializeGoogleMap(element, center, markers) {
	googlemap = initializeGoogleMapBase(element, center);

	if (markers !== null) {
		for(var i=0, len = markers.length; i<len; ++i) {
			marker = markers[i];
			googleMapAddMarker(googlemap, marker.name, marker.lat, marker.lng);
		}
	}
}

function googleMapAddMarker(googleMap, title, lat, lng) {
	return new google.maps.Marker({
		position: new google.maps.LatLng(lat, lng),
		map: googleMap,
		icon: iconImage,
		shadow: shadowImage,
		title: title
	});
}

var currentMarker = null;
var listContainer = null;
var listMarkers = [];
function initializeGoogleMapList(element, center, markers) {
	googlemap = initializeGoogleMapBase(element, center);

	if (markers !== null) {
		listContainer = element.up().down('.container');
		var elements = listContainer.select('li');

		for(var i=0, len = markers.length; i<len; ++i) {
			var index = listMarkers.length;

			marker = markers[i];
			var tmpmarker = googleMapAddMarker(googlemap, marker.name, marker.lat, marker.lng);

			google.maps.event.addListener(tmpmarker, 'click', markerSelect.curry(tmpmarker));

			var tmpelement  = elements[index];
			tmpelement.down('.moreinfo a').update('Meer info');
			Element.observe(tmpelement, 'click', listItemSelect.curry(tmpelement));

			listMarkers[index] = { marker: tmpmarker, element: tmpelement, content: marker.content, infoWindow: marker.infoWindow };

			if (marker.selected) {
				showInfoWindow(listMarkers[index].marker, listMarkers[index].infoWindow);
				gotoMarker(listMarkers[index]);
			}
		}
	}
}

function listItemSelect(element, event) {
	var listMarker = null;
	for(var i=0,len=listMarkers.length;i < len;++i) {
		if (listMarkers[i].element === element) {
			listMarker = listMarkers[i];
			break;
		}
	}

	showInfoWindow(listMarker.marker, listMarker.infoWindow);
	if (currentMarker != listMarker) {
		gotoMarker(listMarker);
	}

	// Event.stop(event);
}

function markerSelect(marker, event) {
	var listMarker = null;
	for(var i=0,len=listMarkers.length;i < len;++i) {
		if (listMarkers[i].marker === marker) {
			listMarker = listMarkers[i];
			break;
		}
	}

	showInfoWindow(listMarker.marker, listMarker.infoWindow);
	if (currentMarker != listMarker) {
		gotoMarker(listMarker);
		Event.stop(event);
	}
}

function gotoMarker(listMarker) {
	if (listMarker !== null) {
		new Effect.Tween(listContainer, listContainer.scrollTop, Element.positionedOffset(listMarker.element).top - (listContainer.getHeight() * 0.5), { duration: 0.5 }, 'scrollTop');
		listMarker.marker.getMap().panTo(listMarker.marker.getPosition());

		if (currentMarker !== null) {
			Element.toggleClassName(currentMarker.element, 'selected');
			currentMarker.marker.setIcon(iconImage);
			currentMarker.marker.setZIndex(null);
		}

		Element.toggleClassName(listMarker.element, 'selected');
		listMarker.marker.setIcon(highlightImage);
		listMarker.marker.setZIndex(1000);

		currentMarker = listMarker;
	}
}

var infoWindow = null;
function showInfoWindow(marker, content) {
	if (content.length > 0) {
		if (infoWindow != null) infoWindow.close();

		infoWindow = new google.maps.InfoWindow({
			content: content,
			pixelOffset: new google.maps.Size(0, 20)
		});

		infoWindow.open(marker.getMap(), marker);
	}
}

/**
 * Load clicked image
 */
/*
var ImageGallery = Class.create({
	initialize: function(element) {
		this.element = element;

		this.current = null;

		this.galleryHtml = new Element('div', {'class': 'gallery'} );

		var previous = new Element('div', {'class': 'button previous disabled'});
		previous.observe('click', previousImage);
		galleryHtml.appendChild(previous);

		var next = new Element('div', {'class': 'button next disabled'})
		next.observe('click', nextImage);
		galleryHtml.appendChild(next);

		var image = new Element('img', {'id': 'galleryimage'});
		galleryHtml.appendChild(image);
		image.observe('click', function() { this.up('.popup').hide(); } );
	},

	nextImage: function() {
	},

	previousImage: function() {
	},

	showImage: function(gallery, element) {
		if (element) {
			$('galleryimage').src = null;
			$('galleryimage').src = 'http://media.tjingo.nl/imagecache/?type=shrink&width=570&height=386&image=' + element.readAttribute('value');

			current = element;

			var previous = current.previous();
			var next = current.next();

			var galHtml = $('galleryimage').up();
			if (previous) {
				galHtml.down('.previous').removeClassName('disabled');
			}
			else {
				galHtml.down('.previous').addClassName('disabled');
			}

			if (next) {
				galHtml.down('.next').removeClassName('disabled');
			}
			else {
				galHtml.down('.next').addClassName('disabled');
			}
		}
	},

	actionLoadImage: function(event) {
		var element = Event.findElement(event, 'li');

		if (!Object.isUndefined(element)) {
			$('popup_window').show();
			$('popup_window').down('.window').setStyle({ width: '610px', height: '426px', top: '200px'} );
			
			var g = getGalleryHtml();
			$('popup_window').down('.content').update(g);

			showImage(g, element);
		}

		Event.stop(event);
	}
});
*/

var current = null;
var gallery = null;
function initializeGallery(element) {
	gallery = element;
}

function getGalleryHtml() {
	var galleryHtml = new Element('div', {'class': 'gallery'} );

	var previous = new Element('div', {'class': 'button previous disabled'});
	previous.observe('click', previousImage);
	galleryHtml.appendChild(previous);

	var next = new Element('div', {'class': 'button next disabled'})
	next.observe('click', nextImage);
	galleryHtml.appendChild(next);

	var image = new Element('img', {'id': 'galleryimage'});
	galleryHtml.appendChild(image);
	image.observe('click', function() { this.up('.popup').hide(); } );

	return galleryHtml;
}


function nextImage() {
	showImage(gallery, current.next());
}

function previousImage() {
	showImage(gallery, current.previous());
}

function showImage(gallery, element) {
	if (element) {
		$('galleryimage').src = null;
		$('galleryimage').src = 'http://media.tjingo.nl/imagecache/?type=shrink&width=570&height=386&image=' + element.readAttribute('value');

		current = element;

		var previous = current.previous();
		var next = current.next();

		var galHtml = $('galleryimage').up();
		if (previous) {
			galHtml.down('.previous').removeClassName('disabled');
		}
		else {
			galHtml.down('.previous').addClassName('disabled');
		}

		if (next) {
			galHtml.down('.next').removeClassName('disabled');
		}
		else {
			galHtml.down('.next').addClassName('disabled');
		}
	}
}

function actionLoadImage(event) {
	var element = Event.findElement(event, 'li');

	if (!Object.isUndefined(element)) {
		$('popup_window').show();
		$('popup_window').down('.window').setStyle({ width: '610px', height: '426px', top: '200px'} );
		
		var g = getGalleryHtml();
		$('popup_window').down('.content').update(g);

		showImage(g, element);
	}

	Event.stop(event);
}

/**
 * Home banner
 */

function initializeHomeBanner(banner) {
	var rotate = new RotateBanner(banner, 6);
	rotate.start();
}

var RotateBanner = Class.create({
	initialize: function(element, timeout) {
		this.element = element;
		this.timeout = timeout;

		this.duration = 1.0;
		this.current = -1;
		this.cycler = null;

		this.moveToIndex = null;

		this.elements = this.element.select('div.banner');
		this.titles = this.element.select('li');
		for(var i=0, len = this.titles.length; i < len; ++i) {
			var title = this.titles[i];
			title.observe('click', this.moveTo.bind(this, i));
			if (title.hasClassName('active')) {
				this.current = i;
			}
			else {
				this.elements[i].hide();
			}
		}

	},

	moveTo: function(index) {
		if (index != this.current) {
			this.moveToIndex = index;
			this.stop();
			this.cycle();
		}
	},

	start: function() {
		if (this.current > -1) {
			this.cycler = new PeriodicalExecuter(this.cycle.bind(this), this.timeout);
		}
	},

	stop: function() {
		if (this.cycler !== null) {
			this.cycler.stop();
			this.cycler = null;
		}
	},
	
	cycle: function() {
		if (this.current > -1) {
			var previousTitle = this.titles[this.current];
			var previousBanner = this.elements[this.current];

			++this.current;
			this.current %= this.elements.length;

			var nextTitle = this.titles[this.current];
			var nextBanner = this.elements[this.current];

			var layout = nextBanner.getLayout();

//			nextBanner.setStyle({ left: -layout.get('width') + 'px'});
			nextBanner.setStyle({ top: layout.get('height') + 'px'});
			nextBanner.show();

			previousTitle.toggleClassName('active');
			nextTitle.toggleClassName('active');

			// previousTitle.up().appendChild(previousTitle);

			new Effect.Parallel([
//				new Effect.Move(previousBanner, {sync: true, x: layout.get('width'), y: 0, mode: 'relative', transition: Effect.Transitions.sinoidal}),
//				new Effect.Move(nextBanner, {sync: true, x: layout.get('width'), y: 0, mode: 'relative', transition: Effect.Transitions.sinoidal})
				new Effect.Move(previousBanner, {sync: true, x: 0, y: -layout.get('height'), mode: 'relative', transition: Effect.Transitions.sinoidal}),
				new Effect.Move(nextBanner, {sync: true, x: 0, y: -layout.get('height'), mode: 'relative', transition: Effect.Transitions.sinoidal})
//				new Effect.Fade(previousBanner, {sync: true }),
//				new Effect.Appear(nextBanner, {sync: true })
			], {duration: this.duration, queue: { scope: 'banner', position: 'end', limit: 3 }});

			if (this.moveToIndex !== null) {
				if (this.moveToIndex == this.current) {
					this.moveToIndex = null;
					this.start();
				}
				else {
					this.stop();
					this.cycle.bind(this).delay(this.duration);
				}
			}
		}
	}
});

/**
 * Tip cycler
 */
function initializeTipCycler(tip) {
	new TipCycler(tip, 10);
}

var TipCycler = Class.create({
	initialize: function(element, timeout) {
		this.element = element;
		this.timeout = timeout;
		this.current = -1;
		this.cycler = null;

		this.elements = tip.select('p');
		for(var i=0, len = this.elements.length; i < len; ++i) {
			var element = this.elements[i];
			if (element.getStyle('display') == 'none') {
				element.setStyle( { 
					opacity: 0,
					display: 'block' 
				} );
			}
			else {
				element.addClassName('current');
				this.current = i;
			}
		}
	},

	start: function() {
		if (this.current > -1) {
			this.cycler = new PeriodicalExecuter(this.cycle.bind(this), this.timeout);
		}
	},

	stop: function() {
		if (this.cycler !== null) {
			this.cycler.stop();
			this.cycler = null;
		}
	},

	cycle: function() {
		if (this.current > -1) {
			var previous = this.elements[this.current];
			previous.removeClassName('current');
			new Effect.Fade(previous, { duration: 0.5, queue: { scope: 'tipcycle', position: 'end' } } );
			
			++this.current;
			this.current %= this.elements.length;

			var next = this.elements[this.current];
			next.removeClassName('current');
			new Effect.Appear(next, { duration: 0.5, queue: { scope: 'tipcycle', position: 'end' } } );
		}
	}
});

/**
 * Set message
 */
function setMessage(message) {
	$('messages').show();
	var texts = $('messages').down('.texts');
	texts.update(message);

	var app = CoreWebApp.getInstance();
	app.parseSelectors(texts);
}

/**
 * Clear messages
 */
function clearMessages() {
	$('messages').down('.texts').update('');
	$('messages').hide();
}

function actionSubmitForm(event) {
	var element = event.findElement('form');
	element.submit();
}

function actionBookmark(hash, event) {
	Effect.ScrollTo(hash);
	// location.hash = hash;
}

function embedFlash(element) {
	var dim = element.getDimensions();

	swfobject.embedSWF(element.readAttribute('swf'), element.id, dim.width, dim.height, '9.0.0', 'expressInstall.swf');
}

/**
 * Global
 */
function actionFaqToggle(event) {
	var element = event.element().up('li');
	if (element.hasClassName('collapsed')) {
		element.removeClassName('collapsed');
	}
	else {
		element.addClassName('collapsed');
	}

	Event.stop(event);
}

/**
 * Close button on the popups
 */
function closeWindow(event) {
	Event.element(event).up('.popup').hide();
	Event.stop(event);
}

function fade(element) {
	new Effect.Fade(element, { duration: 0.5, queue: { scope: 'scope_' + element.identify(), position: 'front' } } );
}

function appear(element) {
	new Effect.Appear(element, { duration: 0.5, queue: { scope: 'scope_' + element.identify(), position: 'end' } } );
}

function actionAddCriteria(event) {
	var element = event.element();

	var app = CoreWebApp.getInstance();
	app.deferAction('addCriteria', cbCriteriaChange, {criteria: element.name, value: element.value});
	app.loadContent('selection', $('selection'));
	app.loadContent('searchresults', $('searchresults'));
	app.process();

	Event.stop(event);
}

function actionRemoveCriteria(event) {
	var element = event.element();

	var app = CoreWebApp.getInstance();
	app.deferAction('removeCriteria', cbCriteriaChange, {criteria: element.readAttribute('type'), value: element.readAttribute('value')});
	app.loadContent('selection', $('selection'));
	app.loadContent('searchresults', $('searchresults'));
	app.process();

	Event.stop(event);
}

function actionClearCriteria(event) {
	var app = CoreWebApp.getInstance();
	app.deferAction('clearCriteria', cbCriteriaChange, {});
	app.loadContent('selection', $('selection'));
	app.loadContent('searchresults', $('searchresults'));
	app.process();

	Event.stop(event);
}

function cbCriteriaChange(data) {
	if (data.state == 'success') {
		setLocationHash('selection=' + data.selection);
	}
}

var searchbar = null;
function initializeSiteSearch(element) {
	searchbar = new SiteSearch(CoreWebApp.getInstance(), element);
}

var SiteSearch = Class.create({
	initialize: function(app, element) {
		this.app = app;

		this.active = false;
		this.lastSearch = '';

		this.element = element;
		this.elementBar = element.down('input.text');
		this.elementResults = element.down('.results');

		// this.elementBar.observe('keyup', this.change.bind(this));
		this.elementBar.observe('focus', this.show.bind(this));

		document.observe('click', this.hide.bind(this));

		this.searchdelay = null;
	},
	
	handleChange: function() {
		if (this.lastSearch != this.elementBar.value) {
			this.change();
			this.lastSearch = this.elementBar.value;
		}
	},

	change: function(event) {
		if (this.searchdelay != null) {
			window.clearTimeout(this.searchdelay);
		}

		this.searchdelay = this.search.bind(this, this.elementBar.value).delay(0.3);
	},

	search: function(query) {
		this.app.deferAction('sitesearch', this._cbSearch.bind(this), { query: query } );
		this.app.process();
	},

	_cbSearch: function(value) {
		if (value.state == 'success') {
			this.elementResults.update(value.content);
		}
		else {
			// could be used to set an extra class or something
			this.elementResults.update(value.content);
		}
	},

	show: function(event) {
		if (!this.active) {
			this.handler = new PeriodicalExecuter(this.handleChange.bind(this), 0.1);
		}
		this.active = true;

		this.elementResults.appear( { duration: 0.2 } );
	},

	hide: function(event) {
		var el = Event.findElement(event, '#' + this.element.id);
		if (el != this.element) {
			this.elementResults.fade( { duration: 0.2 } );

			if (this.active) {
				this.handler.stop();
			}
			this.active = false;
		}
	}
});

/**
 * Initialize scal. Scal only needs one "variable", even to show it multiple times.
 */
var calendar = null;
function actionSelectDate(event) {
	var el = Event.element(event);
	var pick = $('datepick');

	var offset = el.cumulativeOffset();
	pick.style.left = offset[0] + 'px';
	pick.style.top = offset[1] + el.getHeight() + 'px';
	pick.show();

	if (calendar == null) {
		var options = Object.extend({
			updateformat: 'dd-mm-yyyy',
			titleformat: 'mmmm yyyy',
			closebutton: '',
			dayheadlength: 2,
			weekdaystart: 0,
			planner: false
		});

		calendar = new scal(pick, Prototype.emptyFunction, options);

		document.observe('click', toggleCalendar);
	}

	// scal
	calendar.updateelement = Prototype.emptyFunction;
	if (el.value!=='' && el.value!==null) {
		var d = Date.parse(el.value);
		if (d instanceof Date) {
			calendar.setCurrentDate(d);
			el.value = d.format('dd-mm-yyyy');
		}
	}
	calendar.updateelement = updateDate.curry(el);
	// calendar.updateelement = el;

	// new CalendarDateSelect( Event.element(event), test );
}

/**
 * Update date callback
 */
function updateDate(el, d) {
	el.activate();
	el.value = d.format('dd-mm-yyyy');
	calendar.toggleCalendar();
	// actionPickDate(el.fire('change'));
	el.focus();
}

/**
 * Toggle calendar show / hide
 */
function toggleCalendar(event) {
	var element = event.element();

	if (!element.hasClassName('date') && !element.up('.scal')) {
		if (calendar instanceof scal) {
			if (calendar.isOpen()) calendar.toggleCalendar();
		}
	}
}

/**
 * Input elements with a hint attribute are "filled" with a hint attribute
 */
function initializeInputHint(element) {
	new InputHint(element);
}

var InputHint = Class.create({
	initialize: function(element) {
		this.inputElement = element;
		this.hint = element.readAttribute('hint');

		if (this.hint !== null && element.visible()) {
			var hintEl = new Element('SPAN');

			hintEl.setStyle({
				'height': element.getStyle('height'),
				'marginTop': element.getStyle('marginTop'),
				'marginLeft': element.getStyle('marginLeft'),
				'marginBottom': element.getStyle('marginBottom'),
				'marginRight': element.getStyle('marginRight'),
				'paddingTop': element.getStyle('paddingTop'),
				'paddingLeft': element.getStyle('paddingLeft'),
				'paddingBottom': element.getStyle('paddingBottom'),
				'paddingRight': element.getStyle('paddingRight'),
				'borderTopWidth': element.getStyle('borderTopWidth'),
				'borderLeftWidth': element.getStyle('borderLeftWidth'),
				'borderBottomWidth': element.getStyle('borderBottomWidth'),
				'borderRightWidth': element.getStyle('borderRightWidth'),
				'fontSize': element.getStyle('fontSize')
			});
			hintEl.addClassName('hint');
			hintEl.update(this.hint);

			var wrapper = new Element('SPAN');
			wrapper.setStyle( { 
				'position': 'relative', 
				'float': element.getStyle('float'), 
				'display': 'block'
			} );

			Element.wrap(element, wrapper);
			wrapper.appendChild(hintEl);

			var clearCb = this.clear.bind(this);
			var showCb = this.show.bind(this);

			element.observe('focus', clearCb);
			element.observe('blur', showCb);
			hintEl.observe('click', clearCb);

			this.hintElement = hintEl;

			if (element.value.length > 0) {
				hintEl.hide();
			}
		}
	},

	clear: function(event) {
		this.hintElement.hide();
		this.inputElement.focus();
		Event.stop(event);
	},

	show: function(event) {
		if (this.inputElement.value.length == 0) {
			this.hintElement.show();
		}
		Event.stop(event);
	}
});

/**
 * The account class takes care of login / logout / signup etc.
 */
/*
var Account = Class.create({
	initialize: function(app) {
		this.app = app;
	},

	// Load the login box into the requested element
	loadLogin: function(element) {
		this.app.loadContent('loginForm', element);
		this.app.process();
	},

	login: function(username, password) {
	},

	cbLogin: function(value) {
	},

	logout: function() {
	},

	requestLogin: function() {
	},

	create: function() {
	},

	activate: function() {
	}
});

var Account.Login = Class.create({
	// the element to load into and parse later
	initialize: function(app, element) {
		this.app = app;
		this.element = element;
	},

	load: function() {
	},

	trigger: function() {
	},

	cbTrigger: function() {
	}
});
*/

/**
 * Login
 */
function actionLoadLoginPopup(event) {
	$('popup_window').show();
	$('popup_window').down('.window').setStyle({ width: '380px', height: '136px', top: '200px'} );
	$('popup_window').down('.content').update('');

	loadLogin($('popup_window').down('.content'));

	Event.stop(event);
}

function loadLogin(element) {
	var app = CoreWebApp.getInstance();
	app.loadContent('loginForm', element);
	app.process();
}

function actionLogin(event) {
	var form = Event.element(event).up('form');
	var name = form.name;

	var params = {username: form.elements[name + '[username]'].value, password: form.elements[name + '[password]'].value};

	var app = CoreWebApp.getInstance();
	app.deferAction('login', cbLogin.bind(this), params);
	app.loadContent('mainmenu', $('mainmenu'));
	app.process();

	Event.stop(event);
}

function cbLogin(value) {
	if (value.state=='fail') {
		setMessage(value.messages.join('<br/>'));
	}
	else {
		// loadCheckMyData.bind(CoreWebApp.getInstance())();
		$('popup_window').hide();

		var app = CoreWebApp.getInstance();
		if (app.currentPage == 'account' || app.currentPage == 'booktrip' || app.currentPage == 'invoice') {
			window.location.reload();
		}
		else if (value.messages.length > 0) {
			setMessage(value.messages.join("<br />"));
		}
	}
}

/**
 * Logout
 */
function actionLogout(event) {
	var app = CoreWebApp.getInstance();
	app.deferAction('logout', cbLogout);
	app.loadContent('mainmenu', $('mainmenu'));
	app.process();

	Event.stop(event);
}

function cbLogout(value) {
	if (value.state=='success') {
		var app = CoreWebApp.getInstance();

		if (app.currentPage == 'account' || app.currentPage == 'booktrip' || app.currentPage == 'invoice') {
			window.location.reload();
		}
	}
	// window.location.reload();
}

/**
 * Request number
 */
function actionLoadRequestLoginPopup(event) {
	// Event.stop(event);
	$('popup_window').show();
	$('popup_window').down('.window').setStyle({ width: '350px', height: '148px', top: '200px'} );
	$('popup_window').down('.content').update('');

	loadRequestLogin($('popup_window').down('.content'));

	Event.stop(event);
}

function loadRequestLogin(element) {
	var app = CoreWebApp.getInstance(); 
	app.loadContent('requestLoginForm', element); 
	app.process();
}

function actionDirectRequestLogin(event) {
	var el = Event.element(event);

	var app = CoreWebApp.getInstance();
	app.deferAction('requestLogin', cbRequestLogin, {email: el.readAttribute('value') });
	app.process();

	Event.stop(event);
}

function actionRequestLogin(event) {
	if (Event.isLeftClick(event) || event.keyCode == Event.KEY_RETURN || event.keyCode == 0) {
		var el = Event.findElement(event, '#requestform').down('#emailaddress');

		var app = CoreWebApp.getInstance();
		app.deferAction('requestLogin', cbRequestLogin, {email: el.value});
		app.process();

		Event.stop(event);
	}
}

function cbRequestLogin(value) {
	if (value.state=='fail') {
		setMessage(value.messages.join('<br />'));
		// actionLoadLogin(null);
	}
	else {
		$('popup_window').hide();
		if (value.messages.length > 0) setMessage(value.messages.join('<br />'));
	}
}

/**
 * Signup load form
 */
function actionLoadSignupPopup(event) {
	$('popup_window').show();
	$('popup_window').down('.window').setStyle({ width: '380px', height: 'auto', top: '60px'} ); // todo get from call?
	$('popup_window').down('.content').update('');

	var app = CoreWebApp.getInstance();
	app.loadContent('signupWindow', $('popup_window').down('.content'));

	loadSignupForm();

	Event.stop(event);
}

function loadSignupForm() {
	var app = CoreWebApp.getInstance();
	app.loadContent('signupForm', 'signupactivatesnippet');
	app.process();

	_gaq.push(['_trackPageview', location.pathname + '?signuppopup']);
}

/**
 * Set cardholder info
 */
function actionSetAccountInfo(event) {
	var element = Event.element(event);

	var app = CoreWebApp.getInstance();
	
	setAccountInfo(app, element);

	// address lookup
	addressLookup(app, element.form);
	app.process();

	Event.stop(event);
}

function setAccountInfo(app, element) {
	var parts = (element.name + '[').split('[');
	var name = parts[parts.length-2].split(']')[0];

	if (name.length > 0 && name != 'newsletter') { // TODO check if still needed?
		var notification = element.up('tr').down('.notification');

		// var values = getCardholderInfo(element.form, [name]);
		var options = {};
		options[name] = element.value;

		app.deferAction('setCardholder', cbSetCardholderInfo.curry(notification), options );
	}
}

function cbSetCardholderInfo(element, value) {
	element.update(value.messages.join(''));
}

function addressLookup(app, form) {
	var els = form.elements;

	var ops = {};
	for(var i=0, len = els.length; i < len; ++i) {
		var parts = (els[i].name + '[').split('[');
		var name = parts[parts.length-2].split(']')[0];

		if (name == 'country' || name == 'number' || name == 'postalcode') {
			ops[name] = els[i].value;
		}
	}

	app.deferAction('addressLookup', cbAddressLookup.curry(app, form), ops );
}

function cbAddressLookup(app, form, value) {
	var els = form.elements;

	var doProcess = false;

	for(var i=0, len = els.length; i < len; ++i) {
		var parts = (els[i].name + '[').split('[');
		var name = parts[parts.length-2].split(']')[0];
		
		if (name == 'street' || name == 'place') {
			if (value.address[name] != null && els[i].value != value.address[name]) {
				els[i].value = value.address[name];
				setAccountInfo(app, els[i]);
				doProcess = true;
			}
		}
	}

	if (doProcess) {
		app.process();
	}
}

/**
 * Signup cardholder
 */
function actionSignUp(event) {
	var element = Event.element(event);
	element.disable(); // disable the submit, so we cannot multi submit the form ;)

	var form = element.up('form');

	var values = {};
	var elements = form.select('.summary select,.summary input')
	for(var i=0, length = elements.length; i < length; ++i) {
		var myelement = elements[i];
		var parts = (myelement.name + '[').split('[');
		var name = parts[parts.length-2].split(']')[0];
		values[name] = (myelement.type == 'checkbox' ? (myelement.checked ? myelement.value : null) : myelement.value);
	}

	var app = CoreWebApp.getInstance();
	app.deferAction('signUp', cbSignUp.curry(element), values );
	app.process();

	Event.stop(event);
}

/**
 * Signup callback
 */
function cbSignUp(element, value) {
	element.enable();

	if (value.state=='fail') {
		setMessage(value.messages.join('<br/>'));
	}
	else {
		// Load the activate popup!
		$('accountstep1').toggleClassName('active');
		$('accountstep2').toggleClassName('active');

		setMessage(value.messages.join('<br/>'));
		loadActivateForm(value.hashcode);

		// $('popup_window').hide();
		/*
		$('signup_notification').update(value.messages.join(', '));
		// $('popup_window').down('.signupcontent').update(value.messages);

		var app = CoreWebApp.getInstance();
		// app.loadContent('inviteForm', 'signup_content');
		app.loadContent('signupThanks', 'signup_content');
		app.process();
		*/
		
	}
}

function loadActivateForm(hashcode) {
	var app = CoreWebApp.getInstance();
	app.loadContent('signupActivate', 'signupactivatesnippet', { hashcode: hashcode } );
	app.process();

	_gaq.push(['_trackPageview', location.pathname + '?activatepopup']);
}

function actionActivate(event) {
	var element = Event.element(event);
	element.disable(); // disable the submit, so we cannot multi submit the form ;)

	var form = element.up('form');

	var values = {};
	var elements = form.select('input[name]')
	for(var i=0, length = elements.length; i < length; ++i) {
		var myelement = elements[i];
		var parts = (myelement.name + '[').split('[');
		var name = parts[parts.length-2].split(']')[0];
		values[name] = myelement.value;
	}

	var app = CoreWebApp.getInstance();
	app.deferAction('activateAccount', cbActivate.curry(element), values );
	app.process();

	Event.stop(event);
}

/**
 * Activate callback
 */
function cbActivate(element, value) {
	element.enable();

	if (value.state=='fail') {
		setMessage(value.messages.join('<br/>'));
	}
	else {
		$('popup_window').hide();

		var app = CoreWebApp.getInstance();
		app.loadContent('mainmenu', $('mainmenu'));
		app.process();

		_gaq.push(['_trackPageview', location.pathname + '?activatecomplete']);

		var app = CoreWebApp.getInstance();
		if (app.currentPage == 'account' || app.currentPage == 'booktrip' || app.currentPage == 'invoice') {
			window.location.reload();
		}
		else if (value.messages.length > 0) {
			setMessage(value.messages.join("<br />"));
		}

	}
}

/**
 * Send invites
 */
function actionSendInvites(event) {
	var form = Event.element(event).form;
	var names = [];
	var emails = [];

	for(var i=0;i<5;++i) {
		names[i] = form.elements['inviteForm[name][' + i + ']'].value;
		emails[i] = form.elements['inviteForm[email][' + i + ']'].value;
	}

	var app = CoreWebApp.getInstance();
	app.deferAction('sendInvite', cbSendInvite.curry(form), { name: names, email: emails} );
	app.process();

	Event.stop(event);
}

/**
 * Send invite callback
 */
function cbSendInvite(form, value) {
	if (value.state=='fail') {
		setMessage(value.messages.join(', '));
	}
	else {
		for(var i=0;i<5;++i) {
			form.elements['inviteForm[name][' + i + ']'].value = '';
			form.elements['inviteForm[email][' + i + ']'].value = '';
		}

		var app = CoreWebApp.getInstance();
		app.loadContent('inviteThanks', 'signup_content');
		app.process();

		$('signup_notification').update(value.messages);
		_gaq.push(['_trackPageview', location.pathname + '?invitethankyou']);
	}
}

/**
 * get cardholder info from a form
 */
function getCardholderInfo(form, fields) {
	var formname = form.readAttribute('name');

	var items = $H({
		gender: formname + '[gender]',
		initials: formname + '[initials]',
		nameaddition: formname + '[joint]',
		lastname: formname + '[lastname]',
		birthdate: formname + '[birthdate]',
		address: formname + '[address]',
		postalcode: formname + '[postalcode]',
		city: formname + '[city]',
		telephone: formname + '[telephone]',
		email: formname + '[email]'
	});

	if (Object.isUndefined(fields)) fields = ['sex', 'initials', 'joint', 'lastname', 'birthdate', 'address', 'postalcode', 'city', 'telephone', 'email'];

	var values = $H();

	var el;
	var elements = form.elements; // form.getElements();

	items.each(function(pair) {
		el = elements[pair.value];
		if (fields.indexOf(pair.key)>-1) {
			values.set(pair.key, el.value);
		}
	}.bind(this));

	// CoreWebApp.getInstance().loadContent('setCardholder', notification, values.toObject() ); // , actionAfter: cbSetCardHolderInfo.bind(this, elements, items)
	return values;
}

/**
 * Initialize Pricetable dateslider
 */
var slider;
function initializePriceTableSlider(element) {
	slider = new PriceTableSlider(element);
	slider.setCallback(loadPriceTableForSlider);
}

var PriceTableSlider = Class.create({
	initialize: function(element) {
		this.element = element;
		this.sliding = false;
		this.sliderEl = element.down('.slider');
		this.dayWidth = 1.5;
		var monthsEl = element.down('.months');
		this.startDay = parseInt(monthsEl.readAttribute('value'));
		this.callback = null;

		var months = monthsEl.select('.month');
		var total = -(this.startDay * this.dayWidth);
		for(var i=0, len = months.length;i<len;++i) {
			var month = months[i];
			var value = parseInt(month.readAttribute('value'));
			month.setStyle( { width: (this.dayWidth * value) + 'px', left: total + 'px'} );
			total += (this.dayWidth * value);
		}

		var sliderValue = Math.round(parseInt(element.readAttribute('value')) * this.dayWidth);
		var sliderWidth = Math.round(parseInt(this.sliderEl.readAttribute('value')) * this.dayWidth);
		this.sliderEl.setStyle( { left: sliderValue + 'px', width:  sliderWidth + 'px' } );
		this.sliderEl.observe('mousedown', this.startDrag.bind(this));

		document.observe('mouseup', this.stopDrag.bind(this));
		document.observe('mousemove', this.moveSliderAction.bind(this));
		monthsEl.observe('mousedown', this.startDrag.bind(this));

		var nextEl = element.down('.next');
		nextEl.observe('mouseup', this.stepMoveSliderAction.bind(this, nextEl));

		var prevEl = element.down('.previous');
		prevEl.observe('mouseup', this.stepMoveSliderAction.bind(this, prevEl));
	},

	setCallback: function(callback) {
		this.callback = callback;
	},

	startDrag: function(event) {
		this.sliding = true;
		this.sliderEl.addClassName('dragging');
		this.moveSliderAction(event);
		Event.stop(event);
	},

	stopDrag: function(event) {
		if(this.sliding) {
			this.sliding = false;
			this.sliderEl.removeClassName('dragging');
			
			if (this.callback != null) {
				this.callback(this.getRange());
			}
		}
	},

	stepMoveSliderAction: function(element, event) {
		var dx = parseInt(element.readAttribute('value')) * this.dayWidth;
		this.moveSlider(this.sliderEl.offsetLeft + dx);

		if (this.callback != null) {
			this.callback(this.getRange());
		}

		this.clearSelection();

		Event.stop(event);
	},

	moveSliderAction: function(event) {
		if (this.sliding) {
			var offset = this.sliderEl.up('.months').cumulativeOffset();

			var sliderWidth = this.sliderEl.getWidth();
			this.moveSlider(event.pointerX() - offset.left - Math.round(sliderWidth / 2));

			Event.stop(event);
		}
	},

	moveSlider: function(x) {
		// var element = this.sliderEl.up('.months');
		// var offset = element.cumulativeOffset();
		// var width = element.getWidth();

		var sliderWidth = this.sliderEl.getWidth();
		var maxWidth = this.sliderEl.up('.months').getWidth() - sliderWidth;

		if (x < 0) x = 0;
		// if (x > maxWidth) x = maxWidth;

		x = Math.round(x / this.dayWidth) * this.dayWidth;

		this.sliderEl.setStyle( { left: x + 'px' } );
	},

	clearSelection: function() {
		if(document.selection && document.selection.empty) {
			document.selection.empty();
		}
		else if(window.getSelection) {
			var sel = window.getSelection();
			sel.removeAllRanges();
		}
	},

	getRange: function() {
		var days = Math.round(this.sliderEl.offsetLeft / this.dayWidth) + this.startDay + 1;
		var datefrom = new Date();
		// date.setMonth(1);
		datefrom.setDate(days);

		var string = datefrom.format('yyyymmdd') + '-';

		var dateto = new Date();
		dateto.setDate(days + parseInt(this.sliderEl.readAttribute('value')));

		string += dateto.format('yyyymmdd');

		return string;
	}
});

function loadPriceTableForSlider(range) {
	var app = CoreWebApp.getInstance();
	app.deferAction('setPriceTableOptions', null, { options: [ { name: 'departuredate', value: range } ] } );

	reloadPriceTable();
}

/**
 * Pricetable dateslider
 */
function actionPriceTableScroll(event) {
	var element = Event.element(event);

	if (element.tagName!='A') element = element.up('a');

	loadPriceTableForSlider(element.readAttribute('value'));

	Event.stop(event);
}

function actionPriceTableUpdate(event) {
	var element = Event.element(event);

	var name = element.name.split('[')[1].split(']')[0];

	// this.loadContent('loadSearchResults', $('searchresults'), {options: [{name: name, value: element.value}] });
	var app = CoreWebApp.getInstance();
	app.deferAction('setPriceTableOptions', null, { options: [ { name: name, value: element.value } ] } );
	app.process();

	reloadPriceTable();

	// app.loadContent('pricetableOptions', $('priceoptions') );
	// app.loadContent('pricetableSlider', $('pricetableslider') );
	// app.loadContent('pricetable', $('pricetable'), {}, { actionBefore: fade, actionAfter: appear } );

	Event.stop(event);
}

/**
 * Select a certain price
 */
function actionSelectPrice(event) {
	var app = CoreWebApp.getInstance();

	var el = Event.findElement(event, 'a');

	if (el) {
		if ($('currentselection').visible()) {
			new Effect.Parallel([
				new Effect.SlideUp($('currentselection'), { sync: true } ),
				new Effect.Fade($('currentselection'), { sync: true } ),
				new Effect.SlideUp($('pricebreakdown'), { sync: true } ),
				new Effect.Fade($('pricebreakdown'), { sync: true } )
			], { duration: 0.5, queue: { position: 'end', scope: 'toggles' } });
		}

		$('startbooktrip').hide();
		// $('bookstep').hide();

		app.ajax.options.set('pageLoader', $('loading_large'));

		app.deferAction('pickPrices', null, { ids: el.readAttribute('value') } );

		var selected = el.up('table').select('.selected');
		if (selected.length > 0) {
			selected[0].removeClassName('selected');
		}

		el.up().addClassName('selected');
		// app.loadContent('pricetable', $('pricetable'));

		// app.loadContent('bookStep', $('bookstep'));
		
		app.deferAction('priceCheck', cbPriceCheck, {} );

		app.loadContent('currentSelection', 'currentselectionsnippet');
		app.loadContent('priceBreakdown', 'pricebreakdownsnippet');

		// app.loadContent('pickTransport', 'transportsnippet');
		// app.loadContent('changeRoomType', 'roomtypesnippet');
		
		app.process();

		Event.stop(event);
	}
}

function cbPriceCheck(value) {
	var app = CoreWebApp.getInstance();
	app.ajax.options.set('pageLoader', $('loading'));
	$('loading_large').hide();

	// app.loadContent('pricetable', $('pricetable'));
	// app.process();

	if (value.state=='fail') {
		setMessage(value.messages.join('<br />'));
	}
	else {
		// $('quickprice').show();
		// $('checkavailable').show();

		new Effect.Parallel([
			new Effect.SlideDown($('currentselection'), { sync: true } ),
			new Effect.Appear($('currentselection'), { sync: true } ),
			new Effect.SlideDown($('pricebreakdown'), { sync: true } ),
			new Effect.Appear($('pricebreakdown'), { sync: true } )
		], { duration: 0.5, queue: { position: 'end', scope: 'toggles' } });

		// $('bookstep').show();
		$('startbooktrip').show();

		if (value.messages.length > 0) {
			setMessage(value.messages.join('<br />'));
		}
	}
}

/*
function actionPickCompany(event) {
	$('quickprice').update('');
	$('checkavailable').hide();
	$('bookstep').hide();

	var element = Event.element(event);
	var app = CoreWebApp.getInstance();
	var id = element.options[element.selectedIndex].value;

	app.deferAction('setCompany', null, { companyId: id } );
	app.loadContent('pickPersons', $('persons'));
	// app.loadContent('pricetable', $('pricetable') );
	app.process();

	reloadPriceTable();

	if (id == 0) {
		$('personpicker').show();
	}
	else {
		$('personpicker').hide();
	}

	Event.stop(event);
}
*/

/**
 * Person picker
 */
function initializePersonRoomPicker(element) {
	var picker = new PersonRoomPicker(CoreWebApp.getInstance(), element);
	// picker.addCallback(reloadPriceTable);
}

var PersonRoomPicker = Class.create({
	initialize: function(app, element) {
		this.app = app;
		this.element = element;
		this.callbacks = [];

		this.setChanged(false);
		// this.refreshDelay = 0.3;

		this.elementNotifications = this.element.select('.check .notification');

		this.currentValues = [];
		this.currentAssigns = [];
		var inputs = this.element.select('.birthdate');

		var cb = this.changeBirthdate.bind(this);
		for(i=0,len=inputs.length;i<len;++i) {
			this.currentValues[i] = inputs[i].value;
			inputs[i].observe('keyup', cb);
			// inputs[i].observe('change', this.change.bind(this));
		}

		this.element.down('.addperson').observe('click', this.addPerson.bind(this));
		this.element.down('.addroom').observe('click', this.addRoom.bind(this));
		this.element.down('.update').observe('click', this.refreshData.bind(this));

		var cb = this.removePerson.bind(this);
		var removes = this.element.select('.removeperson');
		for(i=0,len=removes.length;i<len;++i) {
			removes[i].observe('click', cb);
		}

		var cb = this.removeRoom.bind(this);
		var removes = this.element.select('.removeroom');
		for(i=0,len=removes.length;i<len;++i) {
			removes[i].observe('click', cb);
		}

		var c = 0;
		var cb = this.assign.bind(this);
		var inputs = this.element.select('.roomassign input');
		for(i=0,len=inputs.length;i<len;++i) {
			if (inputs[i].checked) {
				this.currentAssigns[c] = inputs[i].up('td').readAttribute('value');
				++c;
			}
			inputs[i].observe('click', cb);
		}

		this.busy = false;
		this.refreshdelay = null;
	},
	
	setChanged: function(changed) {
		if (!this.changed) {
			if (changed) {
				fade($('pricetable'));
				fade($('priceoptions'));
				fade($('pricetableslider'));

				/*
				if ($('bookstep').visible()) {
					fade($('bookstep'));
				}
				*/

				$('startbooktrip').hide();

				if ($('currentselection').visible()) {
					new Effect.Parallel([
						new Effect.SlideUp($('currentselection'), { sync: true } ),
						new Effect.Fade($('currentselection'), { sync: true } ),
						new Effect.SlideUp($('pricebreakdown'), { sync: true } ),
						new Effect.Fade($('pricebreakdown'), { sync: true } )
					], { duration: 0.5, queue: { position: 'end', scope: 'toggles' } });
				}

				this.element.down('.update').show();
			}
			else {
				appear($('pricetable'));
				appear($('priceoptions'));
				appear($('pricetableslider'));

				this.element.down('.update').hide();
			}
		}

		this.changed = changed;
	},

	changeBirthdate: function(event) {
		// change birthdate: TODO: not needed anymore? (server side check?)
		this.setChanged(true);
	},

	removePerson: function(event) {
		// collect persons, do we have more than 1?
		var elements = this.element.select('tr[value]');
		if (elements.length > 1) {
			var row = Event.element(event).up('tr');
			row.remove();

			// update colspan
			var tmp = this.element.select('th.add')[0];
			tmp.writeAttribute('rowspan', parseInt(tmp.readAttribute('rowspan')) - 1);

			elements = this.element.select('tr[value]');
			for(var i=0, len=elements.length;i<len; ++i) {
				elements[i].down('td.number label').update(i + 1);
			}

			this.setChanged(true);
		}
	},

	addPerson: function(event) {
		// collect persons
		var elements = this.element.select('tr[value]');
		if (elements.length < 8) {
			var newpersonindex = parseInt(elements[elements.length - 1].readAttribute('value')) + 1;
			var lastrow = this.element.select('tr.bottom')[0];
			var roomcount = this.element.select('th.roomassign').length;

			var newrow = new Element('tr', {value: newpersonindex});

			cell = new Element('td', { 'class': 'number' } );
			var label = new Element('label', { 'for': 'personRoomPicker[birthdate][' + newpersonindex + ']' } );
			label.update(elements.length + 1);
			cell.appendChild(label);
			newrow.appendChild(cell);

			cell = new Element('td', { 'class': 'birthdate' } );
			var birthdate = new Element('input', { 'class': 'birthdate', type: 'text', name: 'personRoomPicker[birthdate][' + newpersonindex + ']', value: '', hint: '(bv. 25-02-1956)' } );
			cell.appendChild(birthdate);
			newrow.appendChild(cell);

			cell = new Element('td', { 'class': 'check' } );
			cell.appendChild(new Element('div', { 'class': 'notification' } ));
			newrow.appendChild(cell);

			cell = new Element('td', { 'class': 'delete' } );
			var remove = new Element('div', { 'class': 'removeperson' } ).update(elements[0].childElements()[3].down('div').innerHTML);
			remove.observe('click', this.removePerson.bind(this));
			cell.appendChild(remove);
			newrow.appendChild(cell);

			var cb = this.assign.bind(this);
			var checkbox;
			for(var i=0;i < roomcount;++i) {
				cell = new Element('td', { 'class': 'roomassign', value: i } );
				checkbox = new Element('input', { type: 'radio', value: i, name: 'personRoomPicker[mapping][' + newpersonindex + ']'} );
				checkbox.observe('click', cb);
				if (i == 0) {
					checkbox.checked = true;
				}
				cell.appendChild(checkbox);
				newrow.appendChild(cell);
			}

			lastrow.up().insertBefore(newrow, lastrow);

			// init hint
			initializeInputHint(birthdate);

			var tmp = this.element.select('th.add')[0];
			tmp.writeAttribute('rowspan', parseInt(tmp.readAttribute('rowspan')) + 1);

			this.setChanged(true);

			/*
			for(var i=0, len=elements.length;i<len; ++i) {
				elements[i].down('td.number label').update(i + 1);
			}
			*/
		}
	},

	removeRoom: function(event) {
		// collect persons, do we have more than 1?
		var elements = this.element.select('th.roomassign');
		if (elements.length > 1) {
			var header = Event.element(event).up('th');
			var index = header.readAttribute('value');

			header.remove();

			var removes = this.element.select('td.roomassign[value=' + index + ']');
			for(var i=0, len = removes.length; i < len; ++i) {
				if (removes[i].down('input').checked) {
					var tmp = removes[i].next();
					if (Object.isUndefined(tmp)) {
						tmp = removes[i].previous();
					}
					tmp.down('input').checked = true;
				}
				removes[i].remove();
			}

			// colspan on tr.bottom td.add
			var tmp = this.element.select(' tr.bottom td.add')[0];
			tmp.writeAttribute('colspan', parseInt(tmp.readAttribute('colspan')) - 1);

			elements = this.element.select('th.roomassign');
			for(var i=0, len=elements.length;i<len; ++i) {
				elements[i].down('span').update('Verblijf ' + (i + 1));
			}

			this.setChanged(true);
		}
	},

	addRoom: function(event) {
		// collect rooms
		var elements = this.element.select('th.roomassign');
		if (elements.length < 4) {
			var newroomindex = parseInt(elements[elements.length - 1].readAttribute('value')) + 1;

			var lastcolumn = this.element.select('th.add')[0];

			var header = new Element('th', { 'class': 'roomassign', value: newroomindex });
			header.appendChild(new Element('span', {}).update('Verblijf ' + (elements.length + 1)));
			var removeroom = new Element('div', {'class': 'removeroom'}).update(elements[0].down('div').innerHTML);
			removeroom.observe('click', this.removeRoom.bind(this));
			header.appendChild(removeroom);

			lastcolumn.up().insertBefore(header, lastcolumn);

			// loop all person rows
			var cb = this.assign.bind(this);
			var cell;
			var persons = this.element.select('tr[value]');
			for(var i=0, len = persons.length;i < len; ++i) {
				cell = new Element('td', { 'class': 'roomassign', value: newroomindex } );
				checkbox = new Element('input', { type: 'radio', value: newroomindex, name: 'personRoomPicker[mapping][' + persons[i].readAttribute('value') + ']'} );
				checkbox.observe('click', cb);
				cell.appendChild(checkbox);
				persons[i].appendChild(cell);
			}

			// colspan on tr.bottom td.add
			var tmp = this.element.select(' tr.bottom td.add')[0];
			tmp.writeAttribute('colspan', parseInt(tmp.readAttribute('colspan')) + 1);

			this.setChanged(true);

			/*
			for(var i=0, len=elements.length;i<len; ++i) {
				elements[i].down('span').update('Verblijf ' + (i + 1));
			}
			*/
		}
	},

	assign: function(event) {
		this.setChanged(true);
	},

	refreshData: function() {
		var elements = this.element.select('tr[value]');
		var ops = { roomCount: this.element.select('th.roomassign').length, personCount: elements.length, birthdates: [], assignments: [] };

		for(var i=0, len = elements.length; i < len; ++i) {
			ops.birthdates[i] = elements[i].childElements()[1].down('input').value;
			var checks = elements[i].select('td.roomassign input');
			for(var j=0, lenj = checks.length; j < lenj; ++j) {
				if (checks[j].checked) {
					ops.assignments[i] = j;
					break;
				}
			}
		}

		this.app.deferAction('setPersonsRooms', null, ops );
		this.app.loadContent('pickPersons', $('persons'));
		this.app.loadContent('pricetableOptions', $('priceoptions') );
		this.app.loadContent('pricetableSlider', $('pricetableslider') );
		this.app.loadContent('pricetable', $('pricetable')); // , {}, { actionBefore: fade, actionAfter: appear } 
		this.app.process();
	}
});

var reloadDelay = null;
var loadTableId = null;
function reloadPriceTable() {
	if (reloadDelay != null) {
		window.clearTimeout(reloadDelay);
	}

	if (loadTableId != null) {
		var app = CoreWebApp.getInstance();
		app.cancel(loadTableId);
		loadTableId = null;
	}

	/*
	if ($('bookstep').visible()) {
		new Effect.Fade($('bookstep'), { duration: 0.5 } );
	}
	*/

	$('startbooktrip').hide();

	if ($('currentselection').visible()) {
		new Effect.Parallel([
			new Effect.SlideUp($('currentselection'), { sync: true } ),
			new Effect.Fade($('currentselection'), { sync: true } ),
			new Effect.SlideUp($('pricebreakdown'), { sync: true } ),
			new Effect.Fade($('pricebreakdown'), { sync: true } )
		], { duration: 0.5, queue: { position: 'end', scope: 'toggles', limit: 1 } });
	}

	reloadDelay = realreloadPriceTable.delay(0.5);
}

function realreloadPriceTable() {
	var app = CoreWebApp.getInstance();

	app.loadContent('pricetableOptions', $('priceoptions') );
	app.loadContent('pricetableSlider', $('pricetableslider') );
	app.loadContent('pricetable', $('pricetable'), {}, { actionBefore: fade, actionAfter: appear } );
	loadTableId = app.process();
}

/**
 * Toggle pickers
 */
function actionShowRoomTransport(event) {
	$('startbooktrip').hide();

	new Effect.Parallel([
		new Effect.SlideUp($('currentselection'), { sync: true } ),
		new Effect.SlideUp($('pricebreakdown'), { sync: true } ),
		new Effect.Fade($('currentselection'), { sync: true } ),
		new Effect.Fade($('pricebreakdown'), { sync: true } ),
//		new Effect.Fade($('changenotice'), { sync: true } ),
//		new Effect.Appear($('transport'), { sync: true} ),
//		new Effect.Appear($('roomtype'), { sync: true } ),
		new Effect.Appear($('recalculate'), { sync: true } )
	], { duration: 0.5, queue: { position: 'end', scope: 'toggles' } });

	// actionBookmark.curry('bookstep').delay(0.5);

	Event.stop(event);
}

/**
 * Room picker
 */
function actionToggleRoom(event) {
	// $('pricebreakdown').fade();
	new Effect.Parallel([
		new Effect.Fade($('transport'), { sync: true } ),
		new Effect.Fade($('pricebreakdown'), { sync: true } )
	], { duration: 0.5, queue: { position: 'end', scope: 'toggles' } });

	new Effect.Appear($('roomtype'), { duration: 0.5, queue: { position: 'end', scope: 'toggles' }} );

	Event.stop(event);
}

function actionChangeRoom(event) {
	var element = Event.element(event);

	// alert(element.value);
	if ($('startbooktrip').visible()) {
		$('startbooktrip').hide();
		new Effect.Parallel([
			new Effect.SlideUp($('pricebreakdown'), { sync: true } ),
			new Effect.Fade($('pricebreakdown'), { sync: true } ),
			new Effect.Appear($('recalculate'), { sync: true } )
		], { duration: 0.5, queue: { position: 'end', scope: 'toggles' } });
	}
	else if (!$('recalculate').visible()) {
		$('recalculate').show();
	}

	var app = CoreWebApp.getInstance();
	app.deferAction('setRoom', null, { selectedindex: element.readAttribute('selectedindex'), roomtype: element.value } );
	app.process();
}


/**
 * Transport picking
 */
function actionToggleTransport(event) {
	// $('pricebreakdown').fade();
	new Effect.Parallel([
		new Effect.Fade($('roomtype'), { sync: true } ),
		new Effect.Fade($('pricebreakdown'), { sync: true } )
	], { duration: 0.5, queue: { position: 'end', scope: 'toggles' } });
	new Effect.Appear($('transport'), { duration: 0.5, queue: { position: 'end', scope: 'toggles' }} );
	// new Effect.SlideUp($('pricebreakdown'), { duration: 1.0 } );
	// new Effect.SlideDown($('transport'), { duration: 1.0 } );

	Event.stop(event);
}

function actionSetTransport(name, event) {
	// clearBreakdown();

	var transportNr = null;
	var transportCode;

	var form = Event.element(event).form;
	var radios = form.elements[form.name + '[' + name + ']'];
	if (!Object.isUndefined(radios.length)) {
		for(var i=0, length = radios.length; i<length; ++i) {
			if (radios[i].checked) {
				transportNr = radios[i].value;
				break;
			}
		}
	}
	else if (radios.checked) { // should always be true in this case.
		transportNr = radios.value;
	}

	transportCode = form.elements[form.name + '[' + name + 'Class]' + '[' + transportNr + ']'].value;

	if (transportNr !== null) {
		var app = CoreWebApp.getInstance();
		app.deferAction('setTransport', null, {type: name, transportCode: transportCode} );
		app.process();
	}
}

function actionToggleScheme(classname, event) {
	Event.element(event).up('.toggle').toggleClassName(classname);
	Event.stop(event);
}

function actionRecalculate(event) {
	$('pricebreakdownsnippet').update('');

	new Effect.Parallel([
//		new Effect.Appear($('changenotice'), { sync: true } ),
//		new Effect.Fade($('transport'), { sync: true} ),
//		new Effect.Fade($('roomtype'), { sync: true } ),
		new Effect.Fade($('recalculate'), { sync: true } )
	], { duration: 0.5, queue: { position: 'end', scope: 'toggles' } });

	var app = CoreWebApp.getInstance();

	app.ajax.options.set('pageLoader', $('loading_large'));

	app.deferAction('getPriceInfo', cbPriceCheck, {});

	app.loadContent('currentSelection', 'currentselectionsnippet');
	app.loadContent('priceBreakdown', 'pricebreakdownsnippet');

	// app.loadContent('pickTransport', 'transportsnippet');
	// app.loadContent('changeRoomType', 'roomtypesnippet');
	
	app.process();

	Event.stop(event);
}

/**
 * Book / invoice
 */
function actionStartBookTrip(event) {
	location.href = '/boeken?action=start';
	Event.stop(event);
}

function actionSetOffer(event) {
	var app = CoreWebApp.getInstance();

	var element = Event.element(event);
	var name = element.name + '[';
	var splited = name.split('][');
	var parts = splited[0].split('[');
	var fieldname = parts[1];
	var formname = parts[0];
	var notification = element.up('tr,div').down('.notification');

	var elements = element.form.elements;
	var options = { }; // travelerid: index
	if (splited.length > 2) {
		options[fieldname] = {};
		options[fieldname][splited[1]] = element.value;
	}
	else {
		options[fieldname] = element.value;
	}
	

	app.deferAction('setOffer', cbSetOffer.curry(notification), options);
	// app.loadContent('invoiceTravelInsurance', $('travelinsurance'), {});
	app.process();

	Event.stop(event);
}

function cbSetOffer(notification, value) {
	if (value.state=='fail') {
		// notification.update(value.messages.join('<br/>'));
		notification.update(value.messages[0]);
		notification.show();
	}
	else {
		// notification.update(value.messages.join('<br/>'));
		notification.update('<span class="state valid"></span>');
		notification.show();
	}
}

function actionSetRoomInfo(event) {
	var app = CoreWebApp.getInstance();

	var element = Event.element(event);
	var name = element.name + '[';
	var splited = name.split('][');
	var parts = splited[0].split('[');
	var fieldname = parts[1];
	var formname = parts[0];
	var notification = element.up('tr').down('.notification');

	var elements = element.form.elements;
	var options = { }; // travelerid: index
	if (splited.length > 2) {
		options[fieldname] = {};
		options[fieldname][splited[1]] = element.value;
	}
	else {
		options[fieldname] = element.value;
	}
	

	app.deferAction('setRoomInfo', cbSetRoomInfo.curry(notification), options);
	// app.loadContent('invoiceTravelInsurance', $('travelinsurance'), {});
	app.process();

	Event.stop(event);
}

function cbSetRoomInfo(notification, value) {
	if (value.state=='fail') {
		notification.update(value.messages[0]);
		// notification.update(value.messages.join('<br/>'));
		notification.show();
	}
	else {
		notification.update(value.messages[0]);
		// notification.update(value.messages.join('<br/>'));
		// notification.update('<span class="state valid"></span>');
		notification.show();
	}
}

function actionPickInvoiceCompany(event) {
	var element = Event.element(event);
	var app = CoreWebApp.getInstance();

	app.deferAction('setInvoiceCompany', null, { companyId: element.options[element.selectedIndex].value } );
	app.loadContent('invoiceTravelers', $('travelers'), {});
	app.process();

	element.selectedIndex = 0;

	Event.stop(event);
}

function cbPickInvoiceCompany(value) {
	location.href = location.href;
}

function actionSetTravelerInfo(event) {
	var app = CoreWebApp.getInstance();

	var element = Event.element(event);
	var name = element.name + '[';
	var splited = name.split('][');
	var fieldname = splited[0].split('[')[1];
	var index = splited[1].split('_')[1];
	var formname = name.split('[')[0];
	// var notification = element.up('tr').down('.notification');

	var elements = element.form.elements;
	var options = {travelerid: index};
	options[fieldname] = element.value;

	app.deferAction('setTravelerInfo', cbSetTravelerInfo.curry(element), options);
	// app.loadContent('invoiceTravelInsurance', $('travelinsurance'), {});
	// app.loadContent('invoiceCancelInsurance', $('cancelinsurance'), {});
	app.process();

	Event.stop(event);
}

function cbSetTravelerInfo(element, value) {
	if (value.state=='fail') {
		element.addClassName('error');
		element.removeClassName('correct');
	}
	else {
		element.addClassName('correct');
		element.removeClassName('error');
	}

	// Check for errors on the row
	/*
	var row = element.up('tr');
	var errors = row.select('.error');

	if (errors.length == 0) {
		row.down('.notification').update('<span class="state valid"></span>');
	}
	else {
		row.down('.notification').update('<span class="state invalid"></span>');
	}
	*/
}

function actionAddTraveler(event) {
	var app = CoreWebApp.getInstance();
	app.deferAction('addTraveler', null, {}); // cbAddTraveler
	app.loadContent('invoiceTravelers', $('travelers'), {});
	// app.loadContent('invoiceTravelInsurance', $('travelinsurance'), {});
	// app.loadContent('invoiceCancelInsurance', $('cancelinsurance'), {});
	app.process();

	Event.stop(event);
}

function actionRemoveTraveler(event) {
	var app = CoreWebApp.getInstance();

	var person = Event.findElement(event, '.personinfo');

	app.deferAction('removeTraveler', cbRemoveTraveler, { travelerid: person.id.split('_')[1] } );
	app.loadContent('invoiceTravelers', $('travelers'), {});
	// app.loadContent('invoiceTravelInsurance', $('travelinsurance'), {});
	// app.loadContent('invoiceCancelInsurance', $('cancelinsurance'), {});
	app.process();

	Event.stop(event);
}

function cbRemoveTraveler(value) {
	if (value.removed == false) {
		setMessage(value.messages.join('<br/>'));
	}
}

function actionSetCoupon(event) {
	var app = CoreWebApp.getInstance();
	var element = Event.element(event);
	app.deferAction('setCoupon', null, { number: element.value } );
	if ($('pricebreakdownsnippet')) app.loadContent('invoicePriceBreakdown', $('pricebreakdownsnippet'));
	app.process();

	Event.stop(event);
}

function actionSetInsurance(event) {
	var app = CoreWebApp.getInstance();
	var element = Event.element(event);

	var insuranceType = element.up('div.insurance').readAttribute('type');

	togglePersonTable(element.up('div.insurance'), (element.value==1));

	app.deferAction('setInsurance', null, { type: insuranceType, value: (element.value==1) } );
	if ($('pricebreakdownsnippet')) app.loadContent('invoicePriceBreakdown', $('pricebreakdownsnippet'));
	app.process();
	// Event.stop(event);
}

function actionSetInsurancePerson(event) {
	var app = CoreWebApp.getInstance();
	var element = Event.element(event);

	var insuranceType = element.up('div.insurance').readAttribute('type');

	var parts = (element.name + '[').split('][');
	parts.pop();
	var personIndex = parts.pop();

	app.deferAction('setInsurancePerson', null, { type: insuranceType, personIndex: personIndex, value: element.checked } );
	if ($('pricebreakdownsnippet')) app.loadContent('invoicePriceBreakdown', $('pricebreakdownsnippet'));
	app.process();
	// Event.stop(event);
}

function togglePersonTable(element, visible) {
	if (visible) {
		element.down('ul').show();
		var elements = element.down('ul').select('input');
		for(var i=0, len = elements.length; i < len; i++) {
			elements[i].checked = true;
		}
	}
	else {
		element.down('ul').hide();
	}
}

/**
 * Invoice
 */
function actionGetTouroperatorComment(event) {
	var app = CoreWebApp.getInstance();
	app.deferAction('getTouroperatorComment', cbGetTouroperatorComment.curry($('touroperatorcomment')), { touroperator: event.element().value });
	app.process();

	Event.stop(event);
}

function cbGetTouroperatorComment(element, value) {
	element.update(value.comment);

	if (value.comment==null || value.comment.length==0) {
		element.hide();
	}
	else {
		element.show();
	}
}

function actionShowAirport(event) {
	var element = Event.element(event);

	if (element.value == 'vl') {
		$('offer_airport').show();
	}
	else {
		$('offer_airport').hide();
	}

	Event.stop(event);
}

function actionAddRoom(event) {
	var app = CoreWebApp.getInstance();
	app.deferAction('addRoom', null, { });
	app.loadContent('invoiceRooms', $('rooms').up());
	app.process();

	Event.stop(event);
}

function actionRemoveRoom(event) {
	var app = CoreWebApp.getInstance();
	app.deferAction('removeRoom', null, { index: event.findElement('tr').readAttribute('value') });
	app.loadContent('invoiceRooms', $('rooms').up());
	app.process();

	Event.stop(event);
}

function actionShowQuestion(event) {
	if ($('invoice_accept').visible()) {
		new Effect.Parallel([
			new Effect.BlindUp($('invoice_accept'), {sync: true }),
			new Effect.Fade($('invoice_accept'), {sync: true })
		], {});
	}

	if ($('invoice_reject').visible()) {
		new Effect.Parallel([
			new Effect.BlindUp($('invoice_reject'), {sync: true }),
			new Effect.Fade($('invoice_reject'), {sync: true })
		], {});
	}

	new Effect.Parallel([
		new Effect.BlindDown($('invoice_choice_state'), {sync: true }),
		new Effect.Appear($('invoice_choice_state'), {sync: true })
	], {});

}

function actionShowBooksteps(event) {
	if ($('invoice_choice_state').visible()) {
		new Effect.Parallel([
			new Effect.BlindUp($('invoice_choice_state'), {sync: true }),
			new Effect.Fade($('invoice_choice_state'), {sync: true })
		], {});
	}

	if ($('invoice_reject').visible()) {
		new Effect.Parallel([
			new Effect.BlindUp($('invoice_reject'), {sync: true }),
			new Effect.Fade($('invoice_reject'), {sync: true })
		], {});
	}

	new Effect.Parallel([
		new Effect.BlindDown($('invoice_accept'), {sync: true }),
		new Effect.Appear($('invoice_accept'), {sync: true })
	], { });
}

function actionShowDenied(event) {
	if ($('invoice_choice_state').visible()) {
		new Effect.Parallel([
			new Effect.BlindUp($('invoice_choice_state')),
			new Effect.Fade($('invoice_choice_state'))
		], {});
	}

	if ($('invoice_accept').visible()) {
		new Effect.Parallel([
			new Effect.BlindUp($('invoice_accept')),
			new Effect.Fade($('invoice_accept'))
		], {});
	}

	new Effect.Parallel([
		new Effect.BlindDown($('invoice_reject')),
		new Effect.Appear($('invoice_reject'))
	], {});
}

function actionSelectRejectOption(event) {
	var element = Event.element(event);

	// $('rejectreason').hide();

	if ($('rejectreason').visible()) {
		new Effect.Parallel([
			new Effect.BlindUp($('rejectreason'), { sync: true } ),
			new Effect.Fade($('rejectreason'), { sync: true })
		], { queue: 'end' });
	}

	$('rejectoptions').down('.answers').hide();

	new Effect.Parallel([
		new Effect.BlindDown($('rejectreason'), { sync: true }),
		new Effect.Appear($('rejectreason'), { sync: true })
	], { queue: 'end', afterSetup: cbSelectRejectOption.curry(element.up('li').readAttribute('value'), element.up('li').readAttribute('subject')) });

	
}

function cbSelectRejectOption(text, subject) {
	$('rejectreason').down('p').update(text);
	$('rejectreason').down('.subject').value = subject;
}

/**
 * Dossier
 */
function actionPickInvoice(event) {
	location.href = 'http://' + location.hostname + event.element().up('tr').readAttribute('value');
	Event.stop(event);
}

function toggleSendMessage(event) {
	var element = Event.findElement(event, '#sendmessage');	

	var children = element.childElements();
	for(var i=0, len=children.length;i < len; ++i) {
		children[i].toggle();
	}
}

function toggleMessage(event) {
	var element = Event.findElement(event, 'li');
	var contentEl = element.down('dd.content');
	// var contentSmallEl = element.down('dd.contentsmall');

	if (element.hasClassName('collapsed')) {
		/*
		new Effect.Parallel([
			new Effect.Appear(contentEl, { sync: true }),
			new Effect.SlideDown(contentEl, { sync: true })
		], { duration: 1.0, queue: { position: 'end', scope: 'message' + element.id, limit: 1 } } );
		element.removeClassName('collapsed');
		*/
		element.removeClassName('collapsed');

		var app = CoreWebApp.getInstance();
		app.deferAction('readMessage', cbMessageRead.curry(element), { id: element.id.split('_')[1], offerid: element.up('ul').readAttribute('offerid') });
		app.process();
	}
	else {
		/*
		new Effect.Parallel([
			new Effect.Fade(contentEl, { sync: true } ),
			new Effect.SlideUp(contentEl, { sync: true })
		], { duration: 1.0, queue: { position: 'end', scope: 'message' + element.id, limit: 1 }, afterFinish: toggleCollapsed.curry(element) } );
		*/
		element.addClassName('collapsed');
	}

	// element.toggleClassName('collapsed');

	Event.stop(event);
}

function cbMessageRead(element, value) {
	if (value.state == 'success') {
		element.removeClassName('unread');
	}
}

function toggleCollapsed(element, more) {
	element.toggleClassName('collapsed');
}

function setProfileAttribute(event) {
	var element = Event.element(event);

	var app = CoreWebApp.getInstance();
	app.deferAction('setProfile', null, { attribute: element.value, value: (element.checked ? 1 : 0) });
	app.process();
}

function setProfileAttributeInverse(event) {
	var element = Event.element(event);

	var app = CoreWebApp.getInstance();
	app.deferAction('setProfile', null, { attribute: element.value, value: (element.checked ? 0 : 1) });
	app.process();
}

function actionToggleFavorite(event) {
	var element = Event.element(event);

	var app = CoreWebApp.getInstance();
	if (element.hasClassName('remove')) {
		app.deferAction('removeFavorite', cbToggleFavorite.curry(element), { accommodationId: element.readAttribute('value') });
	}
	else {
		app.deferAction('addFavorite', cbToggleFavorite.curry(element), { accommodationId: element.readAttribute('value') });
	}
	app.process();

	Event.stop(event);
}

function cbToggleFavorite(element, value) {
	if (value.state == 'success') {
		element.toggleClassName('remove');
		setMessage(value.messages.join('<br/>'));
		var li = element.up('li');
		if (!Object.isUndefined(li) && li.hasClassName('accommodation')) {
			var ul = li.parentNode;
			ul.removeChild(li);
			var els = ul.childElements();
			var odd = false;
			for(var len=els.length, i = 0; i < len; ++i) {
				var el = els[i];
				if (!el.hasClassName(odd ? 'odd' : 'even')) {
					el.removeClassName(odd ? 'even' : 'odd');
					el.addClassName(odd ? 'odd' : 'even');
				}
				odd = !odd;
			}
		}
	}
}


