var Rectangle = new Class( {
	initialize : function( left, top, width, height )
	{
		switch ( $type(left) )
		{
			case 'element' :
				var d = left.getCoordinates();

				this.left   = d.left;
				this.top    = d.top;
				this.width  = d.width;
				this.height = d.height;
				break;
			case 'window' :
				var p = left.getScroll();
				var s = left.getSize();

				this.left   = p.x;
				this.top    = p.y;
				this.width  = s.x;
				this.height = s.y;
				break;
			default :
				this.left = left;
				this.top  = top;
				this.width = width;
				this.height = height;
		}
	},
	intersect : function( rectangle )
	{
		var l = Math.max( rectangle.left, this.left );
		var t = Math.max( rectangle.top, this.top );
		var w = Math.min( rectangle.left + rectangle.width, this.left + this.width ) - l;
		var h = Math.min( rectangle.top + rectangle.height, this.top + this.height ) - t;

		return new Rectangle( l, t, w, h );
	},
	covers : function( rectangle )
	{
		var intersect = this.intersect( rectangle );

		return ( ( intersect.width == rectangle.width ) && ( intersect.height == rectangle.height ) );
	}
} );

var ColumnFloater = new Class({
	initialize: function( canvas, boxes, spacing )
	{
		this.spacing = spacing;

		this.canvas = $$(canvas)[0];
		if ( this.canvas )
		{
			this.boxes = this.canvas.getChildren(boxes);

			if ( this.boxes && this.boxes.length )
			{
				this.colsWidth = this.width = 0;
				with ( this.boxes[0].getPosition(this.canvas) ) this.top = y;

				this.boxes.each( function(c) {
					with ( $(c).getSize() ) this.colsWidth = Math.max( this.colsWidth, x );
				},this);

				this.canvas.setStyle('min-width',this.colsWidth+'px');

				if ( this.colsWidth + this.spacing )
				{
					this.relayout();

					$(window).addEvent('resize',this.onresize.bind(this));
				}
			}
		}
	},
	// slightly delays relayouting to speed-up window resizing
	onresize : function()
	{
		if ( this.delayer )
			window.clearTimeout( this.delayer );

		this.delayer = window.setTimeout( this.relayout.bind( this ), 500 );
	},
	// fixes column-floating layout
	relayout : function()
	{
		if ( this.delayer )
		{
			window.clearTimeout( this.delayer );
			this.delayer = null;
		}

		var cSize = this.canvas.getSize();

		if ( this.width == cSize.x )
			// width hasn't change -> won't relayout
			return;

		this.width = cSize.x;

		var cols = [];
		for ( var i = Math.max( 1, Math.floor( ( cSize.x + this.spacing ) / ( this.colsWidth + this.spacing ) ) ) - 1; i >= 0; i-- )
			cols.push( this.top );

		var col = 0;
		this.boxes.each( function(c) {
			c.setStyles({
				position: 'absolute',
				top: cols[col] + 'px',
				left: String(col*(this.colsWidth+this.spacing))+'px'
			});

			with ( c.getSize() )
				cols[col] += y + this.spacing;

			col = ( col + 1 ) % cols.length;
		}, this);

		var height = 0;
		for ( var i = 0; i < cols.length; i++ )
			height = Math.max( height, cols[i] );

		this.canvas.setStyle('min-height',height+'px');
	}
});


$(window).addEvents({
	'domready' : function(){
		// enable browser-specific css
		$$('body').addClass(Browser.Engine.name);
		$$('body').addClass(Browser.Engine.name+'-'+Browser.Engine.version);

		// enable dropdown menus
		$$('.mod_navigation li').addEvents({
			mouseenter : function() { $(this).addClass( 'hover' ); },
			mouseleave : function() { $(this).removeClass( 'hover' ); }
		});

		// show quicksearch label inside empty search box
//		var qs  = $('quicksearch');
//		var qsl = qs.getElement('label').get('text');
//		var qsi = qs.getElement('input.text');
//		var qsv = qsi.get('value');
//
//		if ( !qsv.trim().length )
//			qsi.set('value',qsl)
//				.addClass('empty');
//
//		qsi.addEvents({
//			focus : function() {if ( qsi.hasClass('empty') ) qsi.removeClass('empty').set('value',''); qsi.select();},
//			blur : function() {if ( !qsi.get('value').trim().length ) qsi.addClass('empty').set('value',qsl);},
//			submit : function() {if ( qsi.hasClass('empty') ) qsi.set('value','');}
//		});

		// manage inline popups
		$$('.popup').each( function( item ) {
			item = $(item);
			item.relatedPopup = new Element( 'div', {
										'html' : item.get('html'),
										'class' : 'popup-box',
										'styles' : {
											display: 'block',
											position: 'absolute',
											'z-index' : 1000
										} } );
			item
				.set( 'html', '*' )
				.setStyle( 'cursor', 'none' );

			item.addEvents({
				mouseenter: function() {
					var hook = this.getPosition();
					var hookSize = this.getSize();
					var box = this.relatedPopup.getSize();
					var win = $(window).getSize();

					if ( hook.x + hookSize.x + box.x > win.x )
						hook.x -= box.x;
					else
						hook.x += hookSize.x;

					if ( hook.y + hookSize.y + box.y > win.y )
						hook.y -= box.y;
					else
						hook.y += hookSize.y;

					this.relatedPopup.setStyles({
						'left' : hook.x + 'px',
						'top' : hook.y + 'px'
					});
					$$('body')[0].adopt( this.relatedPopup );
				}.bindWithEvent( item ),
				mouseleave: function() {
					this.relatedPopup.dispose();
				}.bindWithEvent( item )
			});
		});

		// fix structure of left-hand breadcrumb
		if ( $$('#left .mod_navigation').length < 2 )
			if ( $$('#left .mod_breadcrumb li').length < 2 )
				$$('#left .mod_breadcrumb').dispose();

		// enable collapsable/expandable content
		$$('.collapsed, .expanded').each( function( container ) {
			var trigger = $(container).getChildren('legend')[0];
			var content = $(container).getChildren('div')[0];

			trigger.addEvents({
				click : function() {
					if ( container.hasClass( 'collapsed' ) )
						container
							.addClass( 'expanded' )
							.removeClass( 'collapsed' )
							.getParent().getElements('button.normal-search-on-distributor').addClass('invisible');
					else
						container
							.removeClass( 'expanded' )
							.addClass( 'collapsed' )
							.getParent().getElements('button.normal-search-on-distributor').removeClass('invisible');
				}
			});
		});

		// link foot note references with related footnote so user can click to follow
		$$('.mod_iso_productlist').each( function( list ) {
			var note = list.getElement('.pangv-statement sup');

			list.getElements('sup').each( function( ref ) {
				if ( ref != note )
					ref
						.addEvent('click', function() {
							var wr = new Rectangle( window );
							var nr = new Rectangle( note.getParent() );

							if ( !wr.covers( nr ) )
								window.scroll( nr.left, nr.top );

							note.getParent().highlight( '#ff0' );

							return false;
						} )
						.addClass( 'clickable' );
			} );
		} );

		// find talles matrix block on page
		var maxMatrixBoxHeight = 0;
		$$('body.matrix .matrix-box').each( function( box ) {
			maxMatrixBoxHeight = Math.max( maxMatrixBoxHeight, box.getComputedSize().height );
		} );

		// make matrix blocks clickable as a whole
		$$('body.matrix .matrix-box').each( function( box ) {
			var href = null;

			box.getElements('a').each( function( link ) {
				if ( !href )
					href = link.href;
				else if ( link.href && ( href != link.href ) )
				{
					href = null;
					return false;
				}
			} );

			if ( href )
				box
					.addClass( 'clickable' )
					.addEvent( 'click', function() { location.href = href; return false; } );

			// normalize matrix layout by applying tallest height to all boxes on screen
			box.setStyle( 'height', maxMatrixBoxHeight + 'px' );

			// vertically center image
			var iContainer = box.getElement( '.image_container' );
			var image = box.getElement( 'img' );
			image.setStyle( 'padding-top', String( ( ( iContainer ? iContainer.getComputedSize().height : 260 ) - image.getSize().y ) / 2 ) + 'px' );
		} );

		// add separate prompt on quicksearch
//		$('left').grab( new Element( 'div', { 'class' : 'fake-search-prompt', 'text' : 'Suche:', styles: { display : 'none' } } ), 'top' );


		// fix structure of articles on page
//		$$('.matrix #main * .block:not(.fixed)').each( function(e) {
//			var c = e.getChildren('.block');
//			if ( c && c.length )
//				e = c.shift();
//
//			var i = e.getElement('.image_container');
//			if ( i )
//				i.dispose().grab(new Element('div',{'class':'content'}).adopt(e.getChildren())).inject(e);
//		});
//
//		document.columnlayouter = new ColumnFloater( '.matrix #main > .inside', '.block:not(.fixed)', 30 );
	},
	'unload' : function() {
		// prevent inset quicksearch label from becoming actual search term on reload
//		var qsi = $$('#quicksearch input.text')[0];
//		if ( qsi.hasClass('empty') )
//			qsi.set('value','');
	}
} );


