Object.extend(document, {
	loaded: function(callback) {

		if(!document._callbacks) document._callbacks = new Array();
		document._callbacks.push(callback);

		/* for Mozilla/Opera9 */
		if (document.addEventListener) {
		    document.addEventListener("DOMContentLoaded", this._contentLoadedInit, false);
		}

		/* for Internet Explorer */
		/*@cc_on @*/
		/*@if (@_win32)
		    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
		    var script = document.getElementById("__ie_onload");
		    script.onreadystatechange = function() {
			if (this.readyState == "complete") {
			    document._contentLoadedInit(); // call the onload handler
			}
		    };
		/*@end @*/

		/* for Safari */
		if (/WebKit/i.test(navigator.userAgent)) { // sniff
		    document._domTimer = setInterval(function() {
			if (/loaded|complete/.test(document.readyState)) {
			    document._contentLoadedInit(); // call the onload handler
			}
		    }, 10);
		}

		/* for other browsers */
		Event.observe(window, 'load', document._contentLoadedInit);
	},

	_contentLoadedInit: function() {

		if(document.callbackFired) return;
		document.callbackFired = true;

		// kill the timer
		if (document._domTimer) clearInterval(document._domTimer);

		document._callbacks.each(function(f) {

			f()
		});
	}
});





var BREADCRUMB_TITLE_POSTFIX = ': Vitra.com';
var BREADCRUMB_MAX_ITEMS = 10;
var BREADCRUMB_MAX_CHARS = 120;


function attachEvents()
{
	/* Because IE6 doesn't understand the :hover pseudo-class on anything but
	'a' elements, we need to double-implement the rollover */
	var searchButton = $('site-search-button');
	if(searchButton) {

		Event.observe(searchButton, 'mouseover', function() { this.addClassName('site-search-button-hover');  }.bindAsEventListener(searchButton));
		Event.observe(searchButton, 'mouseout', function() { this.removeClassName('site-search-button-hover');  }.bindAsEventListener(searchButton));
	}

	insertBreadcrumb();
	
	addWishlistEvents();
	
	addChangeCountryLinks();
	
	new LanguageBar();
	
	new VitraOverlay();
}



/*
 * Function adds the current page to the breadcrumb trail before attempting
 * to output the trail - if there is a placeholder for it on the page.
 */
function insertBreadcrumb()
{
	var bc = new Breadcrumb();
	bc.addPage();
	var breadcrumbHeader = $('footer-how-you-got-here-header');

	if(breadcrumbHeader) {

		var trail = bc.display();
		new Insertion.After('footer-how-you-got-here-header', '\n<ul>' + trail.innerHTML + '</ul>');
	}
}



function addWishlistEvents()
{
	var wishlist = new Wishlist();

	var wishlistLink = $('nav-wishlist-link');
	if(wishlistLink) {

		var span = document.createElement('span');
		span.id = 'nav-wishlist-link-items-container';

		var img = document.createElement('img');
		img.src = '/_images/wishlist/numbers/' + wishlist.wishlist.length + '.png';
		img.className = 'png';
		img.alt = '(' + wishlist.wishlist.length + ')';
		img.id = 'nav-wishlist-link-items';
		img.width = 19;
		img.height = 12;

		span.appendChild(img);
		wishlistLink.appendChild(span);
	}

	var wishlistButton = $('product-options-add-to-wishlist-button');
	if(wishlistButton) {

		if(wishlist.inWishlist(PRODUCT)) {

			wishlistButton.addClassName('added');
			wishlistButton.onclick = function() { return false; };
		}

		/* Fix IE6 lack of :hover support */
		Event.observe(wishlistButton, 'mouseover', function() { this.addClassName('hover'); }.bindAsEventListener(wishlistButton));
		Event.observe(wishlistButton, 'mouseout', function() { this.removeClassName('hover'); }.bindAsEventListener(wishlistButton));
	}


	var wishlistForm = $('product-options-add-to-wishlist-form');
	if(wishlistForm) {

		/* preload working image */
		var workingImage = new Image();
		workingImage.src = '/_images/icons/loader.gif';

		Event.observe(wishlistForm, 'submit', function(e) {

			wishlistButton.onclick = function() { return false; };

			var img = document.createElement('img');
			img.src = '/_images/icons/loader.gif';
			img.id = 'product-options-add-to-wishlist-saving';

			$('product-options-add-to-wishlist-form-div').appendChild(img);

			var formAction = wishlistForm.action;
			var actionParts = formAction.split('/');

			wishlist.addProduct(actionParts[actionParts.length -2]);

			/* preload next wishlist number image */
			var numberItemsImage = new Image();
			numberItemsImage.src = '/_images/wishlist/numbers/' + wishlist.wishlist.length + '.png';

			setTimeout(function() {

					var wishlistItems = $('nav-wishlist-link-items');
					if(wishlistItems) {

						wishlistItems.src = '/_images/wishlist/numbers/' + wishlist.wishlist.length + '.png';
						wishlistItems.alt = '(' + wishlist.wishlist.length + ')';
						wishlistItems.width = 19;
						wishlistItems.height = 12;
					}

					new Effect.Fade('product-options-add-to-wishlist-saving', {
							duration: 1.4,
							afterFinish: function() {

								$('product-options-add-to-wishlist-saving').remove();
							}
					});
					$('product-options-add-to-wishlist-button').addClassName('added');
					$('product-options-add-to-wishlist-button').alt = '';
				},
				1200
			);

			Event.stop(e);
		});
	}
}



function addChangeCountryLinks()
{
	var footerLink = $('footer-links-change-country');
	var homePageLink = $('market-home-content-change-country');
	
	var links = new Array();
	if(footerLink) links.push(footerLink.down('a'));
	if(homePageLink) {

		Event.observe(homePageLink, 'mouseover', function() { this.down('span').addClassName('hover'); }.bind(homePageLink));
		Event.observe(homePageLink, 'mouseout', function() { this.down('span').removeClassName('hover'); }.bind(homePageLink));
		links.push(homePageLink);
	}
	
	if($('language-bar-map') &&  $('language-bar')) {
		
		links.push($('language-bar-map'));
		links.push($('language-bar').down('a.language'));
	}

	for(var i = 0; i < links.length; i++) {

		Event.observe(links[i], 'click', function(e) {

			var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape('country') + '=([^;\\s]*)'));
			if(typeof(cookie) != 'undefined' && cookie != null) {

				var d = new Date();
				d.setTime(d.getTime() + (86400000 * parseFloat(-1)));

				document.cookie = 'country=' + escape(cookie[2]) + '; expires=' + d.toGMTString() + '; path=/';
			}
		});
	}
}





/*
 * Breadcrumb Class
 *
 * This class is used to maintain a breadcrumb trail of pages the user has visited.
 * Instantiating the class and calling addPage will add the current page to the
 * list. Calling display will return an unordered list of pages visited, truncated
 * to BREADCRUMB_MAX_CHARS number of characters.
 *
 * Chris Blackburn <chrisb@de-construct.com>
 */
var Breadcrumb = Class.create();
Breadcrumb.prototype = {

	initialize: function() {

		this.titlePostfix = BREADCRUMB_TITLE_POSTFIX;

		this.trail = new Array();
		this.getTrailFromCookie();
	},

	addPage: function() {

		if(BREADCRUMB_MAX_ITEMS <= this.trail.length) {

			this.trail.shift();
		}

		if(this.trail.length < 1 || window.location.pathname != this.trail[this.trail.length-1].url) {

			var documentTitle = document.title.toString();

			var page = new Object();
			page['title'] = documentTitle.substring(0, documentTitle.indexOf(':'));
			page['url'] = window.location.pathname.toString();

			this.trail.push(page);

			this.writeCookie();
		}
	},

	writeCookie: function() {

		var cookieStr = 'breadcrumb=';
		for(var i = 0; i < this.trail.length; i++) {

			cookieStr += escape(this.trail[i]['url'] + '*|*' + this.trail[i]['title']) + '^|)';
		}

		cookieStr += '; path=/';

		document.cookie = cookieStr;
	},

	getTrailFromCookie: function() {

		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + 'breadcrumb' + '=([^;\\s]*)'));
		cookie = (cookie ? unescape(cookie[2]) : null);

		if(cookie) {

			var components = cookie.split('^|)');
			for(var i = 0; i < components.length; i++) {

				var pageParts = components[i].split('*|*');
				if(typeof(pageParts[0]) != 'undefined' && typeof(pageParts[1]) != 'undefined') {

					var contents = new Object();
					contents['url'] = pageParts[0];
					contents['title'] = pageParts[1].escapeHTML();

					this.trail[i] = contents;
				}
			}
		}
	},

	display: function() {

		var strCount = '';
		var list = document.createElement('ul');

		for(var i = this.trail.length-1; i >= 0; i--) {

			strCount += this.trail[i]['title'];
			if(strCount.length < BREADCRUMB_MAX_CHARS) {

				var listItem = document.createElement('li');

				var separatorString = '';
				if(i != this.trail.length-1) {

					var link = document.createElement('a');
					link.href = this.trail[i]['url'];
					link.innerHTML = this.trail[i]['title'];
					listItem.appendChild(link);
					separatorString = '<span class="separator">/</span>';
				} else {

					listItem.innerHTML = this.trail[i]['title'];
				}

				new Insertion.Top(list, '<li>' + listItem.innerHTML + separatorString + '</li>');
			}
		}

		return list;
	}
}



var URL = Class.create();
URL.prototype = {
	initialize: function() {
		this.hash = window.location.hash.slice(window.location.hash.indexOf('#') + 1).split('/');
	}
};



var Wishlist = Class.create();
Wishlist.prototype = {

	initialize: function() {

		this.wishlist = new Array();
		this.getWishlistFromCookie();
	},

	getWishlistFromCookie: function() {

		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + 'wishlist' + '=([^;\\s]*)'));
		var cookie = (cookie ? unescape(cookie[2]) : null);

		if(cookie) {

			var components = cookie.split('&');
			for(var i = 0; i < components.length; i++) {

				if(components[i].length > 0) {

					this.wishlist[i] = components[i];
				}
			}
		}
	},

	addProduct: function(productUid) {

		if(this.inWishlist(productUid)) {

			return false;
		}

		var numberItems = this.wishlist.length;
		this.wishlist[numberItems] = productUid;

		this.writeCookie();
	},

	removeProduct: function(productUid) {

		for(var i = 0; i < this.wishlist.length; i++) {

			if(this.wishlist[i] == productUid) {

				this.wishlist.splice(i, 1);
				this.writeCookie();
				return true;
			}
		}

		return false;
	},

	inWishlist: function(productUid) {

		for(var i = 0; i < this.wishlist.length; i++) {

			if(this.wishlist[i] == productUid) {

				return true;
			}
		}

		return false;
	},

	writeCookie: function() {

		var cookieStr = 'wishlist=';
		for(var i = 0; i < this.wishlist.length; i++) {

			cookieStr += escape(this.wishlist[i]) + '&';
		}

		cookieStr += '; path=/';

		document.cookie = cookieStr;
	}
}



var LanguageBar = Class.create();
LanguageBar.prototype = {
	initialize: function() {
		if (!$('language-bar')) {
			return false;
		}
				
		Event.observe('language-bar-close', 'click', this.close.bindAsEventListener(this));
		Event.observe('language-bar-map', 'mouseover', this.showRollovers.bindAsEventListener(this));
		Event.observe('language-bar-map', 'mouseout', this.hideRollovers.bindAsEventListener(this));
		Event.observe($('language-bar').down('a.language'), 'mouseover', this.showRollovers.bindAsEventListener(this));
		Event.observe($('language-bar').down('a.language'), 'mouseout', this.hideRollovers.bindAsEventListener(this));
	},
	
	close: function(e) {
		Event.stop(e);
		
		var d = new Date();
		d.setTime(d.getTime()+(30*24*60*60*1000));

		document.cookie = 'hide_languagebar=true; expires=' + d.toGMTString() + '; path=/';	
	
		new Effect.SlideUp('language-bar-wrapper', { duration: 0.3 });
	},
	
	showRollovers: function() {
		$('language-bar').down('a.language').addClassName('hover');
		$('language-bar-map').addClassName('hover');
	},
	
	hideRollovers: function() {
		$('language-bar').down('a.language').removeClassName('hover');
		$('language-bar-map').removeClassName('hover');
	}
}



var VitraOverlay = Class.create();
VitraOverlay.prototype = {
	initialize: function() {
		var overlayLinks = document.getElementsByClassName('vitra-com-overlay');
		if(overlayLinks.length > 0) {
			// Attach two DIV containers to the body - overlay and lightbox
			body = $$('body')[0];
			overlay = document.createElement('div');
			overlay.id = 'vitra-com-overlay';
			modal = document.createElement('div');
			modal.id = 'vitra-com-modal'
		
			// Create a content container
			modal_content = document.createElement('div');
			modal_content.className = 'content';
			modal.appendChild(modal_content);		
			
			body.appendChild(overlay);
			body.appendChild(modal);		
	
			document.getElementsByClassName('vitra-com-overlay').each(function(element) {
				Event.observe(element, 'click', this.showOverlay);
			}.bind(this));
		}
	},
	
	showOverlay: function(e) {			
		var myAjax = new Ajax.Request(Event.element(e).href + '?ajax=1', {
			method: 'get',
			onComplete: function(response) {		
				$$('#vitra-com-modal .content')[0].update(response.responseText);
								
				body = $$('body')[0];	
				body.addClassName("modal");	
			}
		});
		
		Event.stop(e);
	}
}


document.loaded(attachEvents);