Behaviour.register({
	'select': function( obj ) {
		var active	= obj.getAttribute('active');
		if( active != '' && obj.options.length > 0 )
		{
			var options	= obj.options;
			for(var i=0; i<options.length; i++)
			{
				if( options[i].value == active )
				{
					obj.selectedIndex	= i;
					//options[i].selected = true;
					return;
				}
			}
		}
	},
	'body': function( obj ) {
		// none
	},
	'fieldset.adresxpress': function( obj ) {
		if( AdresXpressCache.store[obj] )
			return;

		// Setup onload & oncomplete handlers
		obj.onload	= function() {
			var baseid		= this.id;
			var postalcode	= $(baseid + '_postalcode');

			if( postalcode.value.length == 0 ) {
				var divs	= getChildrenByTagName( this, 'DIV' );
				if( divs.length == 0 )
					divs	= this.getElementsByTagName( 'TR' );
				Element.hide( divs[1] );
				Element.hide( divs[2] );
				if( divs[3] )
					Element.hide( divs[3] );
			}
		}.bindAsEventListener(obj);

		obj.oncomplete	= function() {
			var baseid		= this.id;
			var postalcode	= $(baseid + '_postalcode');
			var housenum	= $(baseid + '_number');
			
			if( postalcode.value.length > 0 && housenum.value.length > 0 ) {
				var divs	= getChildrenByTagName( this, 'DIV' );
				if( divs.length == 0 )
					divs	= this.getElementsByTagName( 'TR' );
				Element.show( divs[1] );
				Element.show( divs[2] );
				if( divs[3] )
					Element.show( divs[3] );
			}
		}.bindAsEventListener(obj);

		new AdresXpress( obj.getAttribute('id') );
	}
});

function addToFavorites()
{
	if (document.all)
		window.external.AddFavorite( 'http://' + location.hostname, document.title );
}

AdresXpressCache	= Class.create({
	cache: {},
	store: {},
	get: function( ident ) {
		return this.cache[ident];
	},
	put: function( ident, data ) {
		this.cache[ident] = data;
	}
});
AdresXpressCache = new AdresXpressCache();
AdresXpress = Class.create({
	baseid: '',
	objs: {},
	busyicon: null,
	initialize: function( baseid ) {
		this.baseid	= baseid;
		this.objs	= {
			postalcode:	$(baseid + '_postalcode'),
			number:		$(baseid + '_number'),
			street:		$(baseid + '_street'),
			city:		$(baseid + '_city'),
			country:	$(baseid + '_country')
		};

		// Call optional onload handler
		if( $(baseid).onload )
			$(baseid).onload();

		// Register event handlers
		Event.observe( this.objs.postalcode, 'blur', this.handlePostalcode.bindAsEventListener(this) );
		Event.observe( this.objs.number, 'blur', this.handleNumber.bindAsEventListener(this) );
		Event.observe( this.objs.street, 'blur', this.handleStreet.bindAsEventListener(this) );

		AdresXpressCache.store[baseid] = this;
	},	
	handlePostalcode: function() {
		this.objs.postalcode.value = this.objs.postalcode.value.toUpperCase();
	},
	handleNumber: function() {
		var code	= this.objs.postalcode.value.replace( /[^0-9A-Z]/i, '' );
		var num		= this.objs.number.value.replace( /[^0-9]/, '' );
		var ident	= code + num;

		if( code.match( /[0-9]{4}[ ]{0,1}[a-zA-Z]{2}/ ) && !isNaN(parseInt(num)) )
		{
			// Check cache
			var cache	= AdresXpressCache.get( ident );
			if( cache != null )
			{
				this.updateFields( cache );
				return;
			}

			// Display busy icon
			this.busyicon		= document.createElement( 'IMG' );
			this.busyicon.src	= '/media/images/ajax_running.gif';
			this.busyicon.style.margin	= '2px 0px -2px 5px';
			this.objs.number.parentNode.appendChild( this.busyicon );

			// Block street + city fields
			this.objs.street.disabled	= 'disabled';
			this.objs.city.disabled		= 'disabled';

			// AJAX request
			new Ajax.Request(
				'/XML/AdresXpress?postcode='+code+'&huisnummer='+num, 
				{
					onComplete: this.handleAjaxData.bindAsEventListener(this)
				}
			) // Ajax.Request
		}
		else
		{
			this.updateFields( {} );
		}
	},
	handleStreet: function() {
		var street	= this.objs.street.value.replace( /\s+$/, '' );
		var num		= this.objs.number.value;

		if( street.substring( street.length - num.length ) != num )
			this.objs.street.value = street + ' ' + num;
	},
	handleAjaxData: function( request ) {
		// Remove busy icon
		this.busyicon.parentNode.removeChild( this.busyicon );
		this.busyicon	= null;

		var retval	= request.getResponseHeader( 'X-RETVAL' );
		if( retval != 'ok' ) {
			alert( 'error' );
			return;
		}

		var doc		= request.responseXML;
		var address	= doc.selectSingleNode( '/address' );
		var data	= {};

		if( doc.selectNodes( '/address/straatnaam' ).length == 0 )
		{
			this.updateFields( data );

			// Cache
			var ident			= address.getAttribute('postcode') + address.getAttribute('huisnummer')
			AdresXpressCache.put( ident, data );

			return;
		}

		data['straatnaam']	= doc.selectSingleNode( '/address/straatnaam' ).firstChild.nodeValue;
		data['huisnummer']	= doc.selectSingleNode( '/address/huisnummer' ).firstChild.nodeValue;
		data['postcode']	= doc.selectSingleNode( '/address/postcode' ).firstChild.nodeValue;
		data['woonplaats']	= doc.selectSingleNode( '/address/woonplaats' ).firstChild.nodeValue;
		data['netnummer']	= doc.selectSingleNode( '/address/netnummer' ).firstChild.nodeValue;

		this.updateFields( data );

		// Cache
		var ident			= address.getAttribute('postcode') + address.getAttribute('huisnummer')
		AdresXpressCache.put( ident, data );
	},
	updateFields: function( data ) {
		// Unblock street + city fields
		this.objs.street.removeAttribute( 'disabled' );
		this.objs.city.removeAttribute( 'disabled' );

		// Call optional oncomplete handler
		if( $(this.baseid).oncomplete )
			$(this.baseid).oncomplete();

		if( data['straatnaam'] == null )
		{
			//this.objs.street.value	= '';
			//this.objs.city.value	= '';
			/*try {
				this.objs.street.focus();
			} catch(e) {};*/
		}
		else
		{
			this.objs.street.value	= data['straatnaam'] + ' ' + this.objs.number.value;
			this.objs.city.value	= data['woonplaats'];
			/*
			if( this.objs.country )
				this.focusNext( this.objs.country );
			else
				this.focusNext( this.objs.city );
			*/
		}		
	},
	focusNext: function( field ) {
		var f	= field.form;
		var els = f.elements;
		var x, nextEl;
		for( var i=0, len=els.length; i<len; ++i ) {
			x = els[i];
			if( field == x && ( nextEl = els[i+1] ) )
				if( nextEl.focus ) try { nextEl.focus(); } catch(e) {};
		}
	}
})

function localizeURI( uri ) {
	// Check for locale in current URI
	var path = window.location.pathname;
	if( path.match( /^\/[a-z]{2}_[A-Z]{2}\// ) ) {
		return path.substr(0,6) + uri;
	} else {
		return uri;
	}
}

/** Add XMLDocument::selectNodes() and XMLDocument::selectSingleNode to mozilla */
if( document.implementation.hasFeature('XPath', '3.0') )
{
	XMLDocument.prototype.selectNodes = function( cXPathString, xNode )
	{
		if( !xNode ) { xNode = this; } 
		var oNSResolver = this.createNSResolver( this.documentElement )
		var aItems = this.evaluate( cXPathString, xNode, oNSResolver, 
						XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null )
		var aResult = [];
		for( var i = 0; i < aItems.snapshotLength; i++ )
			aResult[i] =  aItems.snapshotItem(i);

		return aResult;
	}
	XMLDocument.prototype.selectSingleNode = function( cXPathString, xNode )
	{
		if( !xNode ) { xNode = this; } 
		var xItems = this.selectNodes( cXPathString, xNode );
		if( xItems.length > 0 )
			return xItems[0];
		else
			return null;
	}
}

function getChildrenByTagName( node, tagName ) {
	var out	= [];
	tagName	= tagName.toUpperCase();

	if( node && node.childNodes ) {
		for( var i=0; i<node.childNodes.length; ++i ) {
			if( node.childNodes[i].tagName && node.childNodes[i].tagName.toUpperCase() == tagName )
				out.push( node.childNodes[i] );
		}
	}

	return out;
}

FieldHint = {
	currentHint: null,
	findHint: function( node ) {
		if( node.attributes['hint'] == undefined && node.attributes['rb:hint'] == undefined ) {
			var divs = node.parentNode ? node.parentNode.getElementsByTagName( 'div' ) : [];
			for (var i=0; i<divs.length; i++) {
				if( divs[i].className.indexOf( 'hint' ) >= 0 )
					return divs[i];
			}
			return null;
		} else {
			if( node.attributes['hint'] != undefined )
				return $(node.getAttribute('hint'));
			else
				return $(node.getAttribute('rb:hint'));
		}
	},
	show: function( node ) {
		var hint = FieldHint.findHint( node );
		if( hint ) {
			FieldHint.currentHint = { node: node, hint: hint };
			var parent = $(node.parentNode);
			var offset	= parent.positionedOffset();
			var dimension = parent.getDimensions();

			hint.style.top = offset.top + 5 + 'px';
			hint.style.left = offset.left + dimension.width + 15 + 'px';
			hint.style.display = 'inline';
		}
	},
	hide: function( node ) {
		var hint = FieldHint.findHint( node );
		if( hint ) {
			FieldHint.currentHint = null;
			hint.style.display = 'none';
		}
	},
	prepare: function( obj ) {
		FieldHint.hook( obj.getElementsByTagName( 'input' ) );
		FieldHint.hook( obj.getElementsByTagName( 'select' ) );
		FieldHint.hook( obj.getElementsByTagName( 'textarea' ) );
	},
	hook: function( objs ) {
		var focusHook = function( evt ) {
			FieldHint.show( Event.element( evt || window.event ) );
		};
		var blurHook = function( evt ) {
			FieldHint.hide( Event.element( evt || window.event ) );
		};
		for (var i=0; i<objs.length; i++) {
			if( objs[i].attributes['nohint'] != undefined || objs[i].attributes['rb:nohint'] != undefined )
				continue;
				
			Event.observe( objs[i], 'focus', focusHook );
			Event.observe( objs[i], 'blur', blurHook );
		}
	},
	bootstrap: function() {
		// Capture window resize to reposition active hint
		Event.observe(document.onresize ? document : window, 'resize', function() {
			if( FieldHint.currentHint != null ) {
				FieldHint.show( FieldHint.currentHint.node );
			}
		});
	}
}

FormStore = {
	store: {},
	read: function( ident, node ) {
		FormStore.store[ident] = {};
		
		FormStore.readFields( ident, node.getElementsByTagName( 'input' ) );
	},
	write: function( ident, node ) {
		FormStore.writeFields( ident, node.getElementsByTagName( 'input' ) );
	},
	readFields: function( ident, nodes ) {
		nodes = nodes || [];
		for( var i=0; i<nodes.length; i++ ) {
			FormStore.store[ident][nodes[i].name] = $F(nodes[i]);
		}
	},
	writeFields: function( ident, nodes ) {
		nodes = nodes || [];
		for( var i=0; i<nodes.length; i++ ) {
			node = nodes[i];
			if( FormStore.store[ident] && FormStore.store[ident][node.name] )
				node.value = FormStore.store[ident][node.name];
		}
	}
}

Newsletter = {
	subscribe: function() {
		new Ajax.Updater( 'newsletter-menu', localizeURI('/Site/Newsletter'), {
			method: 'post',
			parameters: Form.serialize( 'newsletter-menu' ),
			onComplete: function() {
				Newsletter.bootstrap();
				$('newsletter-fname').focus();
				$('newsletter-fname').select();
			}
		});
	},
	bootstrap: function() {
		if( $('newsletter-menu') ) {
			Event.observe( $('newsletter-email'), 'keydown', function(evt) {
				var event = evt || window.event;
				if( event.keyCode == Event.KEY_RETURN ) {
					Newsletter.subscribe();
					Event.stop( event );
				}
			} );
			Event.observe( $('newsletter-subscribe'), 'click', function(evt) {
				var event = evt || window.event;
				Newsletter.subscribe();
				Event.stop( event );
			} );
		}
	}
}
//Bootstrap
Event.observe( window, 'load', function() {
	FieldHint.bootstrap();
	Newsletter.bootstrap();
});
