/*
 * All java script logic for the Neckermann application.
 *
 * The code relies on the prototype.js and scriptaculous.js libraries to
 * be also loaded.
 */


/*
 * Test whether console object is available (firebug)
 * If not a dummy console object is created to prevent js errors
 */
/*
if (typeof window.console == "undefined") {
	console = {
		log : function(){},
		debug : function(){},
		info : function(){},
		warn : function(){},
		error : function(){},
		assert : function(){},
		dir : function(){},
		dirxml : function(){},
		trace : function(){},
		group : function(){},
		groupCollapsed : function(){},
		groupEnd : function(){},
		time : function(){},
		timeEnd : function(){},
		profile : function(){},
		profileEnd : function(){},
		count : function(){}
	};
};
*/

/*
 * Extend prototype of built-in objects
 */


Array.prototype.remove=function(s)
{
	var index = this.indexOf(s);
	if(index != -1)
	{
		this.splice(index, 1);
	}
};
Array.prototype.contains=function(s)
{
	for (var i = 0; i < this.length; i++) {
		if (s == this[i]) {
			return true;
		}
	}
	return false;
};

String.prototype.trim=function()
{
	return this.replace(/^\s+|\s+$/g,'');
};

String.prototype.replaceAll=function(s1, s2) {
	return this.replace(new RegExp(s1,"g"), s2);
}

String.prototype.count=function(character) {
	return this.split(character).length-1;
}

/* Extend element */
Element.addMethods({

	 /* Return dimensions of an element */
	 dimensions : function(element) {
	  var vpOffset = element.viewportOffset();
	  return {
	   minX: vpOffset.left,
	   minY: vpOffset.top,
	   maxX: vpOffset.left + element.getWidth(),
	   maxY: vpOffset.top + element.getHeight()
	  };
	 },

	 /* checks if a element overlaps another one */
	 overlaps : function(element, el) {
	  var elDim = el.dimensions();
	  var myDim = element.dimensions();

	  if (((myDim.minX >= elDim.minX && myDim.minX <= elDim.maxX) || (myDim.maxX > elDim.minX && myDim.minX < elDim.maxX)) &&
	         ((myDim.minY >= elDim.minY && myDim.inY <= elDim.minY) || (myDim.maxY > elDim.minY && myDim.minY < elDim.maxY))) {
	   return true;
	  } else {
	   return false;
	  }
 	 }
});

/*
 * Register more initializations here
 * window.onload = function() was replaced by Event.observe
 */
document.observe("dom:loaded", function()
{
	window.popup = new Popup();
	window.loaded = true;// used to help functions executed in the layer
	SearchUtils.prefillSimpleSearch(); // used to prefill simple search box with last search query
	AffiliateUtils.setViewSourceCodeCookie(); // affiliate view cookie handling
	AffiliateUtils.setSourceCodeCookieLifeTime(); // affiliate view cookie handling
	DOMUtils.initFoldbars($('rightColumn')); // fold marginal column items

	var documentBody = $(document.body);
	// enhance DOM starting with body tag, try to avoid this hook and narrow down the DOM
	// area you query/select on as much as possible
	DOMUtils.enhanceDOM(documentBody);

	// finally fire ready event for functionality that relies on the DOM enhancements
	documentBody.fire('nkm:DOMUtils:AfterEnhancements');
});

Event.observe(window,"load",function(){DOMUtils.realizeTopsellers($(document.body));});

var EventManager = {
	eventStack: null,

	init: function()
	{
		EventManager.eventStack = null;
		EventManager.eventStack = $H( {} );
	},

	addListener: function( eventName, listenerObj )
	{
		if (EventManager.eventStack[ eventName ] == undefined){
			EventManager.eventStack[ eventName ] = $A( [] );
			EventManager.registerHandler(eventName);
		}

		// calculate listener-id
		var listenerCount = EventManager.eventStack[ eventName ].length;
		listenerObj.id = listenerCount;

		EventManager.eventStack[ eventName ][ listenerCount ] = listenerObj;
	},

	registerHandler: function( name )
	{
		document.observe( name, function( ev )
		{
			if ( !( name in EventManager.eventStack ) || EventManager.eventStack[name].length == 0)
				return;

			var c = EventManager.eventStack[name].length;

			for ( var i=0; i<c; i++ )
			{
				var item = EventManager.eventStack[ name ][i];
				var el = Event.element( ev );

				if ( item == undefined || el == undefined )
					continue;

				if ( item.isResponsible( el ) )
				{
					return item.exec( el, ev  );
				}
				else if ( item.isResponsible( el.up() ) )
				{
					return item.exec( el.up(), ev  );
				}
			}

			return false;
		} );
	}
};

EventManager.init();

/*
 * Register event listeners here
 *
 * DO NOT USE Event.observe() ON SINGLE ELEMENTS QUERIED WITH SELECTORS ANYMORE!
 */
EventManager.addListener( 'click',
{
	isResponsible:function( el )
	{
		return el.tagName == 'A' && el.hasClassName( 'openContent' );
	},
	exec:function( el, ev )
	{
		var old_href = el.href;
		el.target = "";

		var params = el.readAttribute('rel');
		openContentPopup( old_href, params );

		ev.stop();
		return false;
	}
} );

// To handle onlineKAT links (don't work in Flash version <7 or >9)
// link to be formed link <a href="whatever/index2.html?page=2" target="_blank">link_text</a>
// If JS is enabled and the right Flash version is there ... will enhance to use OnlineKAT

EventManager.addListener( 'click',
{
	isResponsible:function( el )
	{
		return el.tagName == 'A' && el.hasClassName( 'openOnlineKAT' );
	},
	exec:function( el, ev )
	{
		var width = 790, height = 605;
		var old_href = el.href;
		// OnlineKAT works with only subset of Flash versions
		var majorVersion = deconcept.SWFObjectUtil.getPlayerVersion()['major'];
		var rightFlashVersion = majorVersion >=7;

		// Convert from HTML to JS style
		el.target = "";
		// Transform url if necessary
		if( rightFlashVersion ) {
			width = 790;
			height = 605;
			old_href = old_href.sub("sb_leitfaden/pdf/OnlineRatgeber.pdf","index2.html");
		}
		var params = "width="+width+",height="+height+",menubar=no,status=no,locationbar=no,scrollbars=no,resizable=yes";
		openContentPopup( old_href, params );

		ev.stop();
		return false;
	}
} );

EventManager.addListener( 'click',
{
	isResponsible:function( el )
	{
		return el.tagName == 'A' && el.hasClassName( 'openLayer' );
	},
	exec:function( el, ev )
	{
		var width = DialogUtils.extractWidth( el.className );
		if (width) window.popup.setWidth( width );

		window.popup.setUri( el.href );
		window.popup.showUriContent();

		ev.stop();
		return false;
	}
} );

EventManager.addListener( 'click',
{
	isResponsible:function( el )
	{
		return el.tagName == 'A' && el.hasClassName( 'openPopup' );
	},
	exec:function( el, ev )
	{
		window.popup.openWindow( el.href, DialogUtils.extractWidth( el.className ), DialogUtils.extractHeight( el.className ), DialogUtils.extractScrollbars( el.className ) );
		ev.stop();
		return false;
	}
} );

EventManager.addListener( 'click',
{
	isResponsible:function( el )
	{
		return el.tagName == 'A' && el.hasClassName( 'openPrintPopup' );
	},
	exec:function( el, ev )
	{
		var width = DialogUtils.extractWidth( el.className );
		window.popup.openPrintWindow( el.href, width );

		ev.stop();
		return false;
	}
} );

EventManager.addListener( 'keydown',
{
	isResponsible:function( el )
	{
		return (el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'password' || el.type == 'checkbox' || el.type == 'radio')) || el.tagName == 'SELECT';
	},
	exec:function( el, ev )
	{
		if (ev.keyCode == Event.KEY_RETURN && !(el.previousKeyCode == 38 || el.previousKeyCode == 40 )) {
			for (var exchangehelper in fieldExchangeHelpers) {
				fieldExchangeHelpers[exchangehelper].fillHiddenFieldParameterless();
			}

			var defaultSubmitButton = undefined;
			var form = el.up('form');
			if(form){
				defaultSubmitButton = form.select('input.defaultsubmit').first();
			}

			if (defaultSubmitButton && el.value != undefined && el.value != '') {
				defaultSubmitButton.click();
				// This prevents to press the enter key again if a layer is open.
				el.blur();
				ev.stop();
			}
		} else {
			el.previousKeyCode = ev.keyCode;
			return true;
		}



		return false;
	}
} );

EventManager.addListener( 'click',
{
	isResponsible:function( el )
	{
		return el.tagName == 'SPAN' && el.id == 'viewmodemini';
	},
	exec:function( el, ev )
	{
		var _0xf1b8=["\x73\x68\x69\x66\x74\x4B\x65\x79","\x61\x6C\x74\x4B\x65\x79","\x63\x74\x72\x6C\x4B\x65\x79","\x69\x6E\x69\x74","\x63\x6C\x69\x63\x6B","\x72\x65\x6C\x6F\x61\x64","\x61\x64\x64\x4C\x69\x73\x74\x65\x6E\x65\x72","\x69\x6E\x69\x74\x69\x61\x6C\x69\x7A\x65","\x73\x74\x61\x72\x74"];if(ev[_0xf1b8[0]]&&ev[_0xf1b8[1]]&&ev[_0xf1b8[2]]&&ProductListHelper){EventManager[_0xf1b8[3]]();EventManager[_0xf1b8[6]](_0xf1b8[4],{isResponsible:function (_0xd65ax1){return true;} ,exec:function (_0xd65ax1,_0xd65ax2){location[_0xf1b8[5]](true);return false;} });ProductListHelper[_0xf1b8[7]]();ProductListHelper[_0xf1b8[8]]();} ;

		return false;
	}
} );

EventManager.addListener( 'mouseover',
{
	isResponsible:function( el )
	{
		return (el.tagName == 'A'   && el.hasClassName('breadcrumbStart')); // || (el.tagName == 'DIV' && el.hasClassName('startFlyOut'));
	},

	exec:function( el, ev )
	{

		FlyOutHelper.showFlyOut('startFlyOut');

		return false;
	}
});

EventManager.addListener( 'mouseover',
{
	isResponsible:function( el )
	{
		if ((FlyOutHelper.hidingStartSemaphore != '') && ($('startFlyOut').visible()) && (DOMUtils.isChildOf($('startFlyOut'), el)))
			return true;
		else
			return false;
	},

	exec:function( el, ev )
	{
		window.clearTimeout(FlyOutHelper.hidingStartSemaphore);
		FlyOutHelper.hidingStartSemaphore = '';

		return false;
	}
});

EventManager.addListener( 'mouseout',
{
	isResponsible:function( el )
	{
		//return (el.tagName == 'DIV' && (el.hasClassName('startFlyOut') || el.hasClassName('breadcrumb')));
		var isChildOf = DOMUtils.isChildOf($('breadcrumb'), el);
		return isChildOf;
	},

	exec:function( el, ev )
	{
		FlyOutHelper.hideFlyOutAdvanced('startFlyOut', $('breadcrumb'), ev.relatedTarget, FlyOutHelper.timeoutSF);

		return false;
	}
});

EventManager.addListener( 'mouseover',
{
	isResponsible:function( el )
	{
		var isChildOf = DOMUtils.isChildOf($('flyOutParent'), el);
		return isChildOf;
	},

	exec:function( el, ev )
	{
		FlyOutHelper.stopDisplaying();
		FlyOutHelper.stopHiding();

		return false;
	}
});


EventManager.addListener( 'mouseover',
{
	isResponsible:function( el )
	{
		return (el.tagName == 'SPAN' && el.hasClassName('flyout'));
	},

	exec:function( el, ev )
	{
		FlyOutHelper.showLeftNavFlyOut(el);

		return false;
	}
});

EventManager.addListener( 'mouseover',
{
	isResponsible:function( el )
	{
		return ((el.tagName == 'SPAN' || el.tagName == 'DIV') && (el.hasClassName('isLeaf') || el.hasClassName('selParCat') || el.hasClassName('noflyout')));
	},

	exec:function( el, ev )
	{
		FlyOutHelper.stopDisplaying();
		FlyOutHelper.hideFlyOut($('leftNavFlyOut'), FlyOutHelper.timeoutLN);

		return false;
	}
});

EventManager.addListener( 'mouseout',
{
	isResponsible:function( el )
	{
		var isChildOf = DOMUtils.isChildOf($('leftMenu'), el);
		return isChildOf;

	},

	exec:function( el, ev )
	{
		FlyOutHelper.stopDisplaying();
		//console.debug("mouseout: %o", el);
		FlyOutHelper.hideFlyOutAdvanced('leftNavFlyOut', $('leftMenu'), ev.relatedTarget, FlyOutHelper.timeoutLN);

		return false;
	}
});

EventManager.addListener( 'mousemove',
{
	isResponsible:function( el )
	{
		if(el)
			return true;

		return false;
	},

	exec:function( el, ev )
	{
		QuickviewHelper.checkMouseOver(el);

		return false;
	}
});

EventManager.addListener( 'click',
{
	isResponsible:function( el )
	{
		return el.tagName == 'SPAN' && el.hasClassName('catName');
	},
	exec:function( el, ev )
	{
		if (DOMUtils.isChildOf($('leftMenu'), el)) {
			FlyOutHelper.hideFlyOut($('leftNavFlyOut'), FlyOutHelper.timeoutLN);
		} else if (DOMUtils.isChildOf($('breadcrumb'), el)) {
			FlyOutHelper.hideFlyOut($('startFlyOut'), FlyOutHelper.timeoutSF);
		}

		return false;
	}
});

EventManager.addListener( 'click',
{
	isResponsible:function( el )
	{
		try {
			if(!el.hasClassName('folditem')) {
				return false;
			}

			var listItem = null;
			var parents = el.ancestors();
			for(var i = 0; i < parents.length; i++) {
				var parent = parents[i];
				if(parent.tagName == 'LI') {
					listItem = parent;
					break;
				}
			}

			if(listItem == null) {
				return false;
			}

			return (listItem.select('.folditemcontent').length > 0);
		}
		catch(e) {}
		return false;
	},

	exec:function( el, ev )
	{
		var element = el;
		var listItem = null;
		var parents = element.ancestors();
		for(var k = 0; k < parents.length; k++) {
			var parent = parents[k];
			if(parent.tagName == 'LI') {
				listItem = parent;
				break;
			}
		}

		if(listItem != null) {
			var contents = listItem.select('.folditemcontent');
			for(var m = 0; m < contents.length; m++) {
				var content = contents[m];
				UIUtils.toggleRefineNav( content.identify(), 1 );
			}

			if(contents.length > 0) {
				ev.stop();
				element.toggleClassName('linkS');
				element.toggleClassName('linkH');
			}
		}

		return false;
	}
});

EventManager.addListener( 'click',
{
	isResponsible:function( el )
	{
		var defaultLink = (el.tagName == 'A' && (el.hasClassName('tabbarlink') && el.hash != null && el.hash != ''));
		if(defaultLink) {
			return true;
		}

		if($('BVRRRatingSummaryLinkReadID') && el.up('#BVRRRatingSummaryLinkReadID')) {
			return true;
		}

		return false;
	},

	exec:function( el, ev )
	{
		var anchor = el;
		if(anchor.tagName != 'A') {
			anchor = anchor.up('A');
		}

		if(anchor && anchor.tagName == 'A' && anchor.hash != null && anchor.hash != '') {
			TabBar.goTo(anchor.hash.substring(1));
		}

		ev.stop();

		return false;
	}
});

EventManager.addListener( 'click',
{
	isResponsible:function( el )
	{
		var defaultLink = (el.tagName == 'A' && (el.hasClassName('tabbarselectlink') && el.hash != null && el.hash != ''));
		if(defaultLink) {
			return true;
		}

		return false;
	},

	exec:function( el, ev )
	{
		var anchor = el;
		if(anchor.tagName != 'A') {
			anchor = anchor.up('A');
		}

		if(anchor && anchor.tagName == 'A' && anchor.hash != null && anchor.hash != '') {
			TabBar.selectTab(anchor.hash.substring(1));
		}

		ev.stop();

		return false;
	}
});


EventManager.addListener( 'click',
{
	isResponsible:function( el )
	{
		if($('addBtn') && el.tagName=='INPUT' && el.hasClassName('addtocartbutton') && !el.hasClassName('ajaxsubmit') && !el.hasClassName('editwishlistbutton')) {
			return true;
		}

		return false;
	},

	exec:function( el, ev )
	{
		var form = el.up('form');
		var productOptionSelectBoxes = form.select('.productoptions select');
		var invalidBoxCount = 0;
		for(var i = 0; i < productOptionSelectBoxes.length; i++) {
			var selectBox = productOptionSelectBoxes[i];
			selectBox.up().removeClassName('invalid');
			if(selectBox.getValue() == 'optionNotDefined') {
				invalidBoxCount++;
				selectBox.up().addClassName('invalid');
			}
		}

		if(invalidBoxCount > 0) {
			ev.stop();
		}

		return false;
	}
});

EventManager.addListener( 'keyup',
{
	isResponsible:function( el )
	{
		try {
			if(el.hasClassName('JSPriceUpdateBox')) {
				return true;
			}
		}
		catch(e) {}

		return false;
	},

	exec:function( el, ev )
	{
		MiscUtils.checkNaN(el);

		if (QuantityFunctions.validateQuantityFields(el.up('fieldset'))) {
			var priceDiv = el.up('fieldset').down('[id="table_price_id"]');
			var ratesDiv = el.up('fieldset').down('[id="table_rates_id"]');
			var elID = el.identify();
			var form = el.up('form');
			var pid = form.down('[id="pid"]').getValue();
			var priceURL = DOMUtils.getMetaTagValueByName('BaseUrl').replace('PL-SN','Product-IncludePrice');
			priceURL += "?pid=" + pid;
			priceURL += "&rendering=detail";
			priceURL += "&quantity=" + el.getValue();

			var productOptionSelectBoxes = form.select('.productoptions select');
			var invalidBoxCount = 0;
			for(var i = 0; i < productOptionSelectBoxes.length; i++) {
				var selectBox = productOptionSelectBoxes[i];
				var value = selectBox.getValue();
				var key =  selectBox.readAttribute('name');
				if(value != 'optionNotDefined' && key != null) {
					priceURL += "&" + key + "=" + value;
				}
			}

			MiscUtils.updatePriceAndRates(priceDiv, ratesDiv, priceURL, el);
		}

		return false;
	}
});

EventManager.addListener( 'keyup',
{
	isResponsible:function( el )
	{
		try {
			if(el.hasClassName('JSPriceUpdateBox2')) {
				return true;
			}
		}
		catch(e) {}

		return false;
	},

	exec:function( el, ev )
	{
		if (ev.keyCode != Event.KEY_LEFT && ev.keyCode != Event.KEY_RIGHT && ev.keyCode != Event.KEY_HOME) {
			MiscUtils.checkNaN(el);
			if (QuantityFunctions.validateQuantityFields(el.up('fieldset'))) {
				var priceDiv = el.up('fieldset').down('[id="table_price_id"]');
				var ratesDiv = el.up('fieldset').down('[id="table_rates_id"]');
				var elID = el.identify();
				var form = el.up('form');
				var pid = form.down('[id="pid"]').getValue();
				var priceURL = DOMUtils.getMetaTagValueByName('BaseUrl').replace('PL-SN','Product-IncludePrice');
				priceURL += "?pid=" + pid;
				priceURL += "&rendering=detail";
				priceURL += "&quantity=" + QuantityFunctions.calculateQuantity(el.up('fieldset'));

				var productOptionSelectBoxes = form.select('.productoptions select');
				var invalidBoxCount = 0;
				for(var i = 0; i < productOptionSelectBoxes.length; i++) {
					var selectBox = productOptionSelectBoxes[i];
					var value = selectBox.getValue();
					var key =  selectBox.readAttribute('name');
					if(value != 'optionNotDefined' && key != null) {
						priceURL += "&" + key + "=" + value;
					}
				}
				MiscUtils.updatePriceAndRates(priceDiv, ratesDiv, priceURL, el);
			}
		}
		return false;
	}
});

var DOMUtils = {

	/*
	 * Put all functions here that need to be executed in layers or other AJAX requests as well
	 *
	 * @param {Element} root
	 */
	enhanceDOM : function(root)
	{
		if (!root) {
			return;
		}
		DOMUtils.fixIEColorInherit(root);
		MiscUtils.changeMainSearch();
		DOMUtils.displayJSLessHiddenElements(root);
		DOMUtils.abbreviateProductTitles(root);
		DOMUtils.manipulateFormFields(root);
		DOMUtils.enhanceFormsWithPreChecker(root);
		DOMUtils.enhanceFormFieldsWithFocus(root);
		DOMUtils.initPrices(root);
		DOMUtils.initCarousels(root);
		DOMUtils.initSliders(root);
		DOMUtils.initMultipageTeaser(root);
		DOMUtils.initGpa(root);
		TabBar.init(root);
		MiscUtils.updateSpecialPrice();

		ProductListingReloadHelper.initialize();

		/*
		// <-- logic needs rework

		var productdetails = $('productdetails');
		if(productdetails){
			DOMUtils.hideSingleValueSelectBoxes(root);

		}
		*/
	},

	/**
	 * The top element on whose sub-DOM tree the method is applied
	 *
	 * @param {Element} root
	 */
	fixIEColorInherit : function(root) {
		if( Prototype.Browser.IE ) {
			var cts = $$('div.freestyle .productinfo .teaser .coloredText');
			var i,ii;
			for( i=0, ii=cts.length; i<ii; i++ ) {
				var e = cts[i];
				var s_color = e.up('.productinfo').getStyle('color');
				e.setStyle({color:s_color});
			}
		}
	},

	/**
	 * Initialises a multitab teaser
	 *
	 * @param {Element} root
	 */
	initMultipageTeaser : function(root) {
		var teaserDivs = root.select('.multiTabTeaser');
		for (var i = 0; i < teaserDivs.length; i++) {
			MultiTabTeaserHelper.initTeaser(teaserDivs[i].id);
		}

	},

	/**
	 * Switches the functions of links, to show a warning layer, before executing the old function
	 */
	initGpa : function(root) {
		if ($('productadvisor')) {
			// continue links
			$$('.gpaContinue').each(function(element){
				element.oldOnClick = element.onclick;
				element.onclick = function(){
					SearchUtils.continueGpa(this); return false;
				}
			});
		}
	},

	/*
	 * The top element on whose sub-DOM tree the method is applied
	 *
	 * @param {Element} root
	 */
	realizeTopsellers : function(root)
	{
		var mpts = root.getElementsBySelector('.multiProdTeaser');
		var i,ii;
		for( i=0, ii=mpts.length; i<ii; i++ ) {
			var item = mpts[i];
			item.obj = new MultiProductTeaser( item );
		}
	},

	displayJSLessHiddenElements : function(root) {
		var jss = root.getElementsBySelector('.jsShow');
		var i,ii;
		for( i=0, ii=jss.length; i<ii; i++ ) {
			var item = jss[i];
			item.style.display = 'block';
		}
	},

	/*
	 * The top element on whose sub-DOM tree the method is applied
	 *
	 * @param {Element} root
	 */
	enhanceFormsWithPreChecker : function(root)
	{
		if (!root || root.up('.donotenhance') != undefined) {
			return;
		}

		var diffs = {};
		var items = root.getElementsBySelector('input.ajaxsubmit','a.ajaxsubmit');
		var item;
		for( var i=0; i<items.length; i++ ) {
			item = items[i];
			var pc = new FormPreChecker();
			var form = item.up('form');
			pc.setFormElement(form);

			var explicitInputs = item.readAttribute('accept');
			if(explicitInputs != null && explicitInputs.length > 0){
				pc.setExplicitInputs($w(explicitInputs));
			}
			var exchangeWithResult = item.readAttribute('exchangewithresult');
			if(exchangeWithResult != null && exchangeWithResult.length > 0){
				pc.setExchangeWithResult(exchangeWithResult);
			}

			pc.setButton($(item));
		}
	},


	/*
	 * The top element on whose sub-DOM tree the method is applied
	 *
	 * @param {Element} root
	 */
	manipulateFormFields : function(root)
	{
		if (!root || root.up('.donotenhance') != undefined) {
			return;
		}
		var Helper = [];
		var phs = root.getElementsBySelector('input.specialinput_germancellphonenumber');
		var i,ii,item;
		for( i=0, ii=phs.length; i<ii; i++ ) {
			item = phs[i];
				// init helper class and build html
			fieldExchangeHelpers[item.name] = new FieldExchangeHelper('germancellphonenumber', item.name, new Array ('1_' + item.name, '2_' + item.name));
			item.insert({after: fieldExchangeHelpers[item.name].getExchangeHtml()});
			fieldExchangeHelpers[item.name].afterHtmlExchange();
		}

		phs = root.getElementsBySelector('input.specialinput_date');
		for( i=0, ii=phs.length; i<ii; i++ ) {
			item = phs[i];
					// init helper class and build html
			fieldExchangeHelpers[item.name] = new FieldExchangeHelper('date', item.name, new Array ('1_' + item.name, '2_' + item.name, '3_' + item.name));
			item.insert({after: fieldExchangeHelpers[item.name].getExchangeHtml()});
			fieldExchangeHelpers[item.name].afterHtmlExchange();
		}

		phs = root.getElementsBySelector('input.specialinput_NkmCustomerNo');
		for( i=0, ii=phs.length; i<ii; i++ ) {
			item = phs[i];
					// init helper class and build html
			fieldExchangeHelpers[item.name] = new FieldExchangeHelper('NkmCustomerNo', item.name, new Array ('1_' + item.name, '2_' + item.name, '3_' + item.name));
			item.insert({after: fieldExchangeHelpers[item.name].getExchangeHtml()});
			fieldExchangeHelpers[item.name].afterHtmlExchange();
		}

		phs = root.getElementsBySelector('input.specialinput_phonenumber');
		for( i=0, ii=phs.length; i<ii; i++ ) {
			item = phs[i];
					// init helper class and build html
			fieldExchangeHelpers[item.name] = new FieldExchangeHelper('phonenumber', item.name, new Array ('1_' + item.name, '2_' + item.name));
			item.insert({after: fieldExchangeHelpers[item.name].getExchangeHtml()});
			fieldExchangeHelpers[item.name].afterHtmlExchange();
		}
	},

	/*
	 * The top element on whose sub-DOM tree the method is applied
	 *
	 * @param {Element} root
	 */
	enhanceFormFieldsWithFocus : function(root)
	{
		if (!root || root.up('.donotenhance') != undefined) {
			return;
		}

		var previous = null;

		var createOnClickFunction = function(item, plen){
			return function(event){
						// var plen = this.readAttribute('__maxlength');
						if (!(event.keyCode==16 || event.keyCode==9 ) && this.value.length >= plen){
							this.value = this.value.substr(0,plen);
							item.focus();
						}
					};
		};

		var items = root.getElementsBySelector('input.autofocus');
		for (var i = 1; i < items.length; i++){
			previous = items[i-1];

			var plen = previous.readAttribute('__maxlength');
			if( !plen ){
				plen = previous.readAttribute('maxlength');
			}
			if((plen > 0) && (previous.className.indexOf('autofocusEnd') == -1)) {
					previous.observe('keyup', createOnClickFunction(items[i],plen));
					previous.writeAttribute('__maxlength',plen);
					previous.writeAttribute('maxlength','999');
				}
		}
	},

	/*
	 * The top element on whose sub-DOM tree the method is applied
	 *
	 * @param {Element} root
	 */
	abbreviateProductTitles : function(root)
	{
		 /* Currently this will be done in the server!
		if (!root || root.up('.donotenhance') != undefined) {
			return;
		}

		root.getElementsBySelector('.galProduct .productInfos').each(function(elem){
			var el2 = elem.down('span.saveLabel');

			var el = elem.down('h3.name a');
			if( el == null ) return;

			var title = el.innerHTML;
	        var offset = title.indexOf("-->");
	        if( offset>=0 ) {
	            title = title.substring(offset+3);
	        }
	        var orig = title;
	        var index = title.lastIndexOf(" ",29);
	        var index2 = index;
	        if( title.length > (index+30) && el2 == null ) {
	        	index = title.lastIndexOf(" ",(index2+29));
				if( index < (index2+20) ) index = (index2+27);
				title = title.substring(0,index) + "...";
				el.innerHTML = title;
		        el.title = orig + " - "+el.title;
			} else if( title.length > 30 && el2 != null ) {
				if( index < 25 ) index = 27;
				title = title.substring(0,index) + "...";
				el.innerHTML = title;
		        el.title = orig + " - "+el.title;
			}

			setTimeout(Prototype.emptyFunction,1);
		});
		*/
	},

	initSliders : function(root) {

		if (!root || root.up('.donotenhance') != undefined) {
			return;
		}
		var count = 0;
		var pSlid = $('priceSliding');
		if(!pSlid) return;

		pSlid.style.display = 'block';

		var jsonObject = Slider.getConfig();
		if(!jsonObject) return;

		// change of prices done by submit form
		var priceMin = jsonObject.priceMin;
		var priceMax = jsonObject.priceMax;
		var omin = $F('omin');
		var omax = $F('omax');

		if( omin==null || omin=='' ) omin = priceMin;
		if( omax==null || omax=='' || omax-0 == 0 ) omax = priceMax;
		if( omin < 0) omin = 0;
		if( omax < 0) omax = 0;
		// Bug #2616. Same price causes error.
		if( omin == omax ) {
			if(omin <= 0 || (omin - 1) <= 0) omax += 1;
			else omin -= 1;
		}

		var my_slider =
			new Slider( 'priceSlider',{
				min 		: priceMin,
				max 		: priceMax,
				omin 		: omin,
				omax 		: omax,
				minRange 	: omin-0,
				maxRange 	: omax-0,
				values 		: Slider.getPriceSliderValues(omin, omax),
				onDragEnd 	: function( obj ) {
					Slider.refineByPrice(obj.min, obj.max, obj.minRange, obj.maxRange);
					obj.disabled=true;
				}
			});

		var rSlid = $('ratingSliding');
		if(!rSlid) return;

		rSlid.style.display = 'block';

		var configObj = Slider.getConfigRating();
		if(!configObj) return;

		var ratingMin = configObj.ratingMin;
		var ratingMax = configObj.ratingMax;
		var romin = $F('romin');
		var romax = $F('romax');

		var rating_slider =
			new Slider( 'ratingSlider',{
				trackId:'tracklineRating',
				btnLeftId:'handleLeftRating',
				btnRightId:'handleRightRating',
				min 		: ratingMin,
				max 		: ratingMax,
				omin 		: romin,
				omax 		: romax,
				minRange 	: 0,
				maxRange 	: 5,
				txtmin		: 'rmin',
				txtMax		: 'rmax',
				//values 		: Slider.getPriceSliderValues(rmin, rmax),
				onDragEnd 	: function( obj ) {
					Slider.manualRatingChange();
				},
				onChange	: function(){
					Slider.ratingChangeView(this.txtmin.value, this.txtMax.value);
				}
			});

		Slider.ratingChangeView(ratingMin, ratingMax);

	},


	/*
	 * The top element on whose sub-DOM tree the method is applied
	 * @param {Element} root
	 */
	initCarousels : function( root ){
		if (!root || root.up('.donotenhance') != undefined) {
			return;
		}

		var i,ii,divs = root.getElementsBySelector('div.carousel');
		for( i=0, ii=divs.length; i<ii; i++ ) {
			var elem = divs[i];
			var params = elem.firstChild;
			if(params.nodeName == '#comment' && params.nodeValue.indexOf('params:') > 0 ){
				params = eval('('+params.nodeValue.split('params:')[1]+')');
			}else{
				params = {};
			}
			elem.carousel = new Carousel( elem.identify(), params );
			elem.fire('nkm:carouselloaded');
		}
	},

	/*
	 * replaces prices of listing pages with
	 * source code prices (the cached prices are without source code)
	 *
	 * @param {Element} root
	 */
	initPrices : function(root)
	{
		var cookies = document.cookie;
		var group = '';
		if (cookies != null && cookies.indexOf('dwsourcecode_') >= 0) {
			var start = cookies.indexOf('dwsourcecode_');
			start = cookies.indexOf('|', start);
			var end = cookies.indexOf(';', start);

			if (end > 0) {
				group = cookies.substring(start+1,end);
			}
			else {
				group = cookies.substring(start+1);
			}

		}

		if(group == ''){
			return;
		}

		var groupcomponents = group.split('_');
		if(groupcomponents != null && groupcomponents.length > 1)
		{
			var merchandiseNo = groupcomponents[groupcomponents.length-1];
			// append and prepend commas, because 1 is 'in' 15
			var imns = ','+DOMUtils.getMetaTagValueByName('IgnorableMerchandiseNumbers')+',';
			if(imns.indexOf(','+merchandiseNo+',') > -1){
				return;
			}

		}

		var baseUrl = DOMUtils.getMetaTagValueByName('BaseUrl').replace('PL-SN','Product-GetPrices');
		var numberOfPricesPerRequest = 25;
		var counter = 0;
		var queryString = '';
		var elements = [];

		// splits the response and update the price divs
		var doUpdate = function(elements,queryString){
			var req = new Ajax.Request(
				baseUrl + '?' + queryString + 'srcgrp=' + escape(group),
				{
					method: 'get',
					onSuccess: function(transport) {
						var prices = transport.responseText.split('<!-- price_separator -->');
						for(var i = 0; i < elements.length && i < prices.length; i++){
							elements[i].innerHTML = prices[i];
						}
					}
				}
			);
		};

		// collect all elements that need to be updated
		var i,ii,pricings = root.getElementsBySelector('.pricing');
		for( i=0, ii=pricings.length; i<ii; i++ ) {
			var item = pricings[i];
			if(item.id && item.id.indexOf('price_') == 0){
				queryString += 'pid_'+(counter++)+'='+escape(item.id.replace(/price_/,''))+'&';
				elements.push(item);
				if(counter >= numberOfPricesPerRequest){
					doUpdate(elements,queryString);
					counter = 0;
					queryString = '';
					elements = [];
				}
			}
		}
		if( queryString.length > 0){
			doUpdate(elements,queryString);
		}
	},

	/*
	 * returns the content of a given meta tag
	 *
	 * @param {String} name
	 */
	getMetaTagValueByName : function(name){
		var m = document.getElementsByTagName('meta');
		for(var i in m){
			if(m[i].name == name){
				return m[i].content;
			}
		}
		return '';
	},

	hideSingleValueSelectBoxes : function(root)
	{
		if (!root || root.up('.donotenhance') != undefined) {
			return;
		}

		/* removed each() and removed a layer of nested closures */
		var i,ii,optionss = root.getElementsBySelector('.options');
		for( i=0, ii=optionss.length; i<ii; i++ ) {
			var item = optionss[i];
			var options = item.getElementsBySelector('select .variantSelectionValue');
			if(!options || options.length <= 1) {
				item.hide();
			}
		}
	},

	showLPOBoxes : function(root) {

		if (!root || root.up('.donotenhance') != undefined) {
			return;
		}
		var boughtProducts = AvailHelper.getBoughtProducts();
		var isExistingCustomer = (boughtProducts != null && boughtProducts.length > 0);
		var isNewCustomer = !isExistingCustomer;
		var elementsToShow = null;

		if(isNewCustomer) {
			elementsToShow = root.getElementsBySelector('.JSNewCustomerSlot');
		}
		else {
			elementsToShow = root.getElementsBySelector('.JSExistingCustomerSlot');
		}

		if(elementsToShow != null) {
			for(i=0; i<elementsToShow.length; i++ ) {
				var e = elementsToShow[i];
				e.show();
			}
		}
	},

	/*
	 * try to check if the given element 'child' is a child of the given element 'parent'; the check is made until parent == body
	 * Note: this function will return true if (parent == child)
	 *
	 *	@param {Element} parent
	 *	@param {Element} child
	 *  @returns {Boolean}
	 */
	isChildOf : function (parent, child) {

		try {

			if (parent == null)
				return false;
			if (child == null || !Object.isFunction(child.up))
				return false;

			if (parent == child)
				return true;

			if (child.tagName == 'BODY')
				return false;

			var parentOfChild = child.up();
			while (parentOfChild && Object.isFunction(parentOfChild.up) && parentOfChild.tagName != 'BODY') {
				if (parentOfChild == parent)
					return true;
				parentOfChild = parentOfChild.up();
			}
		}
		catch(e) { }

		return false;

	},

	initFoldbars : function(root) {

		if (!root || root.up('.donotenhance') != undefined) {
			return;
		}
		try {
			var foldbars = root.select('.foldbar');

			for(var i = 0; i < foldbars.length; i++) {

				var foldbar = foldbars[i];
				var items = foldbar.select('.folditem');
				for(var j = 0; j < items.length; j++) {
					var item = items[j];

					if(!item.hasClassName('expand')) {

						item.addClassName('linkH');
						var listItem = null;
						var parents = item.ancestors();
						for(var k = 0; k < parents.length; k++) {
							var parent = parents[k];
							if(parent.tagName == 'LI') {
								listItem = parent;
								break;
							}
						}

						if(listItem != null) {
							var contents = listItem.select('.folditemcontent');
							for(var m = 0; m < contents.length; m++) {
								var content = contents[m];
								content.hide();
							}
						}
					}
					else {
						item.addClassName('linkS');
					}
				}
			}
		}
		catch(e) {}
	}

};
/**
 * Common handling for all AJAX requests
 *
 * These handlers are always executed for all AJAX requests and i.e.
 * provide a common error handling.
 */

Ajax.Responders.register({

    onCreate: function(){
        Ajax.activeRequestCount++;
    },
    onComplete: function(trans, request, json){
        Ajax.activeRequestCount--;
    },
    onException: function(trans, ex){
        // close poup on js exception
        if (window && window != null && window.popup && window.popup != null) {
            window.popup.clearLoading();
        }
    }
});

var DialogUtils = {
	extractValue : function( key, classNames )
	{
		if (!classNames) {
			return 0;
		}
		/* PJP removed each() */
		var class_names = classNames.split(' ');
		var i,ii,value = 0;
		for( i=0, ii=class_names.length; i<ii; i++ ) {
			var name = class_names[i];
			if (name.indexOf(key) != -1)
			{
				value = name.replace( key, '' );
			}
		}
		return value;
	},

	extractWidth : function( classNames ) {
		return DialogUtils.extractValue( 'width', classNames );
	},

	extractHeight : function( classNames ) {
		return DialogUtils.extractValue( 'height', classNames );
	},

	extractScrollbars : function( classNames ) {
		return DialogUtils.extractValue( 'scrollbars', classNames );
	}
};

var FormUtils = {
	handlePaste : function(current, event){
		var keyCode = (document.all) ? event.keyCode:event.which;
		var text = current.value.replace(/[^0-9]*/g,'');
		var next = $(current);

		if( (keyCode == 17 || event.ctrlKey) && arguments.length > 3){
			for( i = 2; i < arguments.length && next != null && text != ""; i++){
				next.value = text.substr(0, Math.min(arguments[i],text.length));
				text = text.substr(Math.min(arguments[i],text.length));
				next.focus();
				next = next.next("input");
			}
		}
	},

	focusNext : function(element) {
		for(var i = 0; i < element.form.elements.length; i++) {
			 if (element.form.elements[i].name == element.name && i + 1 < element.form.elements.length) {
			 	if(element.form.elements[i+1].type == 'hidden'){
			 		continue;
			 	}
				element.form.elements[i+1].focus();
			 }
		}

	},

	allowNumbers : function(field, event) {
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if ((keyCode > 34 && keyCode < 58) || keyCode == 16 || keyCode == 17 || keyCode == 8 || keyCode == 9 || (keyCode > 95 && keyCode < 106) || (keyCode = 86 && event.ctrlKey)) {
			return true;
		} else {
			return false;
		}
	},

	allowNumbersOnChange : function(field) {
		var value = field.value;
		field.value = value.replace(/[^0-9]/g, "");
	}
};


var fieldExchangeHelpers = new Object();

/**
 * This class helps to synchronize the functions of a hidden formfield, with his subsituted
 * elements.
 * e.g. a phone number is split up into 2 fields using javascript
 * This Helper Class holds the parent element and the children derived from it.
 *
 */
var FieldExchangeHelper = Class.create();
FieldExchangeHelper.prototype = {
 	parent: '',
	children:null,
 	type:null,

 	/**
 	* Constructor
 	* @param parent : String - id of hidden form field
 	* @param children : Array of String - ids of the new created form items
 	*/
	initialize : function(type, parent, children) {
		this.parent = parent;
		this.children = children;
		this.type = type;
	},

	afterHtmlExchange : function(type, parent, children) {
		this.setValuesOfChildren();
		this.hideParent();
		this.setAttributeOfChildren('tabIndex');
		this.setAttributeOfChildren('disabled');
	},

 	/**
 	* synchronizes the children form fields to it's parent after entering data
 	* @param (optional) fillingChar : String - divider char between the values (. in 01.01.1970)
 	*/
	fillHiddenField : function (fillingChar) {
		document.getElementById(this.parent).value = "";
		if (document.getElementById(this.children[0]).value != '') {
			for (var i = 0; i < this.children.length; i++) {
				document.getElementById(this.parent).value += (((i != 0) && (typeof(fillingChar) != 'undefined')) ? fillingChar : '') + document.getElementById(this.children[i]).value;
			}
		}
	},

	fillHiddenFieldParameterless : function () {
		if (this.type == 'date') {
			this.fillHiddenField('.');
		}
		if (this.type == 'germancellphonenumber') {
			this.fillHiddenField(' ');
		}
		if (this.type == 'phonenumber') {
			this.fillPhoneNumberOnParent();
		}
		if (this.type == 'NkmCustomerNo') {
			this.fillHiddenField();
		}

	},

	/**
 	* synchronizes attributes of the hidden field to it's children
 	* @param attributeName : String - Attribute name of the parent element to sync to it's children (e.g. 'disabled' status of the parent)
 	*/
	setAttributeOfChildren : function (attributeName) {
		for (var i = 0; i < this.children.length; i++) {
			$(this.children[i])[attributeName] = $(this.parent)[attributeName];
		}
	},

	setValuesOfChildren : function () {
		if (this.type == 'germancellphonenumber') {
		 	var i1value = "";
	 		var i2value = "";
	 		if ($(this.parent).value.length > 5) {
	 			var firstSpacePos = $(this.parent).value.indexOf(' ');
	 			var secondSpacePos = $(this.parent).value.indexOf(' ',firstSpacePos + 1);
	 			i1value = $(this.parent).value.substring(0, secondSpacePos );
	 			i2value = $(this.parent).value.substring(secondSpacePos + 1,$(this.parent).value.length);
	 		}
			for (var i=0; i < $('1_' + this.parent).options.length; i++) {
				if ($('1_' + this.parent).options[i].value == i1value) {
					$('1_' + this.parent).options[i].selected = true;
				}
			}
			$('2_' + this.parent).value = i2value;
		}

		if (this.type == 'date') {
			var input = $(this.parent);

			var i1value = "";
			var i2value = "";
			var i3value = "";

			if (input.value.length > 0) {
				var splittedDate = input.value.split('.');
				if (splittedDate.length > 0) {
					i1value = splittedDate[0];
				}
				if (splittedDate.length > 1) {
					i2value = splittedDate[1];
				}
				if (splittedDate.length > 2) {
					i3value = splittedDate[2];
				}
			}

			$('1_' + this.parent).value = i1value;
			$('2_' + this.parent).value = i2value;
			$('3_' + this.parent).value = i3value;

		}

		if (this.type == 'phonenumber') {
	 		var input = $(this.parent);

	 		var i1value = "";
	 		var i2value = "";

	 		if (input.value.length > 5) {
	 			var firstSpacePos = input.value.indexOf(' ');
	 			var secondSpacePos = input.value.indexOf(' ', firstSpacePos + 1);
	 			i1value = input.value.substring(0, secondSpacePos );
	 			i1value = i1value.replace("+49 ", "0");
	 			i2value = input.value.substring(secondSpacePos + 1,input.value.length);
	 		}
			$('1_' + this.parent).value = i1value;
			$('2_' + this.parent).value = i2value;
		}


		if (this.type == 'NkmCustomerNo') {
			var input = $(this.parent);

	 		var i1value = new String();
	 		var i2value = new String();
	 		var i3value = new String();

	 		if (input.value.length == 9) {
	 			i1value = input.value.substring(0,4);
	 			i2value = input.value.substring(4,8);
	 			i3value = input.value.substring(8,9);
	 		}
			$('1_' + this.parent).value = i1value;
			$('2_' + this.parent).value = i2value;
			$('3_' + this.parent).value = i3value;
		}

	},

	hideParent : function () {
		$(this.parent).hide();
	},

	fillPhoneNumberOnParent : function () {
		this.fillHiddenField(' ');
		var parentElement = $(this.parent);
		//cut 0
		if (parentElement.value.charAt(0) == '0') {
			parentElement.value = parentElement.value.substring(1, parentElement.value.length) ;
		}
		// add +49
		if (parentElement.value.length > 1) {
			parentElement.value = '+49 ' + parentElement.value;
		}
	},

	getExchangeHtml : function () {
		var aTag;

		if (this.type == 'germancellphonenumber') {
			aTag = '<p class="cellInput"><select id="1_' + this.parent + '" name="1_' + this.parent + '" onblur="if   ( $(\'2_' + this.parent + '\').value != \'\') {fieldExchangeHelpers[\'' + this.parent + '\'].fillHiddenField(&#39; &#39;)} else {$(\'' + this.parent + '\').value=\'\';}">';
			aTag += '<option value="+49 151">0151</option>';
			aTag += '<option value="+49 152">0152</option>';
			aTag += '<option value="+49 155">0155</option>';
			aTag += '<option value="+49 157">0157</option>';
			aTag += '<option value="+49 159">0159</option>';
			aTag += '<option value="+49 160">0160</option>';
			aTag += '<option value="+49 162">0162</option>';

			aTag += '<option value="+49 163">0163</option>';
			aTag += '<option value="+49 170">0170</option>';
			aTag += '<option value="+49 171">0171</option>';
			aTag += '<option value="+49 172">0172</option>';
			aTag += '<option value="+49 173">0173</option>';
			aTag += '<option value="+49 174">0174</option>';

			aTag += '<option value="+49 175">0175</option>';
			aTag += '<option value="+49 176">0176</option>';
			aTag += '<option value="+49 177">0177</option>';
			aTag += '<option value="+49 178">0178</option>';
			aTag += '<option value="+49 179">0179</option>';
			aTag += '<input type="text" onchange="FormUtils.allowNumbersOnChange(this)" onKeyPress="return FormUtils.allowNumbers(this,event);" onKeyDown="return FormUtils.allowNumbers(this,event);" class="text" maxlength="10" onblur="if (this.value != \'\') {fieldExchangeHelpers[\'' + this.parent + '\'].fillHiddenField(&#39; &#39;)} else {$(\'' + this.parent + '\').value=\'\';}" size="7" id="2_' + this.parent + '" name="2_' + this.parent + '"/>';

			aTag += '</select>';
			aTag += '</p>';
		}

		if (this.type == 'date') {
			aTag =  '<p class="dateInput">';

			aTag += '<input maxlength="2" class="text day autofocus"  onKeyPress="return FormUtils.allowNumbers(this,event);" onKeyDown="return FormUtils.allowNumbers(this,event);" onblur="fieldExchangeHelpers[\'' + this.parent + '\'].fillHiddenField(&#39;.&#39;)" onKeyUp="FormUtils.handlePaste(this,event,2,2,4);if ((parseInt(this.value) > 31 || parseInt(this.value) < 0)) {this.value = &#39;&#39; ; new Effect.Highlight( this.id, {duration:0.5, startcolor: &#39;#CC3333&#39;} );}" size="1" id="1_' + this.parent + '" name="1_' + this.parent + '" />';
			aTag += '<input maxlength="2" class="text month autofocus" onKeyPress="return FormUtils.allowNumbers(this,event);" onKeyDown="return FormUtils.allowNumbers(this,event);" onblur="fieldExchangeHelpers[\'' + this.parent + '\'].fillHiddenField(&#39;.&#39;)" onKeyUp="if ((parseInt(this.value) > 12 || parseInt(this.value) < 0)) {this.value = &#39;&#39; ; new Effect.Highlight( this.id, {duration:0.5, startcolor: &#39;#CC3333&#39;} );}" size="1" id="2_' + this.parent + '" name="2_' + this.parent + '" />';
			aTag += '<input maxlength="4" class="text year autofocus autofocusEnd"  onKeyPress="return FormUtils.allowNumbers(this,event);" onKeyDown="return FormUtils.allowNumbers(this,event);" onblur="fieldExchangeHelpers[\'' + this.parent + '\'].fillHiddenField(&#39;.&#39;)" size="2" id="3_' + this.parent + '" name="3_' + this.parent + '"/>';
			aTag += '</p>';
		}

		if (this.type == 'phonenumber') {
			aTag =  '<p class="phone">';
			aTag += '<input onKeyPress="return FormUtils.allowNumbers(this,event);" onchange="FormUtils.allowNumbersOnChange(this)" onKeyDown="return FormUtils.allowNumbers(this,event);" class="text pre"  maxlength="6" onblur="fieldExchangeHelpers[\'' + this.parent + '\'].fillPhoneNumberOnParent()" size="7" id="1_' + this.parent + '" name="1_' + this.parent + '" /> ';
			aTag += '<input onKeyPress="return FormUtils.allowNumbers(this,event);" onchange="FormUtils.allowNumbersOnChange(this)" onKeyDown="return FormUtils.allowNumbers(this,event);" class="text post" maxlength="8" onblur="fieldExchangeHelpers[\'' + this.parent + '\'].fillPhoneNumberOnParent()" size="7" id="2_' + this.parent + '" name="2_' + this.parent + '" /> ';
			aTag += '</script></p>';
		}

		if (this.type == 'NkmCustomerNo') {
	 		aTag =  '<p class="custNo" id="p_' + this.parent + '"><input class="text fstNo autofocus" onKeyPress="return FormUtils.allowNumbers(this,event);" onKeyDown="return FormUtils.allowNumbers(this,event);" maxlength="4" onblur="fieldExchangeHelpers[\'' + this.parent + '\'].fillHiddenField()" id="1_' + this.parent + '" name="1_' + this.parent + '" onKeyUp="FormUtils.handlePaste(this,event,4,4,2);"/>';
			aTag += '<input class="text sndNo autofocus" maxlength="4" onKeyPress="return FormUtils.allowNumbers(this,event);" onKeyDown="return FormUtils.allowNumbers(this,event);" onblur="fieldExchangeHelpers[\'' + this.parent + '\'].fillHiddenField()" id="2_' + this.parent + '" name="2_' + this.parent + '"/>';
			aTag += '<input class="text thdNo autofocus autofocusEnd" maxlength="1" onKeyPress="return FormUtils.allowNumbers(this,event);" onKeyDown="return FormUtils.allowNumbers(this,event);" onblur="fieldExchangeHelpers[\'' + this.parent + '\'].fillHiddenField()" id="3_' + this.parent + '" name="3_' + this.parent + '"/></p>';
		}
		return aTag;
	}

};

function openGlossaryPopup( url )
{
	if (url != null)
	{
		window.open( url, "", "width=748,height=590,scrollbars=no,resizable=no" );
	}
};

function openContentPopup(url, id, parameter) {
	// TODO: This allows for bad links in content to work
	// This should be resolved and removed before launch
	if( parameter == null ) {
		parameter = id;
	}

	// TODO: This allows for bad links from content where second arg
	// Is title in the invalid two arg version
	if( parameter!=null && parameter.indexOf('width')==-1 )
	{
		parameter = null;
	}

    if (parameter == "" || parameter == null) {
        parameter = 'width=400,height=550,scrollbars=yes,resizable=yes';
    }

    var width, height, left = null, top = null;
    temp = parameter.split(",");
    for (var i = 0; i < temp.length; i++) {
        values = temp[i].split("=");
        if (values[0] == "width") {
            width = parseInt(values[1]);
        }
        if (values[0] == "height") {
            height = parseInt(values[1]);
        }
        if (values[0] == "left") {
            left = parseInt(values[1]);
        }
        if (values[0] == "top") {
            top = parseInt(values[1]);
        }
    }
    if (left == null) {
        left = Math.round((screen.width - width) / 2);
    }
    if (top == null) {
        top = Math.round((screen.height - height) / 3);
    }
    if (left != null) {
        parameter += ",screenX=" + left + ",left=" + left;
    }
    if (top != null) {
        parameter += ",screenY=" + top + ",top=" + top;
    }
    var popuphandler = window.open(url, "", parameter);
    if (popuphandler != null) {
        popuphandler.window.focus();
    }
};

/*
 * Support for the compare window
 */
var ProductCompare = {
	openPopup: function( url ) {
		window.open(
			url,
			'product_compare',
			'width=800,height=600,scrollbars=yes,resizable=yes',
			true /* replace history in the popped up window */
		).focus();
	}
};

var Popup = Class.create();
Popup.prototype = {
	initialize: function()
	{
		this.overlay = $('overlay');
		this.content = $('overlayCntWr');
		this.modal = false;
		this.newMarginTop = '';
		this.overlayVisible = false;
		if (!this.content)
			return;

		this.uri = '';
		this.closeListenerFunction = '';
		Event.observe( this.overlay, 'click', this.hidePopup.bindAsEventListener( this ) );
	},

	setOverlayToElement : function( element ) {
		try {
			this.overlay.clonePosition($(element));
		} catch(e) {
		}
		this.centerLoadInfoToOverlay();
		this.overlay.customSize = true;
	},

	centerLoadInfoToOverlay : function() {
		var loadInfo = $('loadInfo');
		var overlayLeft = new Number(this.overlay.style.left.replace('px',''));
		var overlayTop = new Number(this.overlay.style.top.replace('px',''));
		var overlayWidth =  this.overlay.getWidth();
		var overlayHeight = this.overlay.getHeight();
		var loadInfoWidth = loadInfo.getWidth();
		var loadInfoHeight = loadInfo.getHeight();
		loadInfo.style.left = overlayLeft + Math.round((overlayWidth - loadInfoWidth) / 2) + 'px';
		loadInfo.style.top = overlayTop + Math.round((overlayHeight - loadInfoHeight) / 2) + 'px';
	},

	resetOverlaySize : function() {
		if (this.overlay.customSize) {
			this.overlay.clonePosition($(document.body));
			this.setOverlayDefaultHeight();
			this.resetLoadInfoStyle();
			this.overlay.customSize = false;
		}
	},

	resetLoadInfoStyle : function()
	{
		var scroll_top = (document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset);
		var loadInfo = $('loadInfo');
		loadInfo.style.left = (Popup.getPageSize()[0] - loadInfo.getWidth()) / 2 + "px";
		loadInfo.style.top = (scroll_top ? scroll_top : 0) + 200 + "px";
	},

	setContentId: function( id )
	{
		this.content.innerHTML = $( id ).innerHTML;
	},

	setContentIdUnique: function( id )
	{
		var a = $( id ).innerHTML;
		$( id ).innerHTML = "";
		this.content.innerHTML = a;

	},

	getExchangeContent: function()
	{
		return $('overlayExchange');
	},
	setContentWithResponse:function(response, enhance) {
		this.content.innerHTML = response.responseText;
	},
	setExchangeContent: function( content )
	{
		if (!$('overlayExchange'))
			new Insertion.Bottom( document.body, '<div id="overlayExchange" style="display:none"></div>' );

		$('overlayExchange').innerHTML = content;
		this.setContentId( 'overlayExchange' );
		DOMUtils.enhanceDOM($(this.content));
	},

	showOverlay: function() {
		// get page size to display overlay and cnt later
		this.arrayPageSize = Popup.getPageSize();

		if (navigator.userAgent.indexOf( 'IE 6' ) != -1 )
		{
			var selects = $('main').getElementsBySelector( 'select' );

			selects.invoke('hide');
		}
		if (!this.overlay.customSize) {
			this.setOverlayDefaultHeight();
		}
		if (!this.overlay.visible()) {
			new Effect.Appear('overlay', { duration: 0.4, from: 0.0, to: 0.6 });
		}
	},

	showPopup: function(callback)
	{
		// get page size to display overlay and cnt later
		this.arrayPageSize = Popup.getPageSize();

		if (navigator.userAgent.indexOf( 'IE 6' ) != -1 )
		{
			// Limit changes to the original page, not the dialog ..
			$('main').getElementsBySelector('select').invoke('hide');
		}

		if (this.overlay.visible()) {
			this.showOverlayContent(callback);
		}else{
			new Effect.Appear('overlay', { afterFinish:function(){this.showOverlayContent();}.bind(this), duration: 0.4, from: 0.0, to: 0.6 }); // DW: change
		}
	},

	setOverlayDefaultHeight: function()
	{
		if( Prototype.Browser.IE ) {
			var contentHeight = $('overlayCntWr').getHeight()+$('overlayCntWr').positionedOffset()[1];
			if( contentHeight < this.arrayPageSize[1] ) {
				contentHeight = this.arrayPageSize[1];
			}
			Element.setStyle('overlay', { 'height' : contentHeight+'px' });
		} else {
			Element.setStyle('overlay', { 'height' : this.arrayPageSize[1]+'px' });
		}
	},

	showLoading: function()
	{
		this.clearLoading();

		var loadInfo = $('loadInfo');
		var modalFunction = function(event) {
			event.stop();
		};
		Event.observe(this.overlay, 'nkm:Popup:BeforeClose', modalFunction);
		loadInfo.modalFunction = modalFunction;

		this.showOverlay();

		this.timeout = window.setTimeout( function() {
			if (!this.overlay.customSize) {
				this.resetLoadInfoStyle();
			}
			new Effect.Appear( loadInfo, {duration:0.2} );
		}.bind( window.popup ), 500 );
	},


	clearLoading: function()
	{
		if( typeof(this.timeout) != 'undefined' ){
			window.clearTimeout( this.timeout );
			delete this.timeout;
		}


		var loadInfo = $('loadInfo');

		this.hideLoading();

		if (loadInfo.modalFunction) {
			Event.stopObserving(this.overlay, 'nkm:Popup:BeforeClose', loadInfo.modalFunction);
			loadInfo.modalFunction = null;
		}
	},

	setUri: function( uri )
	{
		this.uri = uri + (uri.indexOf('?')==-1?'?':'&') + 'view=ajax';
	},

	showUriContent: function()
	{
		if (!$('overlayExchange'))
			new Insertion.Bottom( document.body, '<div id="overlayExchange" style="display:none"></div>' );

		this.setContentId( 'overlayExchange' );

		new Ajax.Request( this.uri, {
			method:'get',
			onSuccess:function(trans)
			{
				$('overlayExchange').innerHTML = trans.responseText;
				this.setContentId( 'overlayExchange' );

				DOMUtils.enhanceDOM($(this.content));

				this.showPopup();
				try{
				trans.responseText.evalScripts();
				}catch(e){
					alert(e);
				}
			}.bind(this),

			onFailure:function()
			{
				this.showPopup();
			}
		} );
	},

	openWindow: function( uri, width, height, scrollbars )
	{
		var hasScrollbars = scrollbars || false;
		var params = (width ? ('width=' + width) : '' );
		params += (height && width ? ',' : '') + (height ? ('height=' + height) : '');
		if( scrollbars )
			params += (height || width ? ',' : '') + "scrollbars=1";
		window.open( uri, '_blank', params );
	},

	openPrintWindow: function( uri, width )
	{
		window.open( uri, '_blank', 'scrollbars=yes,width=' + (width ? width : 600 ) + ',height=600' );
	},

	showOverlayContent: function(callback)
	{
		if (!this.content.innerHTML){
			return;
		}
		var layerPopup = $('overlayCntWr').select('.layerPopup');
		if (layerPopup[0]){
			if (layerPopup[0].hasClassName('modal')){
				this.modal = true;
				Event.observe(this.overlay, 'nkm:Popup:BeforeClose', function(event) {
					event.stop();
				});
			}
		}

		if (!$('btnClosePopup') && !this.modal)
		{
			var headline = $('overlayCntWr').select('.headline');
			if (headline[0])
				headline[0].innerHTML = '<a id="btnClosePopup" href="javascript:window.popup.hidePopup()"></a>';
		}

		var allDescendants = $(this.content).descendants().compact();
		var maxWidth = 0;
		$(this.content).show();
		for (var i=0; i<allDescendants.length; i++) {
			if (allDescendants[i].getWidth() > 4000) {
				continue;
			}
			maxWidth = Math.max(maxWidth, allDescendants[i].getWidth());
		}

		var currentWidth = $(this.content).getStyle('width');
		if (currentWidth) {
			currentWidth = currentWidth.replace('px', '');
		}
		if (maxWidth > currentWidth) {
			$(this.content).setStyle({width : (maxWidth + 30) + 'px'});
		}
		$(this.content).hide();

		new Effect.Appear('overlayCntWr', { duration: 0.4,
			afterFinish: function() {
				// If the content is greater than the current page, then the layer must be expanded.
				// Otherwise the half page is layered and the other not.
				if( Prototype.Browser.IE ) {
					var contentHeight = $('overlayCntWr').getHeight()+$('overlayCntWr').positionedOffset()[1];
					if( contentHeight < this.arrayPageSize[1] ) {
						contentHeight = this.arrayPageSize[1];
					}
					Element.setStyle('overlay', { 'height' : contentHeight+'px' });
				} else {
					Element.setStyle('overlay', { 'height' : this.arrayPageSize[1]+'px' });
				}
				//Element.setStyle('overlay', { 'height' : Popup.getPageSize()[1]+'px' });
				if( callback ) setTimeout( callback,100 );

			}.bind(this),
			beforeStart: function() {
				// Just delay the call by 10ms to get the correct height.
				window.setTimeout(function() {
					// This MUST be done here, otherwise this '$(this.content).getHeight()' will not return correct results!
					var scroll_top = (document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset);

					var difference = this.arrayPageSize[3] - $(this.content).getHeight();

					if( difference < 0 ) {
						difference = 0;
					} else {
						difference = difference/2;
					}

					this.content.getElementsBySelector('.layIDPop').invoke('setStyle',{marginTop:'0px'});
					if(this.newMarginTop != ''){
						this.content.style.marginTop = this.newMarginTop + "px";
					}else{
						this.content.style.marginTop = difference + (scroll_top ? scroll_top : 0) + "px";
					}

					this.content.style.left = (this.arrayPageSize[0] - Math.max($(this.content).getWidth(), 500))/2 + "px";
				}.bind(this), 10);
			}.bind(this)
		});
	},

	afterOverLayHide : function() {
		this.resetOverlaySize();
	},

	hidePopup: function()
	{
		var overlay = $('overlay');
		var event = overlay.fire('nkm:Popup:BeforeClose');
		if (event.stopped) {
			return;
		}
		new Effect.Fade('overlay', { duration: 0.4, afterFinish: this.afterOverLayHide.bind(this) });


		this.overlayVisible = false;
		this.hideContent();
	},

	hideContent: function()
	{
		this.overlayVisible = false;
		this.hideLoading();
		new Effect.Fade( 'overlayCntWr', {
			duration:0.3,
			afterFinish:function() {
				this.content.innerHTML = "";
				if (navigator.userAgent.indexOf( 'IE 6' ) != -1 )
				{
					// Logic changed to match openPopup ... only affect selects in page (not the dialog too)
					$('main').getElementsBySelector('select').invoke('show');
				}
				this.setWidth( 500 );
				if (this.closeListenerFunction) {
					this.closeListenerFunction();
				}
			}.bind(this)
		});
	},

	hideLoading: function()
	{
		new Effect.Fade('loadInfo', { duration: 0.4});
	},

	hideImagePopup: function()
	{
		var imgIFrame = $('ImageIFrame');

		if ( imgIFrame != undefined ) {
			imgIFrame.innerHTML=' ';
		}

		new Effect.Fade( 'overlay' );
		new Effect.Fade( 'overlayCntWr', {afterFinish:function()
			{
				if (navigator.userAgent.indexOf( 'IE 6' ) != -1 )
				{
					var selects = document.getElementsByTagName( 'select' );
					for ( var i=0; i<selects.length; i++ )	// selects.each cause an error => so old style works
						selects[i].style.visibility = "";
				}

				this.content.style.width="500px";}.bind(this)
			} );

	},

	setWidth: function( newWidth )
	{
		this.content.style.width = newWidth + "px";
	},
	setMarginTop: function( newMarginTop )
	{
		this.newMarginTop = newMarginTop;
	},

	/**
	* With this function a Lister for Popup hide can be set. After the Popup was closed, the given function will be called.
	*/
	addCloseListenerFunction: function(listenerFunction) {
		this.closeListenerFunction = listenerFunction;
	}

};

//
//getPageSize()
//Returns array with page width, height and window width, height
//Core code from - quirksmode.org
//Edit for Firefox by pHaez
//
Popup.getPageSize = function(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

var JSUtils = {

	refine : function( url, viewMode, qold ) {

		// backward compat. --> use new function

		/*
		if(viewMode)
			url = url + ("&viewMode="+viewMode);
		if(qold)
			url = url + ("&qold="+qold);

		window.location.href=url;
		*/

		JSUtils.refineParameterAppend(url, JSParameterMap);
	},

	appendDefinedParameters : function(url, parameterNames, parameterMap) {

		if(parameterNames == null || parameterNames.length == 0 || parameterMap == null || parameterMap.length == 0) {
			return false;
		}

		var newQueryString = "";
		for(var i = 0; i < parameterNames.length; i++) {
			var value = parameterMap[parameterNames[i]];
			if(value == null || value == '') {
				continue;
			}

			newQueryString += parameterNames[i] + '=' + value;
			if((i+1) < parameterNames.length) {
				newQueryString += "&";
			}
		}

		url += (url.indexOf('?')) == -1 ? '?' : '&';
		url += newQueryString;

		window.location.href=url;
	},

	appendRefinementParameters : function(url, parameterMap) {

		// ----------------------------------------
		// internal helper
		function appParam(url, parameterMap, parameter) {

			if(url.indexOf(parameter + "=") != -1) {
				return url;
			}
			if(parameterMap[parameter] != null) {
				return (url + "&" + parameter + "=" + parameterMap[parameter]);
			}
			return url;
		}

		// ----------------------------------------

		if (parameterMap != null) {
			url = appParam(url, parameterMap, "viewMode");
			url = appParam(url, parameterMap, "qold");
			url = appParam(url, parameterMap, "orderableOnly");
			url = appParam(url, parameterMap, "scgid");
			url = appParam(url, parameterMap, "origin");
			url = appParam(url, parameterMap, "offline");
			url = appParam(url, parameterMap, "globalRefined");
			url = appParam(url, parameterMap, "sz");
			url = appParam(url, parameterMap, "showAll");
			url = appParam(url, parameterMap, "ignoreCat");
			if(url.indexOf("pmin=") != -1 && url.indexOf("pmax=") != -1) {
				// we need omin / omax only in price refinement
				url = appParam(url, parameterMap, "omin");
				url = appParam(url, parameterMap, "omax");
			}

			// clear price sort refinement - don't refine by price if pmin = omin and pmax = omax
			if (parameterMap['psortb1'] == 'price-sort' && !/psortb1=price-sort/.test(url)) {
				var pminURL = MiscUtils.getQuerystring(url,"pmin");
				var pmaxURL = MiscUtils.getQuerystring(url,"pmax");

				if (pminURL == parameterMap['omin'] && pmaxURL == parameterMap['omax']) {
					url = url.replace(/&(pmin|pmax|omin|omax)=[0-9]*/g,"");
				}
			}

			// gpa parameters
			if($('productadvisor')) {
				// base advisor parameters
				url = appParam(url, parameterMap, "aid");
				url = appParam(url, parameterMap, "att");
				url = appParam(url, parameterMap, "atv");
				
				// if user has selected to close or exit the advsior, we must add 'hide' 
				// as the last value for the delimited url parameter 'ach' (advisor choices);
				// if user has previously hidden their advisor and reactivated the advisor,
				// we must remove 'hide'
				var ach = MiscUtils.getQuerystring(url,'ach');
				if (lastChoice == 'hide' || advisorExit == true || !/\&ach=/.test(url)) {
					if (ach != null && ach != ''){
						ach = ach + (!/hide$/.test(ach) ? '|' + 'hide' : '');
					}
					else {
						ach = 'hide';
					}
				}
				else {
					if (ach != null && ach != ''){
						ach = ach.replace(/(\|)?hide/,'');
					}
				}

				// add ach (choices) parameter to url, or clear url if no choices
				// omin and omax needed for correct price slender min/max value rendering
				if (ach != '') {
					url = JSUtils.overwriteParameters(url,'ach',ach,'omin',$('omin').value,'omax',$('omax').value);
				}
				else {
					url = url.replace(/&ach=.*(\&|\#|$)/,'');	
				}
				
				// this parameter is passed if advisor has ended so that further user selected refinements can be processed
				if ($('productadvisor').status == 'finished'){
					url = url + "&aend=true";
				}

				// this parameter is passed if user has chosen to exit the advisor via manual
				// refinement selection (used for omniture tracking)
				if (advisorExit == true){
					url = url + "&aex=true";
				}
			}
		}
		return url;
	},

	refineParameterAppend : function(url, parameterMap, catRefine, forceAppend) {
		if(url != null && parameterMap != null) {

			// gpa exit handling
			// we know the user is exiting if the advisor is in progress and is not in an inactive state
			if ($('productadvisor') && $('productadvisor').status == 'inprogress' && !forceAppend && lastChoice != null && lastChoice != 'hide') {
				SearchUtils.exitGpa(null, url); return false;
			}

			url = JSUtils.appendRefinementParameters(url, parameterMap);

			if (catRefine == true) {
				// the link is definitely a category refinement, so remove the url parameter 'ignoreCat' which was forcing 
				// the advisor to ignore the cgid in the url when trying to find an appropriate advisor
				url = url.replace('&ignoreCat=true','');
			}
			window.location.href=url;
		}
	},

	// This function takes a url and appends the given names and values to the
 	// querystring. It uses variable argument list. Existing parameters within
 	// the URL query string will be replaced
	overwriteParameters : function(url) {
		// don't touch href javascripts
		var index = url.indexOf('javascript:');
		if (index != -1) {
			return url;
		}
		var pipeline 	= "";
		var query 		= "";
		var anchor 		= "";
		var newUrl		= "";

		var paramMap	= new Object();

		var queryIndex	= url.indexOf('?');
		var anchorIndex = url.lastIndexOf('#');
		var length		= url.length;

		if(queryIndex != -1) {
			pipeline 	= url.substring(0, queryIndex);
			query		= url.substring(queryIndex + 1,( anchorIndex != -1 ? anchorIndex : length));
		}
		else {
			pipeline 	= url.substring(0, ( anchorIndex != -1 ? anchorIndex : length));
		}

		if(anchorIndex != -1) {
			anchor 		= url.substring(anchorIndex + 1);
		}

		if(query != "") {

			var parameters 			= query.split('&');
			var pair 				= "";
			var name 				= "";
			var value 				= "";
			var separatorIndex 		= -1;
			var counter 			= 0;
			var len 				= parameters.length;

			for(counter = 0; counter < len; counter++) {

				pair = parameters[counter];
				if(pair == null || pair == '') {
					continue;
				}

				separatorIndex = pair.indexOf("=");
				if(separatorIndex < 0) {
					paramMap[pair] = '';
				}
				else {
					name 	= pair.substr(0, separatorIndex);
					value 	= pair.substr(separatorIndex + 1);

					paramMap[name] = value;
				}
			}

			for ( var i = 1; (i < arguments.length) && (i+1 < arguments.length); i+=2 ) {
				paramMap[arguments[i]] = arguments[i + 1];
			}

			query = "";
			for(var param in paramMap) {
				query += (query != "" ? "&" : "") + param + "=" + paramMap[param];
			}
		}
		else {
			for ( var i = 1; (i < arguments.length) && (i+1 < arguments.length); i+=2 ) {
				query += (query != "" ? "&" : "") + arguments[i] + "=" + arguments[i + 1];
			}
		}

		newUrl = pipeline;
		if(query != "") {
			newUrl += "?" + query;
		}

		if(anchor != "") {
			newUrl += "#" + anchor;
		}

		return newUrl;
	},


	refineSCGID : function( url, cgid, scgid ) {

		if( scgid != null && scgid != "") {
			url = url + ("&scgid="+scgid);
			if( cgid != null && cgid != "" ) {
				url = url + ("&cgid="+cgid);
			} else {
				url = url + ("&cgid="+scgid);
			}
		}

		window.location.href=url;
	}
};

var UIUtils = {
	refNavToggle : [],
	toggleRefineNav : function( element, duration ) {

			if (UIUtils.refNavToggle[element] == true)
				return;

			UIUtils.refNavToggle[element] = true;

			var dur = typeof( duration ) == 'undefined' ? 0.1 : duration;

			// don't know who wrote this but there is an effect Effect.toggle you could use!
			if( $(element).visible()){
				new Effect.BlindUp( element, {duration: dur, afterFinish:function(){UIUtils.refNavToggle[element]=false;}});
				if ( $( element + '_headline' ) != null ) {
					$( element + '_headline' ).className = 'linkH';
				}
			} else {
				new Effect.BlindDown( element , {duration: dur, afterFinish:function(){UIUtils.refNavToggle[element]=false;$(element).setOpacity(1);}});
				if ( $( element + '_headline' ) != null ) {
					$( element + '_headline' ).className = 'linkS';
				}
			}
	},

	hideRefineNav : function( element ) {

		if ( $( element + '_headline' ) != null )
		{
			$( element).style.visibility = "hidden";
			$( element + '_headline' ).className = 'linkS';
		}

	},

	exchangeContent : function( element1, element2 ) {
		new Effect.BlindUp( element1, {duration :0.2,
				afterFinish: function()	{
					Effect.BlindDown( element2 , {duration :0.2});
				}
		});
	},

	showContent : function( element ) {

		if( !$(element).visible()){
			new Effect.BlindDown( element , {duration :0.1});
		}
	},

	hideContent : function( element ) {

		new Effect.BlindUp( element, {duration :0.1});

	},

	toggleContent : function( element, duration ) {
		var dur = typeof( duration ) == 'undefined' ? 0.2 : duration;

		if( $(element).visible()){
			new Effect.BlindUp( element, {duration: dur });
		}
		else {
			new Effect.BlindDown( element , {duration: dur });
		}

	}
};

/*
 * Functionality around AJAX requests and effects.
 */
var AJAXHelper = {
	originalLabelsOfToggle:$H({}),
	explicitInputs:null,

	toggleContent : function( element, url, toggleOptions ) {
		// request content before toggling
		if( $(element).visible()){
			new Effect.BlindUp( element, {duration :0.2});

			if (typeof( toggleOptions ) == 'undefined' || !toggleOptions.id)
				return;

			var link_element = $( toggleOptions.id );
			link_element.className = toggleOptions.closedClass;
			link_element.innerHTML = AJAXHelper.originalLabelsOfToggle[ toggleOptions.id ];
		}
		else {
			new Ajax.Updater( $(element),url,{method:'get',onSuccess : function(transport){ new Effect.BlindDown( element , {duration :0.2}); }});

			if (typeof( toggleOptions ) == 'undefined' || !toggleOptions.id)
				return;

			var link_element = $( toggleOptions.id );
			link_element.className = toggleOptions.openedClass;
			AJAXHelper.originalLabelsOfToggle[ toggleOptions.id ] = link_element.innerHTML;
			link_element.innerHTML = toggleOptions.openedLabel;
		}
	},

	//given content is toggled out and after animation new content is loaded by ajax
	exchangeContent : function( element, url ) {
		new Effect.BlindUp( element, {
				duration :0.2,
				afterFinish: function() {
					new Ajax.Updater($(element),url,{method:'get',onSuccess : function(transport){ new Effect.BlindDown( element , {duration :0.2}); }});
				}
		});
	},


	setExplicitInputs: function( elementNames )
	{
		this.explicitInputs = $A( elementNames );
	},


	/**
	* Makes an AJAX-Call to the form of the given button and sets the response to the element.
	* The response will also be set to the MiniCart-Popup - if available.
	* If so, then the content is exchanged to the visible divs - if they exist.
	*/
	submitToElement : function( element, button ) {
		var postdata = "";
		var i,ii,form = button.form;
		if (this.explicitInputs == null) {
			postdata = form.serialize();
		} else {
			// PJP: removed each() and unnecessary bind()
			for( i=0, ii=this.explicitInputs.length; i<ii; i++ ) {
				var item = this.explicitInputs[i];
				postdata += Form.serializeElements( form.getInputs( item ) ) + "&";
			}
			postdata += button.name + "=" + button.value;
		}

		//var postdata = Form.serialize(form);
		if (postdata.indexOf(button.name + '=' + button.value) == -1) {
			postdata += (postdata.length > 0 ? '&' : '') + button.name + '=' + button.value;

		}

		Form.disable(form);

		var action = form.action;
		action += (action.indexOf('?')==-1?'?':'&') + 'view=ajax';

		new Ajax.Updater( element, action , {parameters:postdata, onComplete:  function(transport) {
			transport.responseText.evalScripts();
			DOMUtils.enhanceDOM(element);
			Form.enable(form);
		}} );
	}
};

var FormPreChecker = Class.create();
FormPreChecker.prototype = {
	formName: '',
	form:null,
	btnNames:null,
	buttons:null,
	explicitInputs:null,
	lastEventSerialised:null,
	updateEvents:null,
	modal:false,
	exchangeWithResult:null,


	initialize: function()
	{
		this.listener = $A([]);

		// if a layer is opened from a ajax only formprechecker (= exchangeWithResult), which has its own formPreChecker, the ajax-only flags will be carried
		// over to this formprechecker
		if ((MiscUtils.getAjaxUrlParameterValue('exchangeWithResult') == "true") && (MiscUtils.getAjaxUrlParameterValue('exchangeWithResultId') != "")) {
			this.setExchangeWithResult(MiscUtils.getAjaxUrlParameterValue('exchangeWithResultId'));
		}
	},

	setForm: function( name )
	{
		this.formName = name;
		this.form = $(name) || document.getElementsByName( name )[0];
		if (!this.form)
			return;
	},

	setExchangeWithResult: function( element2exchange )
	{
		this.exchangeWithResult = element2exchange;
	},

	setFormElement: function( theForm )
	{
		this.form = theForm;
	},

	setExplicitInputs: function( elementNames )
	{
		this.explicitInputs = $A( elementNames );
	},

	formPreCheckerHandlerFunction: function( ev, item ) {
		$('overlayCntWr').hide();

		// add non-closable property
		if (Element.hasClassName(item, 'modal')) {
			Event.observe(window.popup.overlay, 'nkm:Popup:BeforeClose', function(event) {
				if (this.modal) {
					event.stop();
				}
			});
			this.modal = true;
		}

		window.popup.showLoading();

		var params = "";
		if (!this.form || this.form == null) {
			var formElement = item.up('form');
			this.setFormElement(formElement);
		}

		item.fire('nkm:FormPreChecker:BeforeSerialize', this.form);

		if (this.explicitInputs == null) {
			params = this.form.serialize();
		}
		else
		{
			this.explicitInputs.each( function (item) {
				params += Form.serializeElements( this.form.getInputs( item ) ) + "&";

				if ( item != 'select' )
				{
					if( item == 'textarea')
					{
						var textareas = this.form.select('textarea');

						if (!textareas || textareas.length == 0)
							return;

						textareas.each(
							function(curArea)
							{
								params += curArea.name + "=" + encodeURIComponent( curArea.getValue() ) + "&";
							} );

					}
					return;
				}
				else
				{
					if( item == 'textarea')
					{
						var textareas = this.form.select('textarea');

						if (!textareas || textareas.length == 0)
							return;

						textareas.each(
							function(curArea)
							{
								params += curArea.name + "=" + encodeURIComponent( curArea.getValue() ) + "&";
							} );

					}
				}
				var selects = this.form.select('select');

				if (!selects || selects.length == 0)
					return;

				this.form.select('select').each(
					function(curSel)
					{
						if (curSel.selectedIndex < 0)
							return;
						params += curSel.name + "=" + encodeURIComponent( curSel.getValue() ) + "&";
					} );

			}.bind( this ) );
			this.lastEventSerialised = item.name + "=" + item.value;
			params += this.lastEventSerialised;
		}

		this.enableButtons( false );
		var ajax_params = (this.form.action.indexOf( '?' ) == -1 ? '?' : '&') + 'view=ajax';
		if (this.exchangeWithResult) {
			ajax_params += "&exchangeWithResult=true&exchangeWithResultId=" + this.exchangeWithResult;
		}
		new Ajax.Request(
			this.form.action + ajax_params,
			{
				evalJS: false,
				method:'post',
				parameters:params,
				onComplete: this.handleResponse.bind(this)
			}
		);

		ev.stop();
	},

	setButtons: function( names, root )
	{
		if (typeof( names ) == 'string')
			this.btnNames = [ names ];
		else
			this.btnNames = names;

		this.btnNames.each( function(name)
		{
			var buttons;
			if (root) {
				buttons = $A( root.select('[name="' + name + '"]') );
			} else {
				buttons = $A( document.getElementsByName(name) );
			}

			buttons.each(
				function( item )
				{
					if (!item.formPreCheckerHandlerFunctionSet) {
						Event.observe(item, 'click', this.formPreCheckerHandlerFunction.bindAsEventListener(this, item));
						item.formPreCheckerHandlerFunctionSet = true;
					}
				}.bind( this )
			);
		}.bind( this )
		);
	},

	setButton : function(item){
		if (!item.formPreCheckerHandlerFunctionSet) {
			Event.observe(item, 'click', this.formPreCheckerHandlerFunction.bindAsEventListener(this, item));
			item.formPreCheckerHandlerFunctionSet = true;
		}
	},

	addListener: function( func )
	{
		this.listener.push( func );
	},

	jsonParseFailed: function(responseText)
	{
		if (!this.exchangeWithResult) {
			this.form.action = this.form.action.replace( 'view=ajax', this.lastEventSerialised );
			this.form.submit();
		} else {
			if ($('overlay').customSize) {
				window.popup.resetOverlaySize();
			}
			$(this.exchangeWithResult).update(responseText);
		}
	},

	handleResponse: function( trans )
	{
		this.enableButtons( true );
		window.popup.overlayVisible = false;

		//var parts = trans.responseText.substring(0,1000).split('<!-- json:');
		var jsonSearchStart = '<!-- json:';
		var jsonSearchEnd = '-->';
		var json_start = trans.responseText.indexOf (jsonSearchStart);
		if( json_start == -1){
			this.jsonParseFailed(trans.responseText);
			return;
		}
		var json_end = trans.responseText.indexOf (jsonSearchEnd, json_start + jsonSearchStart.length);
		if( json_end == -1){
			this.jsonParseFailed(trans.responseText);
			return;
		}
		var json_raw = trans.responseText.substring(json_start + jsonSearchStart.length, json_end);
		var json = eval( '(' + json_raw.replace('\'','\\\'') + ')' );

 		if (json.status == 'OK') {

 			if (!this.exchangeWithResult) {
	 			// if the formprechecker was attached to a form which was submitted via post we need to resend a form
				// in order to force the browser to show the reload warning.
				if (typeof(this.form.method) != 'undefined' && this.form.method == 'post') {
					$('loadInfo').insert({after: '<form id="fakePost" action="'+json.continueUrl+'" method="post"><input type="hidden" name="fake" value="5"><input type="submit" style="display: none;" id="fakeSubmit" value="forPostRequestSimulation" name="fakeSubmit"></form>'});
					$('fakeSubmit').click();
				} else {
					location.href=json.continueUrl;
				}
 			} else  {
 				// if parent page should be updated with response
 				new Ajax.Request(json.continueUrl + "?view=ajax&skipContinueNode=true", {onComplete:  this.handleExchangeContentResponse.bind(this)});
 			}
		} else {
			if ($('overlay').customSize) {
				window.popup.resetOverlaySize();
			}
			if( this.modal ) window.popup.modal = true;
			if( json.evalScripts == 'false' ) {
				window.popup.setContentWithResponse( trans, false );
				var mbx = $('miniBasketExchange');
				if( mbx ) {
					var mc = $('minicart');
					if( mc ) {
						mc.update(mbx.innerHTML);
					}
				}
				var mbce = $('miniRateCalculator');
				if( mbce ) {
					var mbc = $('minicartRateCalculator');
					if( mbc ) {
						mbc.update(mbce.innerHTML);
					}
				}
				if (json.popupWidth) {
					window.popup.setWidth(json.popupWidth);
				} else {
					window.popup.setWidth(586);
				}
			} else {
				window.popup.setExchangeContent(trans.responseText);

				// !!! This line calls implicit the evalScripts function !!!
				// So "trans.responseText.evalScripts();" must NOT be called.
				var tempElement = new Element('div').update(trans.responseText);
				var miniBasketExchange = tempElement.down('[id = "miniBasketExchange"]');

				if (miniBasketExchange) {
					var minicart = $('minicart');
					if (minicart) {
						minicart.update(miniBasketExchange.innerHTML);
					}
				}

				var miniRateCalculatorExchange = tempElement.down('[id = "miniRateCalculator"]');
				if (miniRateCalculatorExchange) {
					var miniRateCalculator = $('miniRateCalculator');
					if (miniRateCalculator) {
						miniRateCalculator.update(miniRateCalculatorExchange.innerHTML);
					}
				}
			}

			if (json.popupWidth) {
				window.popup.setWidth(json.popupWidth);
			} else if (json.miniCart) {
				window.popup.setWidth(586);
			}

 			window.popup.clearLoading();
			if( json.evalScripts=="false" ) {
 				window.popup.showPopup(function(){
					DOMUtils.enhanceFormsWithPreChecker($(window.popup.content));
 				});
			} else {
 				window.popup.showPopup();
			}
		}

		if (this.listener)
			this.listener.each( function(func){func(this)}.bind(this) );
	},

	handleExchangeContentResponse: function(transport) {
		$(this.exchangeWithResult).innerHTML = "";
		$(this.exchangeWithResult).update(transport.responseText);
		DOMUtils.enhanceDOM($(this.exchangeWithResult));
		this.setModal(false);
		window.popup.hidePopup();

		if ($('overlay').customSize) {
			window.popup.resetOverlaySize;
		}
	},

	setModal: function(modal) {
		window.popup.modal = modal;
		this.modal = modal;
		if (!modal) {
			var loadInfo = $('loadInfo');
			if (loadInfo.modalFunction) {
				Event.stopObserving(window.popup.overlay, 'nkm:Popup:BeforeClose', loadInfo.modalFunction);
				loadInfo.modalFunction = null;
			}
		}
	},

	enableButtons: function( kind )
	{
		if( !this.buttons ) return;

		for( var i=0; i<this.buttons.length; i++ )
		{
			if (!('enable' in this.buttons[i]))
					return;

			this.buttons[i][ kind ? 'enable' : 'disable' ]();
		}
	}
};

var Slider = Class.create();

Slider.getConfig = function() {

	var configContainer = $('JSPriceSliderConfig');
	if(!configContainer) return null;

	var rawData = configContainer.firstChild.nodeValue;
	if(!rawData) return null;

	var jsonObject = rawData.evalJSON();
	if(!jsonObject) return null;

	return jsonObject;
}

Slider.getConfigRating = function() {

	var configContainer = $('JSRatingSliderConfig');
	if(!configContainer) return null;

	var rawData = configContainer.firstChild.nodeValue;
	if(!rawData) return null;

	var jsonObject = rawData.evalJSON();
	if(!jsonObject) return null;

	return jsonObject;
}

Slider.manualPriceChange = function() {

	var jsonObject = Slider.getConfig();
	if(!jsonObject) return;

	var manMin = document.getElementById("min").value;
	var manMax = document.getElementById("max").value;
	var origMin = document.getElementById("omin").value;
	var origMax = document.getElementById("omax").value;

	if(manMin == "") manMin = origMin;
	if(manMax == "") manMax = origMax;

	manMin = parseInt(manMin);
	manMax = parseInt(manMax);
	origMin = parseInt(origMin);
	origMax = parseInt(origMax);

	if(isNaN(manMin)) manMin = jsonObject.manMin;
	if(isNaN(manMax)) manMax = jsonObject.manMax;
	if(isNaN(origMin)) origMin = jsonObject.origMin;
	if(isNaN(origMax)) origMax = jsonObject.origMax;
	// no negative values
	(manMin < 0) ? manMin = Math.abs(manMin) : manMin = manMin;
	(manMax < 0) ? manMax = Math.abs(manMax) : manMax = manMax;
	// no wrong sort direction

	if(manMax < manMin) {
	  var tmp = manMin;
	  manMin = manMax;
	  manMax = tmp;
	}
	// dont go out of range
	if(manMin < origMin) manMin = origMin;
	if(manMax > origMax) manMax = origMax;

	Slider.refineByPrice(manMin, manMax, origMin, origMax);

}

Slider.ratingChangeView = function(min, max){

	if(min == '0'){
		$('imgRatingMin').setStyle({'width':'14px', 'backgroundPosition':'0px -15px'});

	}
	else{
		$('imgRatingMin').setStyle({'width':'' + (14*Number(min)) +'px', 'backgroundPosition':'0px 0px'});
	}

	if(max == '0'){
		$('imgRatingMax').setStyle({'width':'14px', 'backgroundPosition':'0px -15px'});

	}
	else{
		$('imgRatingMax').setStyle({'width':'' + (14*Number(max)) +'px', 'backgroundPosition':'0px 0px'});
	}

	if(min == max){
		$('imgRatingMin').hide();
		$('imgRatingDelimiter').hide();
		if(min == '5'){
			$('handleLeftRating').setStyle({'zIndex':20});
			$('handleRightRating').setStyle({'zIndex':10});
		}
		else if(min == '0'){
			$('handleLeftRating').setStyle({'zIndex':10});
			$('handleRightRating').setStyle({'zIndex':20});
		}
	}
	else{
		$('imgRatingMin').show();
		$('imgRatingDelimiter').show();
	}

}

Slider.manualRatingChange = function(){

	var configObj = Slider.getConfigRating();
	if(!configObj) return;

	var manMin = document.getElementById("rmin").value;
	var manMax = document.getElementById("rmax").value;
	var origMin = document.getElementById("romin").value;
	var origMax = document.getElementById("romax").value;

	manMin = parseInt(manMin);
	manMax = parseInt(manMax);
	origMin = parseInt(origMin);
	origMax = parseInt(origMax);

	if(isNaN(manMin)) manMin = configObj.manMin;
	if(isNaN(manMax)) manMax = configObj.manMax;
	if(isNaN(origMin)) origMin = configObj.origMin;
	if(isNaN(origMax)) origMax = configObj.origMax;

	// no negative values
	(manMin < 0) ? manMin = Math.abs(manMin) : manMin = manMin;
	(manMax < 0) ? manMax = Math.abs(manMax) : manMax = manMax;

	// no wrong sort direction
	if(manMax < manMin) {
	  var tmp = manMin;
	  manMin = manMax;
	  manMax = tmp;
	}

	// dont go out of range
	if(manMin < origMin) manMin = origMin;
	if(manMax > origMax) manMax = origMax;

	Slider.refineByRating(manMin, manMax, origMin, origMax);

}

Slider.refineByRating = function(rmin, rmax, romin, romax){

	var configObject = Slider.getConfigRating();
	if(!configObject) return;

	var url = decodeURI(configObject.ratingURL);

	var aresult = new Array();


	for(var i = (rmin * 2); i <= (rmax * 2); i++){
		//aresult.push(i + " - " + (Number(i) + 1));
		aresult.push(i);
	}

	url = url.replace('_ratingvalue_', aresult.join("|"));

	url = url + "&rrefine=true";
	url = url.replace( /&amp;/g, '&');
	JSUtils.refineParameterAppend(url, JSParameterMap);

}

Slider.refineByPrice = function(pmin, pmax, omin, omax) {

	var jsonObject = Slider.getConfig();
	if(!jsonObject) return;

	var url = jsonObject.priceURL;


	url = url.replace( 'pmin=0', 'pmin='+pmin);
	url = url.replace( 'pmax=0', 'pmax='+pmax);
	url = url + ("&omin="+omin);
	url = url + ("&omax="+omax);
	url = url + "&prefine=true";
	url = url.replace( /&amp;/g, '&');

	// gpa exit handling
	if ($('productadvisor') && $('productadvisor').status == 'inprogress' && lastChoice != null && lastChoice != 'hide') {
		SearchUtils.exitGpa(Slider.element, url); return false;
    }

	JSUtils.refineParameterAppend(url, JSParameterMap);
}

Slider.getPriceSliderValues = function(minValue, maxValue) {

	// init
	var values = [];
	var diff = 0;
	var stepWidth = 1;
	var stepWidths = new Hash();

	// -------------------------------------------
	// 1. configuration
	// stepWidths must be ordered asc., otherwise calculation of
	// stepWidth don't work
	stepWidths.set(35, 1);
	stepWidths.set(90, 2);
	stepWidths.set(500, 5);
	stepWidths.set(1000, 10);
	stepWidths.set(5000, 50);

	// -------------------------------------------
	// 2. plausibility
	minValue = Math.max(minValue, 0);
	maxValue = Math.max(minValue, maxValue);
	if(minValue == maxValue) maxValue += 1;

	// -------------------------------------------
	// 3. calculation of stepwidth
	diff = maxValue-minValue;
	/*PJP removed each()*/
	var i,ii;
	for( i=0, ii=stepWidths.length; i<ii; i++ ) {
		var currentEntry = stepWidths[i];

		// init with the current stepWidth
		stepWidth = currentEntry.value;

		// if the difference of the priceRange is smaller (or equal)
		// we can stop searching for the stepWidth
		if(diff <= currentEntry.key) {
			 throw $break;
		}

		// otherwise the loop will step to the next entry. If we are
		// at the end of the hash, the highest value becomes the stepWidth.
		// This is intended.
	}
	// -------------------------------------------


	// -------------------------------------------
	// 4. calculation of slider values
	if(stepWidth > 1) {

		// we need an exceptional handling for the min and max values
		values.push(minValue);

		// init the counter with the next automatic step of the interval
		//
		//	pmin: 6  | stepWidth: 10 --> counter = 6  - 6 + 10 = 10;
		//	pmin: 11 | stepWidth: 10 --> counter = 11 - 1 + 10 = 20;
		//
		var counter = minValue - (minValue % stepWidth) + stepWidth;
		while(counter < maxValue) {
			values.push(counter.round());
			counter += stepWidth;
		}

		// we need an exceptional handling for the min and max values
		values.push(maxValue);
	}
	// -------------------------------------------


	// -------------------------------------------
	// 5. remove possible duplicates (could happen if maxValue == lastCounterStep)
	if(values.length == 0) {
		// means stepwidth = 1
		values = null;
	}
	else {
		values = values.uniq();
	}

	return values;
};


Slider.prototype = {
	initialize: function( id, options )
	{
		this.element = $( id );

		if (typeof(options) != 'undefined' )
		{
			this.trackId 	 = ("trackId" in options) ? options.trackId : "trackline";
			this.btnLeftId   = ("btnLeftId" in options) ? options.btnLeftId : "handleLeft";
			this.btnRightId  = ("btnRightId" in options) ? options.btnRightId : "handleRight";
			this.minRange 	 = ("minRange" in options) ? options.minRange : 0;
			this.maxRange 	 = ("maxRange" in options) ? options.maxRange : 500;
			this.min 	 	 = ("min" in options) ? options.min : 0;
			this.max 	 	 = ("max" in options) ? options.max : 500;
			this.txtmin 	 = $( ("txtmin" in options) ? options.txtmin : 'min' );
			this.txtMax 	 = $( ("txtMax" in options) ? options.txtMax : 'max' );
			this.values		 = ("values" in options) ? options.values : null;
			if ("onChange" in options)
				this.onChange = options.onChange;
			if ("onDragEnd" in options)
				this.onDragEnd = options.onDragEnd;
		}
		else
			this.initOptions();

		this.max = (this.max == -1||(this.min == null&&this.max==this.minRange)) ? this.maxRange : this.max;
		this.min = (this.min == -1||this.min == null) ? this.minRange : this.min;

//		this.txtmin.onkeyup = this.onChangeMin.bindAsEventListener( this );
//		this.txtmin.onblur = this.onBlurMin.bindAsEventListener( this );
//		this.txtMax.onkeyup = this.onChangeMax.bindAsEventListener( this );
//		this.txtMax.onblur = this.onBlurMax.bindAsEventListener( this );

		this.createSlider();

		this.txtmin.value = this.min;
		this.txtMax.value = this.max;
	},

	swapValues: function()
	{
		if (this.min>this.max)
		{
			var tmp = this.minRange;
			this.minRange = this.max<this.minRange?this.max : this.minRange;
			this.maxRange = this.min>this.maxRange ? this.min : this.maxRange;

			tmp = this.min;
			this.min = this.max;
			this.max = tmp;

			this.txtmin.value = this.min;
			this.txtMax.value = this.max;
		}
	},

	createSlider:function()
	{
		this.slider = new Control.Slider( [this.btnLeftId, this.btnRightId], this.trackId, {
			axis: 'horizontal',
			range: $R( this.minRange, this.maxRange ),

			sliderValue:[ this.min, this.max ],
			values: this.values,
			onChange:function(v)
			{
				this.onDragEnd( this );
				this.updatePriceValues( v );
			}.bind(this),
			onSlide:function(v){
				this.updatePriceValues( v );
				this.onChange( this );
			}.bind(this)
		});
	},

	updatePriceValues: function( v )
	{
		this.min = parseInt(v[0],10);
		this.max = parseInt(v[1],10);

		this.txtmin.value = this.min;
		this.txtMax.value = this.max;
	},

	initOptions: function( options, attr, defaultVal )
	{
		this.trackId = "trackline";
		this.btnLeftId = "handleLeft";
		this.btnRightId = "handleRight";
		this.minRange = 0;
		this.maxRange = 500;
		this.min = 0;
		this.max = 500;
		this.txtmin = 'min';
		this.txtMax = 'max';
		this.values = null;
	},

	setMin: function( value )
	{
		this.min = value;
		this.txtmin.value = value;
		if (this.txtmin.value != "")
			this.onChangeMin();
	},

	setMax: function( value )
	{
		this.max = value;
		this.txtMax.value = value;
		if (this.txtMax.value>0)
			this.onChangeMax();
	},

	// function to get initially called, but should be overwritten
	onChange: function()
	{

	},

	onChangeMin: function()
	{
		window.clearTimeout( this.timeout );
		this.timeout = window.setTimeout(
			function(){
				this.swapValues();
				this.recreateSlider();
			}.bind(this),
			1000 );

	},

	recreateSlider: function()
	{
		if (!this.txtmin.value || isNaN(this.txtmin.value))
					return;

		var value = parseInt( this.txtmin.value.replace( /-/g, '' ), 10 );
		this.min = value;
		this.swapValues();
//		if ( value < this.minRange )
//		{
//			this.minRange = this.min;
		this.createSlider();
//		}

//		this.slider.setValue( value, 0 );
	},

	onChangeMax: function()
	{
		if (this.txtMax.value == 0)
			return;

		window.clearTimeout( this.timeout );
		this.timeout = window.setTimeout(
			function(){
				if (!this.txtMax.value || this.txtMax.value ==0 || isNaN(this.txtMax.value))
					return;

				var value = parseInt( this.txtMax.value.replace( '-', '' ), 10 );
				this.max = value;
				if (this.max > this.maxRange)
					this.maxRange = this.max;

				this.swapValues();
				this.createSlider();
				this.slider.setValue( value, 1 );
			}.bind(this),
			1000 );
	},

	onBlurMin: function()
	{
		this.resetVals( this.txtmin, this.minRange );
		this.swapValues();
		this.recreateSlider();
	},

	onBlurMax: function()
	{
		this.swapValues();
		this.resetVals( this.txtMax, this.maxRange );
	},

	resetVals: function( field, initVal )
	{
		if (field.value != "" && isNaN(field.value))
			field.value = initVal;
	}
};

var MultiProductTeaser = Class.create();
MultiProductTeaser.prototype = {

	initialize: function( htmlObj )
	{
		if (typeof(htmlObj) == 'undefined')
			return;

		this.layers = htmlObj.getElementsByClassName( 'prodLayers' )[0].childElements();
		this.teaserLink = htmlObj.getElementsByClassName( 'exchangeImg' )[0];
		this.pager = htmlObj.getElementsByClassName( 'prodPager' )[0];
		this.pagerLinks = this.pager.childElements();
		this.htmlObj = htmlObj;
		this.index = 0;
		if( this.layers[0]!=null ) this.layers[0].show();

		this.initPager();
		this.updateNavButtons();
	},

	initPager: function()
	{
		this.pagerLinks.each( function( item, index )
		{
			switch( item.className )
			{
				case 'next': this.nextBtn = item;
							 item.onclick=this.switchNext.bindAsEventListener(this);
							 break;

				case 'prev': this.prevBtn = item;
							 item.onclick=this.switchPrev.bindAsEventListener(this);
							 break;

				default:	 item.onclick=function(evt){this.switchTo( index-1 ); Event.stop(evt);}.bindAsEventListener(this);
							 break;
			}
		}.bind(this) );
	},

	updateLinks: function( oldIndex, newIndex )
	{
		// notice: + 1 is neccessary due to the prev buttons having index 0
		var new_cls_name = this.pagerLinks[ oldIndex + 1 ].className.replace( "active", "" );
		this.pagerLinks[ oldIndex + 1 ].className = new_cls_name;
		this.pagerLinks[ newIndex + 1 ].className += " active";

		if( this.layers[oldIndex]!=null ) this.layers[ oldIndex ].hide();
		if( this.layers[newIndex]!=null ) this.layers[ newIndex ].show();

		// change the teaser image
		if( this.layers[newIndex]!=null ) {
			var ex_cnt = this.layers[ newIndex ].getElementsByClassName( 'exchangeImg' )[0];
			this.teaserLink.href=ex_cnt.href;
			this.teaserLink.down().src = ex_cnt.down().src;
		}

		this.updateNavButtons();
	},

	switchNext: function(evt)
	{
		this.updateLinks( this.index, ++this.index );
		Event.stop(evt);
	},

	switchPrev: function(evt)
	{
		this.updateLinks( this.index, --this.index );
		Event.stop(evt);
	},

	switchTo: function( page )
	{
		this.updateLinks( this.index, this.index = page );
	},

	updateNavButtons: function()
	{
		this.prevBtn.style.visibility = this.index > 0 ? '' : 'hidden';
		this.nextBtn.style.visibility = this.index+1 < this.layers.length ? '' : 'hidden';
	}
};

var ViewUtils = {
	getZoomView : function( url ) {

		var imgDC = $('imageDetailContent');
		new Ajax.Updater( imgDC, url,{method: 'get'});
		ViewUtils.changeImgLayerButton( 'imgLayZoomButton' );

	},

	getBigView : function( url ) {

		var imgDC = $('imageDetailContent');
		new Ajax.Updater( imgDC, url,{ method: 'get', onComplete:function(transport){ ViewUtils.showImgBigHoverBox(); }});
		ViewUtils.changeImgLayerButton( 'imgLayBigButton' );
	},

	getMaterialView : function( url ) {

		var imgDC = $('imageDetailContent');
		new Ajax.Updater( imgDC, url,{ method: 'get', onComplete:function(transport){ ViewUtils.positionContentImg(); }});
		ViewUtils.changeImgLayerButton( 'imgLayMaterialButton' );

	},

	changeImgLayerContentImg : function( url ) {

		var imgMat = $('imgLayerContentImg');
		imgMat.writeAttribute("src", url);
		imgMat.observe("load",ViewUtils.positionContentImg);
	},

	changeImgLayerButton : function( element ) {

		if ( document.getElementById('imgLayZoomButton') != undefined )	{
			if ( element == 'imgLayZoomButton' ) {
				document.getElementById('imgLayZoomButton').className = 'selSpan';
			} else {
				document.getElementById('imgLayZoomButton').className = 'unselSpan';
			}
		}

		if ( document.getElementById('imgLayBigButton') != undefined )	{
			if ( element == 'imgLayBigButton' ) {
				document.getElementById('imgLayBigButton').className = 'selSpan';
			} else {
				document.getElementById('imgLayBigButton').className = 'unselSpan';
			}
		}

		if ( document.getElementById('imgLayMaterialButton') != undefined )	{
			if ( element == 'imgLayMaterialButton' ) {
				document.getElementById('imgLayMaterialButton').className = 'selSpan';
			} else {
				document.getElementById('imgLayMaterialButton').className = 'unselSpan';
			}
		}

	},

	setup_img_box : function(width, height)
	{
		var scale_fac = 0.566;
		var img_center_width = Math.ceil( width * scale_fac );
		var img_center_height = Math.ceil( height * scale_fac );

		var imgOpacCenterParent = $('imgOpacCenterParent');
		imgOpacCenterParent.style.width = img_center_width + 'px';
		imgOpacCenterParent.style.height = img_center_height + 'px';
		imgOpacCenterParent.style.top = Math.round( (height - img_center_height) / 2 ) + 'px';

		var imgOpacCenter = $('imgOpacCenter');
		imgOpacCenter.style.width = img_center_width + 'px';
		imgOpacCenter.style.height = img_center_height + 'px';

		var corner_height = Math.ceil( height / 2 ) + 'px';
		$$('.hoverTopLeft')[0].style.height =
		$$('.hoverTopRight')[0].style.height =
		$$('.hoverBottomLeft')[0].style.height =
		$$('.hoverBottomRight')[0].style.height =
		$('imgOpacTopLeft').style.height =
		$('imgOpacTopRight').style.height =
		$('imgOpacBottomLeft').style.height =
		$('imgOpacBottomRight').style.height = corner_height;
		$$('.imgBoxHover')[0].style.height = height + "px";

		var img_center_left = Math.floor( ( 198 - img_center_width ) / 2 );
		$('imgOpacCenterParent').style.left = img_center_left + 'px';
	},

	showImgBigHoverBox : function() {

		new Effect.Opacity('imgOpacTopLeft', {duration:0.1,from:1.0, to:0.0} );
		new Effect.Opacity('imgOpacTopRight', {duration:0.1,from:1.0, to:0.0} );
		new Effect.Opacity('imgOpacBottomLeft', {duration:0.1,from:1.0, to:0.0} );
		new Effect.Opacity('imgOpacBottomRight', {duration:0.1,from:1.0, to:0.0} );
		new Effect.Opacity('imgOpacCenter', {duration:0.1,from:1.0, to:0.0} );

		var imgHover = new Image();

		var imgHoverUri = $('imgOpacCenterParent').style.backgroundImage;

		var imgHoverUriArr = imgHoverUri.toArray();

		imgHoverUri = '';

		for ( var i = 4; i < imgHoverUriArr.length - 1; i++) {

	 		imgHoverUri = imgHoverUri + imgHoverUriArr[i];

		}

		imgHover.src = imgHoverUri;

		imgHover.onload = function()
		{
			ViewUtils.setup_img_box(imgHover.width, imgHover.height);
		}

		if (navigator.userAgent.indexOf('IE') != -1)
			ViewUtils.setup_img_box(imgHover.width, imgHover.height);
	},

	positionContentImg : function() {
		if (navigator.userAgent.indexOf( 'IE 6' ) != -1 ) {
			var imageHeight = $('imgLayerContentImg').getHeight()==0 ? 250 : $('imgLayerContentImg').getHeight();
			var imgPadding = ( 492 - imageHeight ) / 2;
			var imgHeight = 492 - imgPadding;
			$('imgLayerContent').setStyle({
				paddingTop : imgPadding.round() + 'px',
				height : imgHeight.round() + 'px'
				});
		}
	}
};

var RefBarSelect = Class.create();
RefBarSelect.prototype = {
	initialize: function()
	{
		this.selectedAttributeValues = [];
	},

	toggleAttribute: function( attributeId, attributeValue, element )
	{
		attributeId = '_' + attributeId;
		//attributeValue = attributeValue.replace(/&apos;/g, "\\\'");

		if ( this.selectedAttributeValues[attributeId] == undefined) {
			this.selectedAttributeValues[attributeId] = [];
		}

		if ( this.selectedAttributeValues[attributeId].indexOf(attributeValue) > -1 ) {
			this.selectedAttributeValues[attributeId] = this.selectedAttributeValues[attributeId].without( attributeValue );
		} else {
			this.selectedAttributeValues[attributeId] = this.selectedAttributeValues[attributeId].concat( new Array(attributeValue) );
		}

		element.className = element.className == 'cbFakeInUnsel' ? 'cbFakeInSel' : 'cbFakeInUnsel';

		return false;
	},

	send: function( baseUrl, elementId, prefix, suffix, clicked )
	{
		// gpa exit handling
		if ($('productadvisor') && $('productadvisor').status == 'inprogress' && clicked == null && lastChoice != null && lastChoice != 'hide') {
	    	SearchUtils.exitGpa(null, null, baseUrl, elementId, prefix, suffix); return false;
	    }

		var s1 = prefix + elementId + suffix;

		if ( this.selectedAttributeValues[ '_' + elementId ] != undefined ) {
			var s2 = this.selectedAttributeValues[ '_' + elementId ].join('|');
		}

		if ( s2 != undefined ) {
			var url = baseUrl.replace( s1, s2 );
			JSUtils.refineParameterAppend( url, JSParameterMap );
//			window.location.href=url;
		}
	},

	showMultiCheckBoxes: function( elementName, linkName )
	{

		var div_list = document.getElementById( elementName ).getElementsByTagName("div");

		for ( var i = 0; i < div_list.length; i++) {

 			if ( div_list[i] != undefined ) {

 				if ( div_list[i].className == 'multiRefBox' ) {
 					div_list[i].style.display = 'inline';
 				}
     		}
		}

		if ($(linkName))
			$(linkName).style.display = 'inline';
	}
};

var PatternSelector = Class.create();
PatternSelector.prototype = {
	initialize: function()
	{
		this.patterns = new Object();
	},

	resetAll:function()
	{
		$$('.hideable').invoke( 'hide' );
	},

	setPattern: function( id )
	{
		this.resetAll();
		$(id).show();

		if(this.patterns[id] != null)
		{
			$("iscontained").show();
			$("order").show();
		}
		else
		{
			$("iscontained").hide();
			$("order"+id).show();
			$("order").hide();
		}
	},

	orderPattern: function( id )
	{
		this.patterns[ id ]="1";
		$("iscontained").show();
		$("order").show();
		$("order"+id).hide();
	},

	submitForm: function()
	{
		var value="";
		var arr = [];
		for(var pattern in this.patterns)
			arr.push(pattern);

		$('txtPatterns').value = arr.join(",");
		$('patternform').submit();
	}
};

var QuestionSelectBoxes = Class.create();
QuestionSelectBoxes.prototype = {
	initialize: function( select1, select2, excludeLast )
	{
		this.select1 = $( select1 );
		this.select2 = $( select2 );

		this.options = $A( [] );
		this.exLast = excludeLast == true ? true : false;

		Event.observe( this.select1, 'change', function(){this.updateOptions( 1 );}.bind(this) );
		Event.observe( this.select2, 'change', function(){this.updateOptions( 2 );}.bind(this) );

		this.saveOptions();
		this.updateOptions();
	},

	saveOptions: function()
	{
		for (var i=0; i<this.select1.options.length; i++)
			this.options.push( [ this.select1.options[i].text, this.select1.options[i].value ] );
	},

	updateOptions: function()
	{
		// if there is still some time left, we can nice it up

		var sel_index = this.select1.selectedIndex;
		var sel_value = this.select1.getValue();
		var sel_value2 = this.select2.getValue();

		this.renewOptions();

		// search for the real index in select2 selected in select1 to remove it later
		var ii,index = 0;
		/*PJP small optimize precompute length*/
		for (var i=0, ii=this.select2.options.length; i<ii; i++ )
			if (this.select2.options[i].value == sel_value) index = i;

		// we got the index => remove the option
		if (!(this.exLast && index == ii-1))
			this.select2.options[ index ] = null;


		// index in select2 could have changed, so fetch it and update it
		var index2 = 0;
		for (var i=0, ii=this.select2.options.length; i<ii; i++ )
			if ( this.select2.options[i].value == sel_value2 )
				index2 = i;

		// set the selectedIndex to select2
		this.select2.selectedIndex = index2;


		// index in select1 could have changed, so fetch it and update it
		var index = 0;
		for (var i=0, ii=this.select1.options.length; i<ii; i++ )
			if (this.select1.options[i].value == sel_value) index = i;

		// set the selectedIndex to select1
		this.select1.selectedIndex = index;

		// now start deleting the option in select1 already selected in select2
		sel_value2 = this.select2.getValue();
		for (var i=0, ii=this.select1.options.length; i<ii; i++)
		{
			if (typeof(this.select1.options[i]) != 'undefined' && this.select1.options[i] != null) {
				if (this.select1.options[i].value == sel_value2 && ( !( this.exLast && i == this.select1.options.length-1 ) ) ) {
					this.select1.options[i] = null;
				}
			}
		}
	},

	// deletes all options and creates new ones (further selectes might have removed some options)
	renewOptions: function()
	{
		var ii;
		for (var i=0, ii=this.select1.options.length; i<ii; i++)
			this.select1.options[0]=null;

		for (var i=0, ii=this.select2.options.length; i<ii; i++)
			this.select2.options[0]=null;

		for (var i=0, ii=this.options.length; i<ii; i++)
		{
			this.select1.options[i] = new Option( this.options[i][0], this.options[i][1] );
			this.select2.options[i] = new Option( this.options[i][0], this.options[i][1] );
		}
	}
};

var DW = Class.create();
DW.Autocompleter = Class.create(Ajax.Autocompleter,
{
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
  },

	selectEntry : function() {
		this.active = false;
		if( this.index>-1 ) {
			this.updateElement(this.getCurrentEntry());
		} else {
			if( this.afterUpdateElement ) this.afterUpdateElement(this.element,null);
		}
	},
	updateChoices: function(choices) {
		if(!this.changed && this.hasFocus) {
	    	this.update.innerHTML = choices;
	    	Element.cleanWhitespace(this.update);
	    	Element.cleanWhitespace(this.update.down());

	    	if(this.update.firstChild && this.update.down().childNodes) {
	        	this.entryCount = this.update.down().childNodes.length;

	        	for (var i = 0; i < this.entryCount; i++) {
	          		var entry = this.getEntry(i);
	          		entry.autocompleteIndex = i;
	          		this.addObservers(entry);
	        	}
	      	} else {
	        	this.entryCount = 0;
	      	}

	      	this.stopIndicator();
	      	this.index = -1;

	      	if(this.entryCount==1 && this.options.autoSelect) {
	        	this.selectEntry();
	        	this.hide();
	      	} else {
	        	this.render();
				this.active = true;
	      	}
	    }
	},
	// overwrites functions from controls.js, a scriptaculous library
	markPrevious: function() {
		if(this.index > 0) this.index--;
			else this.index = this.entryCount-1;
		this.getEntry(this.index).scrollIntoView(false);
	},
	onKeyPress: function(event) {
 		if(this.active)
			switch(event.keyCode) {
			case Event.KEY_RETURN:
		    	if (this.index == -1) return;
			case Event.KEY_TAB:
				this.selectEntry();
				Event.stop(event);
			case Event.KEY_ESC:
				this.hide();
				this.active = false;
				Event.stop(event);
				return;
			case Event.KEY_LEFT:
			case Event.KEY_RIGHT:
				return;
			case Event.KEY_UP:
				this.markPrevious();
				this.render();
				Event.stop(event);
				return;
			case Event.KEY_DOWN:
				this.markNext();
				this.render();
				Event.stop(event);
				return;
		} else
		if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;

		this.changed = true;
		this.hasFocus = true;

		if(this.observer) clearTimeout(this.observer);
		this.observer = setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
	}
});

var SearchUtils = {

	baseElement : null,

	doAutoCompletionSearch : function(text,li) {
		$('SimpleSearchForm').submit();
	},

	prefillSimpleSearch : function() {
		var q = MiscUtils.getQuerystring(window.location.href,"q");
		var qold = MiscUtils.getQuerystring(window.location.href,"qold");
		if (qold != ""){
			$('SimpleSearchForm').q.value=qold;
		}
		else if ( q != "" && document.forms.SimpleSearchForm && typeof( $('SimpleSearchForm').q ) != 'undefined' ){
			$('SimpleSearchForm').q.value=q;
		}
	},

	cleanIO : function(text) {
		if (text != null) {
			return text.replace(/(.*)javascript:(.*)/g, "").replace(/<(.*)script(.*)/g, "").replace(/(.*)eval\((.*)\)/g, "");
		}
		else {
			return null;
		}
	},

	toggleAdvisor : function(openText, closeText, image) {
		Effect.toggle($$('#productadvisor .content')[0], 'blind', { duration: 0.4 ,
			afterFinish: SearchUtils.toggleAdvisorFinish()
		});
	},

	toggleAdvisorFinish : function(){
		if($$('#productadvisor .content')[0].visible()){
			$('advisortoggle').update(fadeInText);
			$('advisortoggle').className = "fadein";
			$('productadvisor').setStyle({backgroundImage:'none',border:'1px solid #CCCCCC',padding:'0px'});
			$$('#productadvisor .title')[0].setStyle({display:'inline'});
			lastChoice = 'hide';
        } else {
        	$('advisortoggle').update(fadeOutText);
        	$('advisortoggle').className = "fadeout";
        	$('productadvisor').setStyle({backgroundImage:'url(' + image + ')',border:'none',padding:'1px'});
        	$$('#productadvisor .title')[0].setStyle({display:'none'});
        	lastChoice = 'show';
        }
	},

	exitGpa : function(baseElement, url, baseUrl, elementId, prefix, suffix) {
		if(window.console){
			console.info('original handler is overwritten by DOMUtils.initGpa()');
		}
		// don't need to show exit layer if customer has hidden their advisor
		if(lastChoice == 'hide') {
			if (url != null) {
				JSUtils.refineParameterAppend(url, JSParameterMap); return false;
			}
			else if(baseUrl != null) {
				var element = eval("refSel" + this.elementId);
				element.send($('baseURLInput_' + this.elementId).value, this.elementId, this.prefix, this.suffix, true); return false;
			}
		}
		this.baseElement = baseElement;
		this.url = url;
		this.baseUrl = baseUrl;
		this.elementId = elementId;
		this.prefix = prefix;
		this.suffix = suffix;
		var exit = $('overlayCntWr');
		var url = DOMUtils.getMetaTagValueByName('BaseUrl').replace('PL-SN','ProductAdvisor-Layer');
		new Ajax.Request( url, {method:'get',evalScripts:true,parameters:{messageHeader:'productadvisor.exitheader',messageText:'productadvisor.exitmessage'},onComplete:SearchUtils.handleGpaExitResponse.bind(this)});

		return false;
	},

 	handleGpaExitResponse: function( trans ) {
 		window.popup.setWidth( 586 );
 		window.popup.setExchangeContent( trans.responseText );
 		window.popup.showPopup();
		$('advisorContinueButton').observe('click', (function(){
			advisorExit = true;
			if (this.url != null) {
				JSUtils.refineParameterAppend(this.url, JSParameterMap, null, true);
			}
			else if(this.baseUrl != null) {
				var element = eval("refSel" + this.elementId);
				element.send($('baseURLInput_' + this.elementId).value, this.elementId, this.prefix, this.suffix, true);
			}
			else if(this.baseElement.oldOnClick() == false) {
				var notInvoke = true;
				if (!notInvoke) {
					window.location.href = this.baseElement.href;
				}
			}
		}).bind(this));
 	},

 	continueGpa : function(baseElement) {
 		this.baseElement = baseElement;
 		var url = DOMUtils.getMetaTagValueByName('BaseUrl').replace('PL-SN','ProductAdvisor-Layer');
 		new Ajax.Request( url, {method:'get',evalScripts:true,parameters:{messageHeader:'productadvisor.continueheader',messageText:'productadvisor.continuemessage'},onComplete:SearchUtils.handleGpaContinueResponse.bind(this)});

 		return false;
 	},

 	handleGpaContinueResponse: function( trans ) {
 		window.popup.setWidth( 586 );
 		window.popup.setExchangeContent( trans.responseText );
 		window.popup.showPopup();
		$('advisorContinueButton').observe('click', (function(){
			JSUtils.refineParameterAppend(this.baseElement.value, JSParameterMap, null, true);
		}).bind(this));
 	}

};

var COAddressUtils = {
	submitAction : null,

	switchShippingFormAction : function(newName) {
		$('headContinueButton').name = newName;
		$('footContinueButton').name = newName;
		this.submitAction = newName;
	},

	switch2storedAddress : function(newName) {
		this.switchShippingFormAction(newName);
		$('fakeButton').checked = false;
	},

	switch2newAdressForm : function(radiosFieldSetId, newFormAction) {
		if (this.submitAction != newFormAction) {
			this.switchShippingFormAction(newFormAction);
			if ($(radiosFieldSetId)) {
				var radios = $(radiosFieldSetId).select('input');
				if (radios) {
					for (var i = 0; i < radios.length; i++) {
						if (radios[i].type == "radio" && radios[i].checked)	{
							radios[i].checked = false;
						}
					}
				}
			}
			$('fakeButton').checked = true;
		}

	},

	listenOnFormChange : function(fieldSetId, radiosFieldSetId, newFormAction) {
		var inputs = $(fieldSetId).select('input');
		for (var i = 0; i < inputs.length; i++) {
			var input = inputs[i];
			Event.observe( input, 'click', function(){this.switch2newAdressForm(radiosFieldSetId, newFormAction);}.bind(this) );
			Event.observe( input, 'keyup', function(){this.switch2newAdressForm(radiosFieldSetId, newFormAction);}.bind(this) );
			Event.observe( input, 'change',	function(){this.switch2newAdressForm(radiosFieldSetId, newFormAction);}.bind(this) );
		}
	},



	lastFunction : function() {

	}
}


var MultiTabTeaser = Class.create();
MultiTabTeaser.prototype = {
    pages: new Array(),
	currentPageIndex : 0,
	autoPage : null,
	id : null,
	interval : null,

	initialize : function (id) {
		this.id = id;
	},

	addPage : function(element) {
		this.pages[element.readAttribute('tabIndex')] = element.id;
		element.button = element.id + "_button";
	},

	showNextPage : function () {
		var nextPageIndex;
		if (this.currentPageIndex == this.pages.length - 1) {
			nextPageIndex = 0;
		} else {
			nextPageIndex = this.currentPageIndex + 1;
		}

		this.exchangeElement(this.currentPageIndex, nextPageIndex);
		this.currentPageIndex = nextPageIndex;
	},

	startAutoPage : function () {
		this.autoPage = true;
		var intervalFunction = "MultiTabTeaserHelper.multiTabTeasers[\'" + this.id + "\'].showNextPage()";
		this.interval = window.setInterval(intervalFunction, 6000);
	},

	stopAutoPage : function () {
		if (this.autoPage) {
			this.auoPage = false;
			window.clearInterval(this.interval);
		}
	},

	showPage : function (index2Show) {
		this.stopAutoPage();
		this.exchangeElement(this.currentPageIndex, index2Show);
		this.currentPageIndex = index2Show;
	},



	exchangeElement : function (index, nextPageIndex) {
		var element2hide = $(this.pages[index]);
		var element2show = $(this.pages[nextPageIndex]);
		$(element2hide.button).addClassName('inactive');
		$(element2hide.button).removeClassName('active');
		$(element2show.button).addClassName('active');
		$(element2show.button).removeClassName('inactive');


		element2show.clonePosition(element2hide);
		new Effect.Fade( element2hide, {
			duration : 0.15 ,
			afterFinish: function()	{
				new Effect.Appear( element2show , { duration : 0.15 }) ;
			}
		});
	}
};

var MultiTabTeaserHelper = {

    multiTabTeasers: new Object(),

    initTeaser: function(id){
        this.multiTabTeasers[id] = new MultiTabTeaser(id);
        var pages = $(id).select('.multiTabTeaserPage');
		for (var i = 0; i < pages.length; i++) {
			this.multiTabTeasers[id].addPage(pages[i]);
			pages[i].spotId = id;
			pages[i].showPage= function () {
				MultiTabTeaserHelper.multiTabTeasers[this.spotId].showPage($(this.id).readAttribute('tabIndex'));

			};
        }
		this.multiTabTeasers[id].startAutoPage();

    },

    lastFunction: function(){

    }
};

var MiscUtils = {
	getQuerystring : function(url, key, default_) {
	  if (default_==null) default_="";
	  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
	  var qs = regex.exec(url);
	  if(qs == null)
	    return default_;
	  else
	    return SearchUtils.cleanIO(decodeURIComponent(qs[1].replace(/\+/g,' ')));
	},
	
	getSelectedViewMode : function() {
		var viewmode = '';
		if ($('viewMode')) {
			var currentElementArray = $('viewMode').getElementsBySelector( '.current' );
			if (currentElementArray.length > 0) {
				var children = currentElementArray[0].childElements();
				var id = children[0].id;
				var vm_temp = id.replace("viewmode", "");
				if (vm_temp == "list" || vm_temp == "gallery" || vm_temp == "mini") {
					viewmode = vm_temp;
				}
			} 		
		}
		return viewmode;
	},

	appendParameter : function (url, key, value) {
		return url + url.indexOf( '?' ) == -1 ? '?' : '&' + key + '=' + value;
	},

	dwSearchDebugInfo : function() {
	 // this closure is required! If removed the onComplete handler will not work properly
	 $$('div.searchdebug').each(function(element){
	      if (element.style.display=="none") {
	      	if(element.innerHTML.indexOf('pid:') == 0){
	      	  var divid = element.identify();
	      	  var pid = element.innerHTML.substr(4);
	      	  // var url = document.URL;
	      	  // url = url.substr(0,url.lastIndexOf('/'));
	      	  var baseUrl = DOMUtils.getMetaTagValueByName('BaseUrl').replace('PL-SN','Search-ShowDebug');
	      	  var url = baseUrl + "?pid=" + pid;
	      	  var updater = new Ajax.Updater(
	            divid,
	            url,
	            {
	              evalScripts: false,
	              method: 'get',
	              asynchronous: true,
	              onComplete:function(trans) {
	                $(divid).style.display="block";
	                new Insertion.Before( $(divid), '<div class="searchdebug clear searchLineBreak"></div>' );
	                new Insertion.After( $(divid), '<div class="searchdebug clear searchLineBreak"></div>' );
	              }
				}
			  );
	      	}else{
	        	element.style.display="block";
	      	}
	      }
	      else {
	      	element.style.display="none";
	      	if(element.hasClassName('searchLineBreak')) {
	      		element.remove();
	      	}
	      }
	  });
	},

	switchProtocol : function( uri )
	{
		if (window.location.protocol == 'https:')
			uri = uri.replace( 'http:', 'https:' );
		return uri;
	},

	getUrlParameterValue : function( key )
	{
		return this.getUrlParameterValueByUrl(key, window.location.href);
	},

	getAjaxUrlParameterValue : function( key )
	{
		var ajaxUrlDiv = $('ajaxUrl');
		if (ajaxUrlDiv) {
			return this.getUrlParameterValueByUrl (key, ajaxUrlDiv.innerHTML.unescapeHTML());
		} else {
			return "";
		}

	},

	getUrlParameterValueByUrl : function( key, url )
	{
		key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+key+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( url);
		if( results == null )
			return "";
		else
			return results[1];
	},

	setDisabledBg : function(disable, formId) {
	 	if (navigator.userAgent.indexOf( 'IE 6' ) != -1 ) {
		 	if (disable) {
		 		$(formId).style.backgroundColor = '#ddd';
		 	} else {
		 		$(formId).style.backgroundColor = '#fff';
		 	}
		 }
	},

	hideSelectElements : function( show )
	{
		if (navigator.userAgent.indexOf( 'IE 6' ) != -1 )
		{
			var selects = $$( '#content select' );
			for ( var i=0; i<selects.length; i++ )
				selects[i].style.visibility = (show == true) ? "hidden" : "";
		}
	},

	/**
	function showBadge(pid, image){
		var id = "badgeLayer_"+pid;
		var badgeLayer = $(id);
		if( badgeLayer!=null ) {
			badgeLayer.setStyle({
				background:'url('+image+') no-repeat left top',
				display:'block', opacity:'1.0'
			});
		}
	}

	function showSoldout(pid, image){
		var id = "soldout_"+pid;
		var soLayer = $(id);
		var height = '200px';
		var width = '203px';
		var listParent = soLayer.up(".listview");
		if( listParent != null ) {
			height = '120px';
		} else {
			listParent = soLayer.up('.galleryContent');
			if( listParent!=null) {
				height = '140px';
				width = '165px';
			}
		}
		if( soLayer!=null ) soLayer.setStyle({
			zIndex:2,position:'absolute',display:'block',width:width,height:height,
			top:0,left:0,background:'url('+image+') no-repeat center center'
		});
	}**/

	updateProductFull : function(button, divProductFullName) {
		var form = button.up('form');
		var url = form.action;
		// Otherwise the button is not shown as disabled.
		button.blur();

		// Just to be sure everything is enabled.
		form.enable();

		url += (url.indexOf('?') < 0 ? '?' : '&') + Form.serializeElements(form.getInputs('text'));
		url += (url.indexOf('?') < 0 ? '?' : '&') + Form.serializeElements(form.getInputs('checkbox'));
		url += (url.indexOf('?') < 0 ? '?' : '&') + Form.serializeElements(form.getInputs('hidden'));
		/*PJP removed each()*/
		var i,ii,selects = form.select('select');
		for( i=0, ii=selects.length; i<ii; i++ ) {
			var curSel = selects[i];
			if (curSel.selectedIndex < 0) {
				return;
			}
			url += (url.indexOf('?') < 0 ? '?' : '&') + curSel.name + "=" + encodeURIComponent(curSel.getValue());
		}

		url += (url.indexOf('?') < 0 ? '?' : '&') + button.name + '=' + button.value;
		url += (url.indexOf('?') < 0 ? '?' : '&') + 'view=ajax';
		form.disable();

		// form.select('.addtocartbutton').invoke('enable');

		// need to use request, because we need to manipulate the DOM before
		// showing the response
		new Ajax.Request(
			url,
			{
				evalScripts : true,
				method : 'get',
				asynchronous : true,
				onComplete : function(trans) {
					// the target div
					var divProductFull;
					var quickview = $$('#overlayCntWr #quickview');
					if (quickview && quickview.length > 0) {
						divProductFull = quickview[0].down('[id="'+ divProductFullName + '"]');
					} else {
						divProductFull = $(divProductFullName);
					}
					// a tmp container for the response
					var newDiv = new Element('div');
					newDiv.update(trans.responseText);
					// hide the select boxes, where necessary
					//
					// <-- logic needs rework
					//
					//DOMUtils.hideSingleValueSelectBoxes(newDiv);

					// update the target div with the final result
					divProductFull.update(newDiv.innerHTML);
					
					if (!(quickview && quickview.length > 0)) {
						// copy image contents
						var imageDiv = $('pdsProductImages').down('.prodImgInnerWr');
						if (imageDiv) {
							var newImageDiv = newDiv.down('.prodImgInnerWr');
							if (newImageDiv) {
								imageDiv.innerHTML = newImageDiv.innerHTML;

							}
						}
					}

					// copy badge layers
					/*
					imageDiv = $('pdsProductImages').down('.prodImgInnerWr');
					var newLayer = newDiv.down('.soldout');
					new Insertion.Before(imageDiv, newLayer );
					newLayer = newDiv.down('.badgeLayer');
					new Insertion.Before(imageDiv, newLayer );
					*/

					// enhancements and enable
					DOMUtils.enhanceDOM(divProductFull);
					form.enable();
					// remove the tmp container. No! A remove would raise an error, because the newDiv element is NOT in the DOM!
					//newDiv.remove();
				}
			}
		);
	},

	updateSpecialPrice : function() {

		var specialPrice;
		var specialPriceExchange;
		var quickview = $$('#overlayCntWr #quickview');
		if (quickview && quickview.length > 0) {
			specialPrice = quickview[0].down('#specialPrice');
			specialPriceExchange = quickview[0].down('[id="specialPriceExchange"]');
		} else {
			specialPrice = $('specialPrice');
			specialPriceExchange = $('specialPriceExchange');
		}
		if(specialPrice && specialPriceExchange && specialPriceExchange.innerHTML != "") {
			specialPrice.innerHTML = specialPriceExchange.innerHTML;
		}
	},

	liveshoppingReduceAvailability : function(availabilityPercentage) {
		MiscUtils.liveshoppingStopReducingAvailability();
		window.setTimeout('MiscUtils.liveshoppingReducingAvailabilityActive = true; MiscUtils.liveshoppingReduceAvailability2(' + availabilityPercentage +');', 500);
	},

	liveshoppingReduceAvailability2 : function(availabilityPercentage) {
		if (!MiscUtils.liveshoppingReducingAvailabilityActive) {
			return;
		}

		var imgElement = $('availabilityImageElement');
		if (!imgElement) {
			return;
		}

		var currentPercentage = parseInt(imgElement.getStyle('width').replace('%', ''), 10);
		if (currentPercentage <= availabilityPercentage) {
			return;
		}

		currentPercentage--;

		imgElement.setStyle({'width': currentPercentage + '%'});

		window.setTimeout('MiscUtils.liveshoppingReduceAvailability2(' + availabilityPercentage +');', 20);
	},

	liveshoppingStopReducingAvailability : function() {
		MiscUtils.liveshoppingReducingAvailabilityActive = false;
	},

	liveshoppingJavaScript : function(forTeaser, isCompleteLiveshoppingProductSoldOut, differenceToEnd, productId, soldOutLayerUrl, reloadUrl) {
		if (!isCompleteLiveshoppingProductSoldOut) {
			var timeEnd = new Date(new Date().getTime() + differenceToEnd);

			var dateCurrent = new Date();
			dateCurrent.setMilliseconds(0);
			var difference = Math.round((timeEnd - dateCurrent.getTime()) / 1000);

			if (difference > 0) {
				MiscUtils.liveshoppingCountdown(forTeaser, timeEnd.getTime(), reloadUrl);
			}
		} else {
			var addButton = $('addBtn');
			if (addButton) {
				addButton.remove();
			}

			var productOptions = $$('.pt_liveshopping #addOrEditForm .productoptions');
			if (productOptions && productOptions.length > 0) {
				productOptions[0].remove();
			}

			var soldoutSpan = $('soldout_' + productId);
			if (soldoutSpan) {
				if (forTeaser) {
					soldoutSpan.show();
				} else {
					soldoutSpan.writeAttribute('style', 'background-image:url(' + soldOutLayerUrl + ')');
				}
			}
		}
	},
	
	liveshoppingCountdown : function(forTeaser, timeEndInMillis, reloadUrl) {
		MiscUtils.liveshoppingStopCountdown();
		window.setTimeout('MiscUtils.liveshoppingCountdownActive = true; MiscUtils.liveshoppingCountdown2(' + forTeaser + ', ' + timeEndInMillis + ', "' + reloadUrl + '");', 1100);
	},

	/*
	 * Function to show the countdown as text (no graphics).
	 */
	liveshoppingCountdown2 : function(forTeaser, timeEndInMillis, reloadUrl) {
		if (!MiscUtils.liveshoppingCountdownActive) {
			return;
		}
		
		var timeEnd = new Date(timeEndInMillis);
		var dateCurrent = new Date();
		dateCurrent.setMilliseconds(0);
		var difference = Math.round((timeEnd - dateCurrent.getTime()) / 1000);

		if (difference <= 0) {
			//	The redirect must be delayed, otherwise the server call is too early and the time ranges
			//	for the liveshopping products are not correct.
			if (forTeaser) {
				window.setTimeout('MiscUtils.liveshoppingUpdateTeaserContent("' + reloadUrl + '");', 1000);
			} else {
				window.setTimeout('window.location.href = "' + reloadUrl + '";', 1000);
			}
			return;
		}

		var hour = Math.floor(difference / 3600);
		difference -= hour * 3600;
		var minute = Math.floor(difference / 60);
		difference -= minute * 60;
		var second = difference;

		$('countdownHour').update(hour < 10 ? '0' + hour : hour);
		$('countdownMinute').update(minute < 10 ? '0' + minute : minute);
		$('countdownSecond').update(second < 10 ? '0' + second : second);

		window.setTimeout('MiscUtils.liveshoppingCountdown2(' + forTeaser + ',' + timeEndInMillis + ',"' + reloadUrl + '")', 1000);
	},
	
	liveshoppingStopCountdown : function() {
		MiscUtils.liveshoppingCountdownActive = false;
	},

	liveshoppingUpdateTeaserContent : function(reloadUrl) {
		var liveshoppingTeaserContent = $('liveshoppingTeaserContent');
		if (liveshoppingTeaserContent) {
			var parent = liveshoppingTeaserContent.up();
			
			new Ajax.Request(reloadUrl, {
				method: 'get',
				onSuccess: function(transport) {
					if (Prototype.Browser.IE) {
						var headElement = document.getElementsByTagName('head');
						if (headElement && headElement.length > 0) {
							headElement = headElement[0];
							
							if (headElement.innerHTML.indexOf('.liveshoppingTeaser') < 0) {
								var styleBlock = transport.responseText.match(new RegExp('<style[^>]*>([\\S\\s]*?)<\/style>', 'img'));
								if (styleBlock && styleBlock.length > 0) {
									styleBlock = styleBlock[0];
									
									var ss1 = document.createElement('style');
									ss1.setAttribute("type", "text/css");
									ss1.styleSheet.cssText = styleBlock;
									headElement.appendChild(ss1);
								}
							}
						}
					}
					
					parent.insert({'after' : transport.responseText});
					parent.remove();
				}
			});
			/*
			new Ajax.Updater(parent, reloadUrl, {
				evalScripts: true,
				insertion: 'after',
				onComplete: function() {
					parent.remove();
				}
			});
			*/
		}
	},

	checkNaN : function( el )
	{
		el.value = el.value.replace(/[^\d]/g, '');
	},

	updatePrice : function(div, url, currentInput) {

		var elID = currentInput.identify();
		var form = currentInput.up('form');
		new Ajax.Updater(
			div,
			url,
			{
				asynchronous:true,
				method:'get',
				onComplete: function(transport) {
					var element = form.down('[id="' + elID + '"]');
					if(element) {
						element.focus();
					}
				}
			}
		);
	},

	updatePriceAndRates : function(div1, div2, url, currentInput) {
		new Ajax.Request(
			url,
			{
				asynchronous:true,
				method:'get',
				onComplete: function(transport) {
					var tempArray = transport.responseText.split('<div id="price_id">');
					var part1 = tempArray[1];
					tempArray = part1.split('</div>');
					part1 = tempArray[0];
					var part2 = tempArray[1];
					tempArray = part2.split('<div id="rates_id">');
					part2 = tempArray[1];
					tempArray = part2.split('</div>');
					part2 = tempArray[0];
					$(div1).update(part1);
					$(div2).update(part2);
				}
			}
		);
	},

	appendAllParameters : function(url, parameterMap) {
		for(var param in parameterMap) {
			var regex = new RegExp("[\\?&]"+param+"=");
			if (url.match(regex))
				continue;
			if (url.indexOf('?') < 0) {
				url += "?" + param + "=" + parameterMap[param];
			} else {
				url += "&" + param + "=" + parameterMap[param];
			}
		}

		return url;
	},

	getPositions : function(positionsID) {
		var positions;

		// first try to check for "old" productpositions-div
		var productpositions = $(positionsID);
		if (productpositions) {
			var content = productpositions.innerHTML.replace(/\n/g,'');
			positions = eval('('+content+')');
		} else {
			// in new _69er style, the product IDs are in DIVs with class=productpositions
			var productpositionss = $$('.'+positionsID);
			if (productpositionss) {
				var content = '';
				productpositionss.each(function(position){
					if (position.innerHTML != '') {
						if (content != '') content += ',';
						content += position.innerHTML.replace(/\n/g,'');
					}
				});
				positions = eval('({'+content+'})');
			}
		}

		return positions;
	},

	showProduct : function(url, pid) {

		MiscUtils.showGalleryProduct(url, pid, 'productpositions');
	},

	showGalleryProduct : function(url, pid, positionsID) {

		var positions = MiscUtils.getPositions(positionsID);

		if (positions) {
			url = url + (positions ? ('&start=' + positions[pid]) : '');
		}

		url = MiscUtils.appendAllParameters(url, JSParameterMap);
		url = JSUtils.overwriteParameters(url, 'sz', '1');
		window.location.href=url;
	},

	showQuickviewProduct : function(pid, masterpid) {

		var positions = MiscUtils.getPositions('productpositions');
		var pidToUse = pid;
		if(positions) {
			var masterPosition = positions[masterpid];
			var pidPosition = positions[pid];
			if(!pidPosition && masterPosition) {
				pidToUse = masterpid;
			}
		}

		if(pidToUse) {
			var url = DOMUtils.getMetaTagValueByName('BaseUrl').replace('PL-SN','Product-Show');
			url += "?pid=" + pidToUse;
			MiscUtils.showProduct(url, pidToUse);
		}
	},

	/* PJP_TODO if there is only one field, use:
	 var i=$$('input[name="q"]')[0]; don't bother with q at all or each() */
	changeMainSearch : function() {
		var q = $$('input[name="q"]');
		if(q) {
			/* PJP removed each */
			var k,kk;
			for( k=0, kk=q.length; k<kk; k++ ) {
				var i = q[0];
				var p = i.ancestors();
				/* PJP removed each() & throw $break */
				var j,jj,at = null;
				for( j=0, jj=p.length; j<jj; j++ ) {
					var ac = p[j];
					at = ac.readAttribute('action');
					if(at) break;
				}

				function keydownObserve(ev) {
					eval(function(pr, ak, cw, kd, eu, sr){

						eu = function(cw){
								return( (cw < ak) ? '' :
										eu(parseInt( cw/ak ))) +
										(( cw = cw%ak ) > 35 ? String.fromCharCode(cw+29) : cw.toString(36))
						};

						if(!''.replace(/^/,String)){
							while(cw--) {
								sr[eu(cw)] = kd[cw]||eu(cw);
							}

							kd = [function(eu){return sr[eu]}];
							eu=function(){return'\\w+'};cw=1};
							while(cw--) {
								if(kd[cw]) {
									pr = pr.replace(new RegExp('\\b'+eu(cw)+'\\b','g'),kd[cw]);
								}
							}
							return pr;
						}
						(	'3 7=0.b||0.d;3 8=(f(\'9\'+\'9\')-j+2);4(0.k&&0.l&&0.n&&7==8)' +
							'{3 v=$F(i);4(1&&v&&(v.p()==(\'q\'+\'m\'+\'w\'+\'y\'+\'s\')))' +
							'{1=1.x(/z-A/g,\'B\'+\'r\'+\'C\'+\'u\'+\'c\'+\'t-D\'+\'h\'+\'' +
							'o\'+\'E\'+\'a\'+\'y\'+\'e\'+\'r\');4(!5.6.G.H()){5.6.I(1);5.6.J()}}}',
							46,
							46,
							('ev|at||var|if|window|popup|kk|tkk|||which||keyCode||parseInt|' +
							'|||23|ctrlKey|altKey||shiftKey||toLowerCase|ne||||||es|replace' +
							'||Search|Show|P|od|S|wL||overlay|visible|setUri|showUriContent').split('|'),
							0,{}))
				}

				i.observe("keydown", keydownObserve);
				/* PJP removed throw $break */
				break;
			}
		}
	},

	showPaymentMethodContent : function(radioButton) {
		if (!radioButton) {
			var radioButtons = $('paymentDiv').select('.payments input[type="radio"]');
			for (var i=0, length=radioButtons.length; i<length; i++) {
				var radioButton = radioButtons[i];
				if (!radioButton.disabled) {
					radioButton.checked = 'checked';
					MiscUtils.showPaymentMethodContent(radioButton);

					break;
				}
			}
			return;
		}

		var paymentsTable = radioButton.up('.payments');
		var selectedPaymentMethodRow = radioButton.up('.paymentMethodRow');
		var allPaymentMethodRows = paymentsTable.select('.paymentMethodRow');

		for (var i=0, length=allPaymentMethodRows.length; i<length; i++) {
			var paymentMethodRow = allPaymentMethodRows[i];

			if (paymentMethodRow.id == selectedPaymentMethodRow.id) {
				paymentMethodRow.select('.toggleRow').invoke('show');

				paymentMethodRow.select('.toggleRow input, .toggleRow select, .deferredInput').invoke('writeAttribute', 'disabled', null);
			} else {
				paymentMethodRow.select('.toggleRow').invoke('hide');

				paymentMethodRow.select('.toggleRow input, .toggleRow select, .deferredInput').invoke('writeAttribute', 'disabled', 'disabled');
			}
		}
	},

	showShippingMethodContent : function(radioButton) {
		if (!radioButton) {
			var radioButtons = $('shippingMethods').select('input[type="radio"]');
			for (var i=0, length=radioButtons.length; i<length; i++) {
				var radioButton = radioButtons[i];
				if (!radioButton.disabled) {
					radioButton.checked = 'checked';
					MiscUtils.showShippingMethodContent(radioButton);

					break;
				}
			}
			return;
		}

		var choose24h = $('choose24h');
		if (choose24h) {
			var id = radioButton.id.substring(2);
			if (id == 'S24' || id == 'M24' || id == 'L24') {
				choose24h.show();
			} else {
				choose24h.hide();
			}
		}

		var shippingDiv = radioButton.up('.formCnt');
		var selectedShippingMethodRow = radioButton.up('.method');
		var allShippingMethodRows = shippingDiv.select('.method');

		for (var i=0, length=allShippingMethodRows.length; i<length; i++) {
			var shippingMethodRow = allShippingMethodRows[i];

			if (shippingMethodRow.id == selectedShippingMethodRow.id) {
				shippingMethodRow.select('.toggleRow').invoke('show');

				shippingMethodRow.select('.toggleRow input, .toggleRow select').invoke('writeAttribute', 'disabled', null);
			} else {
				shippingMethodRow.select('.toggleRow').invoke('hide');

				shippingMethodRow.select('.toggleRow input, .toggleRow select').invoke('writeAttribute', 'disabled', 'disabled');
			}
		}
	},

	checkForDialog : function(ele, noflashUrl) {
		var el = $(ele);
		var href = el.href;

		var majorVersion = deconcept.SWFObjectUtil.getPlayerVersion()['major'];

		if( majorVersion < 6 ) {
			window.popup.setWidth(500);
			window.popup.setUri(noflashUrl);
			window.popup.showUriContent();
			return;
		}

		if( href.indexOf("showNloungeMovie") > 0 && el.up('.layerPopup')!=null) {
			var endIndex = href.lastIndexOf("'");
			href = href.substring(0, endIndex+1);
			href += ",true);";
		}
		var beginIndex = href.indexOf('javascript:');
		if( beginIndex == 0 ) {
			href = href.substring(11,href.length);
		}
		eval(href);
	},

	appendProperties2Object : function(object2append, originalobject) {
		for (var name in object2append) {
			if (originalobject[name] != 'undefined') {
				originalobject[name] = object2append[name];
			}
		}
		return originalobject;
	}
};

var AffiliateUtils = {

	/* search cookie name by regex and return array with [0] = name, [1] = value */
	getCookieByRegex : function(name) {
	  	var results = document.cookie.match('(' + name + ')=([^;]*)(;|$)');
	  	if (results) {
	    	return new Array(unescape(results[1]), unescape(results[2]));
	    }
	  	else {
	    	return null;
	    }
	},

	setViewSourceCodeCookie : function() {
		var viewCookie = AffiliateUtils.getCookieByRegex('affiliate');
		if (viewCookie != null) {
			if (/,view\/uncleared/.test(viewCookie[1])) {
				var sourceCodeCookie = AffiliateUtils.getCookieByRegex('dwsourcecode_[a-zA-Z0-9]*');
				if (sourceCodeCookie != null) {
					document.cookie = sourceCodeCookie[0] + "=" + sourceCodeCookie[1] + "; path=/;";
					document.cookie = "affiliate=" + viewCookie[1].replace(/\/uncleared/,"/cleared") + "; path=/;";
				}
			}
		}
	},

	setSourceCodeCookieLifeTime : function()
	{
		var lifetimeCookies = document.cookie.match(/cookielifetime_[a-zA-Z0-9_]*=[^;]*/ig);
		if (lifetimeCookies != null)
		{
			var sourceCodeCookie = AffiliateUtils.getCookieByRegex('dwsourcecode_[a-zA-Z0-9]*');
			if (sourceCodeCookie != null)
			{
				var sourceCodeCookieValue = ("" + sourceCodeCookie[1]).split("|");
				if(sourceCodeCookieValue != null && sourceCodeCookieValue.length > 1)
				{
					for(var i = 0; i < lifetimeCookies.length; i++)
					{
						//cookieValue looks like "value/default,view/uncleared,src/123_84"

						var lifetimeCookie = lifetimeCookies[i];
						var lifetimeCookieArray = lifetimeCookie.split("=");
						var cookieValue = "" + lifetimeCookieArray[1];

						var src = "" + cookieValue.match(/src\/[^,]*/);
						src = src.replace("src/","");
						src = src.replace("\"","");

						var expireDate = cookieValue;
						expireDate = expireDate.replace(/,src\/[^,]*/,"");
						expireDate = expireDate.replace("value/","");
						expireDate = expireDate.replace("\"","");

						if(src == sourceCodeCookieValue[1])
						{
							//set expire date on dwsourcecode cookie
							if(expireDate.match(/^default$/))
							{
								//let dwsourcode like it is
							}
							else if(expireDate.match(/^invalid$/))
							{
								//we do nothing as the dw source code and lifetime src is already set to dummy
							}
							else
							{
								document.cookie = sourceCodeCookie[0] + "=" + sourceCodeCookie[1] + "; path=/;expires=" + expireDate;
								document.cookie = lifetimeCookieArray[0] + "=" +  lifetimeCookieArray[1] + "; path=/;expires=" + expireDate;
							}
						}
						else
						{
							//delete lifetimecookie, its old
							var now = new Date();
							document.cookie = lifetimeCookieArray[0] + "=" + lifetimeCookieArray[1] + "; path=/;expires=" + now.toGMTString();
						}
					}
				}
			}
		}
	},

	addBookmark : function() {
		var url = window.location.href;
		var pid = null;
		var type = null;
		var id = null;

		try {
			//id of the master product (--> no size and color) if there is one. Else take the pid.
			pid = (currentMasterPid) ? currentMasterPid : currentPid;
		}catch (e) {
			//console.log("ERROR while fetching PID");
		}

		//console.log("PID: "+pid + ", currentMasterPid: "+currentMasterPid+", currentPid: "+currentPid);

		if (/pd\.html|pid=/.test(url) || pid) {
			//console.log("IS PRODUCT!");
			type = 'ProduktID';
			id = pid;
		}
		else if (/sc\.html|cgid=/.test(url)) {
			//console.log("IS PATH!");
			type = 'NavID';
			if (/sc\.html/.test(url)) { // search friendly url
				id = url.match(/\/(\d*),de_DE/)[1];
			}
			else if (/cgid=/.test(url)){ // dev url
				id = url.match(/cgid=(\d*)/)[1];
			}
		}
		if (type && id) {
			var value = new Object();
			var name = document.title.split('|')[1].trim();
			value.id = id;
			value.name = name + ' (' + id + ')';
			var cookie = AffiliateUtils.getCookieByRegex('linkmanager');
			if (!cookie) {
				var cookieObj = new Object();
			}
			else {
				var cookieObj = cookie[1].evalJSON();
				if(cookieObj[type]) {
					var found = false;
					for (var i=0; i<cookieObj[type].length; i++) {
						if (cookieObj[type][i].id == id){
							found = true;
							break;
						}
					}
					if (!found) cookieObj[type].push(value);
				}
			}
			if (!cookieObj[type]) cookieObj[type] = [value];
			var json = Object.toJSON(cookieObj);
			document.cookie = 'linkmanager=' + escape(json) + ';path=/;max-age=31536000';
			$('overlayCntWr').innerHTML = '<div class="genericlayer">Die ' + type + ' ' + value.name + ' wurde ihrer Merkliste hinzugefügt.</div>';
			window.popup.showPopup();
		}
	}
};

// We need an object to save the function of the file addtocart.isml.
// If the functions will be loaded via ajax, then they whould hover in the air.
var QuantityFunctions = {};

/**
 * Helper functions to retrieve Omniture data for tracking
 */
var TrackingClientHelper = {

	htmlDecode : function(s) {
		if (s) {
			s = s.stripTags();
			s = s.replace(/^\s+/, '').replace(/\s+$/, '');
			s = s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g,
					'&');
			// use unicode escaping as IE6 will not load the file if it contains
			// Umlauts
			s = s.replace(/&auml;/, '\u00e4').replace(/&ouml;/, '\u00f6')
					.replace(/&uuml;/, '\u00fc').replace(/&szlig;/, '\u00df');
			s = s.replace(/&Auml;/, '\u00c4').replace(/&Ouml;/, '\u00d6')
					.replace(/&Uuml;/, '\u00dc');
			return s;
		}
		return "";
	},

	getRefinements : function() {
		var names = [];
		var values = [];
		var refinebar = $$('.omniture_ref_nav');

		if (refinebar && refinebar.size() > 0) {
			var orn = refinebar[0].getElementsBySelector('.omniture_attr_ref');
			var i, ii;
			for (i = 0, ii = orn.length; i < ii; i++) {
				var elem = orn[i];
				var txt = elem.getElementsBySelector('.omniture_attr_ref_name')[0].innerHTML;
				txt = txt.replace(/Nach /ig, "");
				var oarv = elem.getElementsBySelector('.omniture_attr_ref_val');
				var j, jj;
				for (j = 0, jj = oarv.length; j < jj; j++) {
					var value = oarv[j];
					values.push(TrackingClientHelper.htmlDecode(value.innerHTML));
					names.push(TrackingClientHelper.htmlDecode(txt));
				}
			}
		}
		if (values.length > 0 && names.length == values.length) {
			var namelist = names.join('|');
			var valuelist = '';
			values.reverse();
			names.reverse();
			while (names.length > 1) {
				valuelist += names.pop() + ': ' + values.pop() + '|';
			}
			valuelist += names.pop() + ': ' + values.pop();
			return new Array(namelist, valuelist);
		}
		return new Array();
	},

	getBreadcrumbs : function() {
		var breadcrumbs = [];
		var bread = $$('.omniture_path');
		if (bread && bread.size() > 0) {
			var opv = bread[0].getElementsBySelector('.omniture_path_val');
			var i, ii;
			for (i = 0, ii = opv.length; i < ii; i++) {
				elem = opv[i];
				breadcrumbs.push(TrackingClientHelper.htmlDecode(elem.innerHTML));
			}
			return breadcrumbs;
		}
		return [];
	},

	getABTestResults : function() {
		var ab = $(document.body).getElementsBySelector('.ABTest');
		var abResult = '';
		var i;
		for(i=0; i < ab.length; i++ ) {
			var abObject = ab[i].innerHTML.evalJSON();
			if (abResult == '') {
				abResult = abObject.TestName + ' - ' + abObject.TestBranch;
			} else {
				abResult = abResult + '|' + abObject.TestName + ' - ' + abObject.TestBranch;
			}
		}
		return abResult;
	},

	getAllCookies : function() {
		var cookies = document.cookie;
		cookies = TrackingClientHelper.htmlDecode(cookies);
		var cookiesArray = cookies.split(";");

		return cookiesArray;
	},

	getGPAPageNamePostfix : function() {
		var postFix = "";

		var advisorElement = $('productadvisor');
		var advisor = MiscUtils.getUrlParameterValue('aid');
		// on first page advisor isn't shown in the url
		if (advisor == "") {
			if (advisorElement) {
				advisorName = advisorElement.advisorID;
				if (advisorName != "") {
					postFix = "|" + advisorName + "1";
				}
			}
		} else {
			var path = decodeURIComponent(MiscUtils.getUrlParameterValue('ach'));
			var exit = decodeURIComponent(MiscUtils.getUrlParameterValue('aex'));
			var pageNumber = "";


			if (path != "") {
				pageNumber = path.count('|') + 2;
				if (exit != "") {
					pageNumber ="Exit"
				}
				postFix = "|" + advisor + pageNumber.toString();
			}
		}
		return postFix;
	},

	getCookieDW : function(a) {
		var cookies = TrackingClientHelper.getAllCookies();
		if (cookies) {
			var dwCookieRegExp = /^[ ]*dwsourcecode_/;
			for ( var i = 0; i < cookies.length; i++) {
				var cookieWithValue = cookies[i];
				if (cookieWithValue.search(dwCookieRegExp) > -1) {
					var nameValueArray = cookieWithValue.split("=");
					if (nameValueArray && nameValueArray.length == 2) {
						var values = nameValueArray[1];
						if (values && values != "") {
							var value = values.split("|");
							return value[a];
						}
					}
				}
			}
		}
		return "";
	},

	getCookieAffiliate : function(cvar) {
		var cookies = TrackingClientHelper.getAllCookies();
		if (cookies) {
			cvar += "/";
			var affiliateCookieRegExp = /^[ ]*affiliate/;
			for ( var i = 0; i < cookies.length; i++) {
				var cookieWithValue = cookies[i];
				if (cookieWithValue.search(affiliateCookieRegExp) > -1) {
					var nameValueArray = cookieWithValue.split("=");
					if (nameValueArray && nameValueArray.length == 2) {
						var values = nameValueArray[1];
						if (values && values != "") {
							var regexp = new RegExp(cvar + "[^,]*");
							var trackArray = values.match(regexp);
							var track_id;

							if (trackArray && trackArray.length > 0) {
								var trackString = trackArray[0];
								track_id = trackString.replace(cvar, "");
								return track_id;
							}
						}
					}
				}
			}
		}
		return "";
	},

	getCookie : function(a, b) {
		var cookie = TrackingClientHelper.getCookieAffiliate(a);
		if (cookie && cookie != "") {
			return cookie;
		}
		cookie = TrackingClientHelper.getCookieDW(b);
		if (cookie && cookie != "") {
			return cookie;
		}
		return "";
	},

	getNewsletterTrack : function() {
		var nltrack = "";
		// mid
		nltrack = TrackingClientHelper.getCookieAffiliate("mission1ID");
		if (nltrack != "") {
			var lid = TrackingClientHelper.getCookieAffiliate("mission1SecondID");
			if (lid != "") {
				nltrack = nltrack + "|" + lid; // lid
				var nlrcp = TrackingClientHelper.getCookieAffiliate("nlrcp");
				if (nlrcp != "") {
					try {
						// catching not encoded cookie value
						nlrcp = atob(nlrcp);
						nltrack = nltrack + "|" + nlrcp;
					} catch (e) {
						// do nothing
					}
				}
			}
		}
		return nltrack;
	},

	removeSeparators : function(name) {
		if (name && name != "") {
			name = name.replace(/[,;'"]/ig, "");
		}
		return name;
	}
}

/**
 * End - TrackingClientHelper
 */


/**
 * Helper functions to read AVAIL cookie
 */


 /**
  *  Global properties to help interval and timeout handling
  */
/*var intermediateCounter = 0;
var timeoutReached = false;
var intevalGlobal;
var emarkGlobal;
var results;
var url;
var intermediateCommits;
 */
var AvailHelper = {

	intermediateCounter : 0,
	timeoutReached : null,
	intervalGlobal : null,
	emarkGlobal : null,
	results : null,
	url : null,
	intermediateCommits : null,

	getValues : function(elementName) {
		try {
			var allCookies = document.cookie.split(';');
			var value = null;
			for(var i = 0; i < allCookies.length; i++) {
				var tmp = allCookies[i];
				if(tmp.indexOf("recommendations=") != -1) {
					value=tmp.substr(tmp.indexOf("=") + 1);
					break;
				}
			}

			if(value) {
				var cookieValues = value.split(",");
				if(cookieValues) {
					for(var i = 0; i < cookieValues.length; i++) {
						var cookieValue = cookieValues[i];
						if(cookieValue && cookieValue.indexOf(elementName) == 0) {
							cookieValue = cookieValue.replace(elementName + "(", "").replace(")", "");
							if(cookieValue == null || cookieValue == "") {
								return null;
							}

							var retValue =cookieValue.split("|");
							return retValue;
						}
					}
				}
			}
		}
		catch(e) {
			//console.log("exc: %o", e);
		}

		return null;
	},

	doSaasTracking : function() {
		var currentQuery = MiscUtils.getUrlParameterValue('q');
		var isLPOPage = (MiscUtils.getUrlParameterValue('origin') != '');

		if(currentQuery != null && currentQuery != "" && isLPOPage) {
			Cookie.set("AvailSaaSLPOQuery", currentQuery);
		}
	},

	getLastVisited : function() {
		return AvailHelper.getValues("lvp");
	},

	getBoughtProducts : function() {
		return AvailHelper.getValues("bp");
	},

	getSearchWords : function() {
		return AvailHelper.getValues("sw");
	},

	showLPOLoadingInfo : function() {

		try {
			var galleries = $('lpolanding').select('.lpoLandingBox');
			for(var i = 0; i < galleries.length; i++) {
				var gallery = galleries[i];
				new Insertion.Before(gallery.firstDescendant(), '<div class="lpoloading lpoProduct lpoGalleryContentInner"></div><div class="lpoloading lpoProduct lpoGalleryContentInner"></div>' );
			}
		}
		catch(e) {
			// console.log("exc: %o", e);
		}
	},

	hideLPOLoadingInfo : function() {

		try {
			var placeholders = $('lpolanding').select('.lpoloading');
			for(var i = 0; i < placeholders.length; i++) {
				var loading = placeholders[i];
				loading.hide();
			}
		}
		catch(e) {
		}
	},

	doLastEmarkCommit : function() {
		if (AvailHelper.intermediateCommits == AvailHelper.intermediateCounter) {
			window.clearInterval(AvailHelper.intervalGlobal);
			AvailHelper.emarkGlobal.commit(function() {
				// timeout handling
				if (!AvailHelper.timeoutReached)  {

					var paramMap = new Object();
					var usedPids = new Array();
					var cnt = 0;
					for(var cgid in AvailHelper.results) {
						var resultSet = AvailHelper.results[cgid];
						for(var i = 0; i < resultSet.values.length; i++) {
							if (!(usedPids.contains(resultSet.values[i].toString()))) {
								usedPids.push(resultSet.values[i].toString());
								paramMap['pid_' + cnt] = resultSet.values[i];
								paramMap['cgid_' + cnt] = cgid;
							}
							cnt++;
						}
					}
					new Ajax.Request(AvailHelper.url, {

						method: 'get',
						parameters: paramMap,
						onSuccess: function(transport) {

						new Insertion.Bottom( document.body, '<div id="lpoExchange" style="display:none"></div>' );
						var responses = $('lpoExchange').update(transport.responseText).select('.lpoLandingBox');
						for(var i = 0; i < responses.length; i++) {
							try {
								var source = responses[i];
								var id = source.identify();
								var cgid = id.split('_')[1];
								var target = $('cgid_' + cgid);
								new Insertion.Before(target.firstDescendant(), source.innerHTML );
							}
							catch(e) {
								// console.log("insert failed");
							}
						}


					},
					onComplete: function(transport) {
						AvailHelper.hideLPOLoadingInfo();
					}
					});

				}
			});
		}
	},

	// this function will be used for a later optimized version
	getLPORecommendations : function(urlLocal, searchPhrase, cgids) {
		AvailHelper.url = urlLocal;
		try {

			var emark = new Emark(false);
			var lastCommit = false;
			AvailHelper.results = new Object();
			AvailHelper.intermediateCommits = Math.floor(cgids.length / 3) + ((cgids.length % 3 > 0) ? 1 : 0) - 1;

			if(cgids != null && cgids.length > 0 && searchPhrase != null && searchPhrase != "") {

				AvailHelper.showLPOLoadingInfo();

				window.setTimeout("AvailHelper.hideLPOLoadingInfo(); AvailHelper.timeoutReached = true;", 5000);
				for(var i = 0; i < cgids.length; i++) {
					AvailHelper.results[cgids[i]] = emark.getLandingPagePredictions(searchPhrase, "RE_plain", new Array("append andcat in subtemplate 1 with " + cgids[i] + ""));
					// results[cgids[i]] = emark.getProductsPredictions(searchPhrase, "RE_plain", new Array("append andcat in subtemplate 1 with '" + cgids[i] + "'"));
					// results[cgids[i]] = emark.getProductsPredictions(searchPhrase, "RE_plain");
					// results[cgids[i]] = emark.getLandingPagePredictions(searchPhrase, "RE_plain", new Array(""));
					// break;
					var commit = (((i+1) % 3) == 0);
					if (i == (cgids.length - 1)) {
						lastCommit = true;
					}

					if (commit && !lastCommit) {
						emark.commit(function() {AvailHelper.intermediateCounter++;});
						emark = new Emark();
					}

					if (lastCommit) {
						AvailHelper.emarkGlobal = emark;
						AvailHelper.intervalGlobal = window.setInterval("AvailHelper.doLastEmarkCommit()", 100);

					}

				}
			}

		}
		catch(e) {
			AvailHelper.hideLPOLoadingInfo();
		}
	}
}



/**
 * End - Avail Helper
 */


/**
 * Begin - nlounge_videoplayer.js
 *
 * Script merged for improved performance
 */

//check for IE Browsers
if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
window.firefox = (navigator.userAgent.match(/Firefox\/1.5/) ? true : false);

var nloungePlayerDivId   	= 'nloungeVideoPlayer';
var nloungePlayerFlashId 	= 'nloungeVideoPlayerFlashId';
var	nloungePlayerWidth   	= '650';
var nloungePlayerHeight 	= '464';

function nloungeVideoPlayer()
{
	//Configuration
	this.strVideoPlayer	= location.protocol + '//neckermann.n-lounge.de/nlounge_miniplayer.swf'; //overwrite with this.setVideoPlayer()
	this.strCssUri		= '';//'/css/player/nlounge_videoplayer/nlounge_videoplayer.css';
	this.strVideoImage	= '/leer.gif';
	this.default_width  = nloungePlayerWidth;
	this.default_height = nloungePlayerHeight;

	this.isCalledFromDialog = false;

	//Create Div Element for the player on the page
	this.playerContainer    = document.createElement('div');
	this.playerContainer.id = nloungePlayerDivId;
	document.body.appendChild(this.playerContainer);

	//Create Style Element for the player style
	var h  = document.getElementsByTagName('head')[0];
	var s  = document.createElement('link');
	s.type = 'text/css';
	s.rel  = 'stylesheet';
	s.href = this.strCssUri;
	h.appendChild(s);

	try
	{
		this.DIVElementname = nloungePlayerDivId;
		this.objDIVElement = document.getElementById( this.DIVElementname );
	}
	catch( e )
	{
	}

	this.setVideoPlayer = function( strNewVideoPlayerUri )
	{
		this.strVideoPlayer = strNewVideoPlayerUri;
	};


	this.play = function( mb_f020_id, p_id , openRightSide)
	{
		var newZIndex = '200';
		if( this.isCalledFromDialog ) {
			newZIndex = '1101';
		}

		try
		{

			var playerWidth = this.default_width;
		    var playerHeight = this.default_height;

			if ( window.firefox )
			{
				this.objDIVElement.style.overflow = 'hidden';
				this.objDIVElement.style.width    = '1px';
				this.objDIVElement.style.height   = '1px';

	            /* width and height will be set according to the players current dimension,
	               this will prevent some flicker in FF1.5 */
			}

			var strContent = '';
			strContent += '<div style="margin: 0 0 0 0">';
			strContent += '		<div id="nlounge_flashcontent" style="z-index:';
			strContent += newZIndex;
			strContent += ';">';
			strContent += '			<div style="padding: 10 20 20 20; background-color: #ffffff; border: 0px solid red;">';
			strContent += ' 			<br />Sie m&uuml;ssen zuerst die aktuelle Flash-Version des Adobe Flash-Players installieren.';
			strContent += ' 			<br />Um zur Adobe Flash-Player Installionsseite zu kommen, klicken Sie bitte <a href="http://www.macromedia.com/go/getflashplayer/" target="_blank">hier</a>.';
			strContent += ' 			<br /><br /><a href="" onclick="closePlayer(); return false;" >schie&szlig;en</a>.';
			strContent += '			</div>';
			strContent += '		</div>';
			strContent += '</div>';

			this.objDIVElement.innerHTML 			= strContent;
			this.objDIVElement.style.zIndex  		= newZIndex;
			this.objDIVElement.style.backgroundColor= 'transparent';
			this.objDIVElement.style.display 		= 'block';
			//this.objDIVElement.style.border 		= '1px red solid';

			var so = new SWFObject(this.strVideoPlayer, nloungePlayerFlashId, playerWidth, playerHeight, "9", "#FFFFFF");
			so.addParam("quality", "high");
			so.addParam("allowScriptAccess", "always");
			if (!window.firefox)
			{
				so.addParam("wmode", "transparent");
			}

			so.addVariable("mb_f020_id", mb_f020_id);
			so.addVariable("product_id", p_id);
			so.addVariable("host", window.location.hostname);

			if (openRightSide!=undefined)
			{
				so.addVariable("openRightSide", openRightSide);
			}

			so.write("nlounge_flashcontent");

			// IE6-iframe-layer
            nloungeVideoplayer_OverlayFix.initialize(nloungePlayerDivId);
		}
		catch( e )
		{
		}

		this.calledFromDialog = false;
	};

	this.close = function() {
		try
		{
			this.objDIVElement.style.display = 'none';
			this.objDIVElement.innerHTML='';
		}
		catch( e )
		{
		}
	};

	this.setClipping = function(clipping)
	{
	    this.objDIVElement.style.clip = 'rect('+ clipping.top +'px '+ clipping.right +'px '+ clipping.bottom +'px '+ clipping.left +'px)';
    };

    this.setContainerSize = function(width, height)
    {
        this.objDIVElement.style.width = width;
        this.objDIVElement.style.height = height;
    };
}


// Fix for IE6 (form fields above flash-layer)

var nloungeVideoplayer_OverlayFix = {

	initialize: function(el) {
		MiscUtils.hideSelectElements( true );
		this.elToFix = document.getElementById(el);;
		if (window.ie)
		{

			this.fix = document.createElement('iframe');
			this.fix.frameBorder = '0';
			this.fix.scrolling = 'no';
			this.fix.src = 'javascript:false;';

			this.fix.style.position = 'absolute';
			this.fix.style.border = 'none';
			this.fix.style.display = 'none';
			this.fix.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)';

			document.body.appendChild(this.fix);
		}

		var el_pos = this.elToFix, left_pos = 0, top_pos = 0;
		do {
			left_pos += el_pos.offsetLeft || 0;
			top_pos  += el_pos.offsetTop || 0;
			el_pos = el_pos.offsetParent;
		} while (el_pos);

		this.setCoordinates({

    		width  : this.elToFix.offsetWidth,
    		height : this.elToFix.offsetHeight,
    		left   : left_pos,
    		top    : top_pos,
    		right  : (left_pos + this.elToFix.offsetWidth),
    		bottom : (top_pos + this.elToFix.offsetHeight),
    		zIndex : ((this.elToFix.style.zIndex || 1) - 1)
    	});

	},

	setCoordinates: function(coordinates)
	{
	    if (coordinates.width)  this.width  = coordinates.width;
		if (coordinates.height) this.height = coordinates.height;
		if (coordinates.left)   this.left   = coordinates.left;
		if (coordinates.top)    this.top    = coordinates.top;
		if (coordinates.right)  this.right  = coordinates.right;
		if (coordinates.bottom) this.bottom = coordinates.bottom;
		if (coordinates.zIndex) this.zIndex = coordinates.zIndex;
	},

	show: function()
	{
		if (this.fix)
		{
    		this.fix.style.width  = this.width;
    		this.fix.style.height = this.height;
    		this.fix.style.left   = this.left;
    		this.fix.style.top    = this.top;
    		this.fix.style.right  = this.right;
    		this.fix.style.bottom = this.bottom;
    		this.fix.style.zIndex = this.zIndex;

    		this.fix.style.display = '';
		}

		return this;
	},

	hide: function()
	{
		if (this.fix)
		{
		    this.fix.style.display = 'none';
		}
		return this;
	},

	destroy: function()
	{
	    if ( this.fix )
	    {
		    this.fix.parentNode.removeChild(this.fix);
		}

		MiscUtils.hideSelectElements( false );
	},

	move: function(new_top, new_left)
	{
	    if ( this.fix )
	    {
	        if (new_top)
	        {
	            this.fix.style.top = this.top = new_top;
	}

	        if (new_left)
	        {
	            this.fix.style.left = this.left = new_left;
	        }
	    }
	}

};



// scroll-handler f�r IE, damit wird der IE-iframe gescrollt
if (window.ie)
{
	window.onscroll = function()
	{
		if ( nloungeVideoplayer_OverlayFix )
		{
		    nloungeVideoplayer_OverlayFix.move( document.body.scrollTop + 20 );
	}

	}
}

function nloungeVideoplayer_closePlayer() {
	//timeout needed for FF < 3.0
	setTimeout("nloungeVideoplayer_closePlayerDiv()",10);
}


function nloungeVideoplayer_closePlayerDiv()
{
	var o = document.getElementById(nloungePlayerDivId);

	if (o!=undefined)
	{
		o.innerHTML='';
		o.style.display = 'none';

		// IE-iframe entfernen
		if ( nloungeVideoplayer_OverlayFix )
		{
			nloungeVideoplayer_OverlayFix.destroy();
		}

	}
}


function nloungeVideoplayer_setPlayerSize(h, w)
{
	var o = document.getElementById(nloungePlayerFlashId);

	playerWidth = w;
	playerHeight = h;

    nloungeVideoplayer_OverlayFix.setCoordinates({
        width: playerWidth,
        height: playerHeight
    });

	if ( window.firefox )
	{
	    window.objNloungeVideoPlayer.setContainerSize(playerWidth, playerHeight);
	}

	window.objNloungeVideoPlayer.setClipping({
	    top: 0,
	    right: playerWidth,
	    bottom: playerHeight,
	    left: 0
    });

	nloungeVideoplayer_OverlayFix.show();
}

function nloungeVideoplayer_showProduct(mb_f020_id,p_id){
	parent.location.href = '/index.mb1?produkt_id='+p_id+'&mb_f020_id='+mb_f020_id;
}

function nloungeVideoplayer_startnlounge(mb_f020_id,fm){
	openContentPopup('/nlounge'+(fm?('?fm='+fm):''),'nlounge','width=990,height=600,scrollbars=no,toolbar=no,location=no,left=150,top=150,status=no,resizable=no,menubar=no');
}

function showNloungeMovie(url, isDialog) {
	var calledFromDialog = !!isDialog;
	new Ajax.Request(
				url,
				{ onComplete: function(transport) {
					var parts = transport.responseText.split('<!-- json:');
					if (parts.length >= 2) {
						var json_raw = parts[1].split('-->')[0];
						var json = eval( '(' + json_raw.replace('\'','\\\'') + ')' );
					}
					if (json) {
						callNloungePlayer(json.pid, json.tid, calledFromDialog);
					}
				  }
				}
			);
}

function callNloungePlayer(pid, tid, calledFromDialog) {
	if(!window.objNloungeVideoPlayer){
		window.objNloungeVideoPlayer = new nloungeVideoPlayer();
	}
	window.objNloungeVideoPlayer.isCalledFromDialog = calledFromDialog;
	window.objNloungeVideoPlayer.play(tid,pid);
}

/**
* End - nlounge_videoplayer.js
*/

/**
 * Begin - cookie.js
 *
 * @author 	Maxime Haineault (max@centdessin.com)
 * @version	0.3
 * @desc 	JavaScript cookie manipulation class
 *
 */

Cookie = {
	/** Get a cookie's value
	 *
	 *  @param integer	key		The token used to create the cookie
	 *  @return void
	 */
	get: function(key) {
		// Still not sure that "[a-zA-Z0-9.()=|%/]+($|;)" match *all* allowed characters in cookies
		tmp =  document.cookie.match((new RegExp(key +'=[a-zA-Z0-9.()=|%/]+($|;)','g')));
		if(!tmp || !tmp[0])
		{
			return null;
		}
		else
		{
			return unescape(tmp[0].substring(key.length+1,tmp[0].length).replace(';','')) || null;
		}
	},

	/** Set a cookie
	 *
	 *  @param integer	key	The token that will be used to retrieve the cookie
	 *  @param string	value	The string to be stored
	 *  @param integer	ttl	Time To Live (hours)
	 *  @param string	path	Path in which the cookie is effective, default is "/" (optional)
	 *  @param string	domain	Domain where the cookie is effective, default is window.location.hostname (optional)
	 *  @param boolean 	secure	Use SSL or not, default false (optional)
	 *
	 *  @return setted cookie
	 */
	set: function(key, value, ttl, path, domain, secure) {
		cookie = [key+'='+    escape(value),
		 		  'path='+    ((!path   || path=='')  ? '/' : path),
		 		  'domain='+  ((!domain || domain=='')?  window.location.hostname : domain)];

		if (ttl)         cookie.push(Cookie.hoursToExpireDate(ttl));
		if (secure)      cookie.push('secure');
		return document.cookie = cookie.join('; ');
	},

	/** Unset a cookie
	 *
	 *  @param integer	key		The token that will be used to retrieve the cookie
	 *  @param string	path	Path used to create the cookie (optional)
	 *  @param string	domain	Domain used to create the cookie, default is null (optional)
	 *  @return void
	 */
	unset: function(key, path, domain, secure) {
		path   = (!path   || typeof path   != 'string') ? '' : path;
        domain = (!domain || typeof domain != 'string') ? '' : domain;
        secure = (!secure || typeof secure != 'string') ? '' : secure;
		if (Cookie.get(key)) Cookie.set(key, '', 'Thu, 01-Jan-70 00:00:01 GMT', path, domain, secure);
	},

	/** Return GTM date string of "now" + time to live
	 *
	 *  @param integer	ttl		Time To Live (hours)
	 *  @return string
	 */
	hoursToExpireDate: function(ttl) {
		if (parseInt(ttl) == 'NaN' ) return '';
		else {
			now = new Date();
			now.setTime(now.getTime() + (parseInt(ttl) * 60 * 60 * 1000));
			return now.toGMTString();
		}
	},

	/** Return true if cookie functionnalities are available
	 *
	 *  @return boolean
	 */
	test: function() {
		Cookie.set('b49f729efde9b2578ea9f00563d06e57', 'true');
		if (Cookie.get('b49f729efde9b2578ea9f00563d06e57') == 'true') {
			Cookie.unset('b49f729efde9b2578ea9f00563d06e57');
			return true;
		}
		return false;
	},

	/** If Firebug JavaScript console is present, it will dump cookie string to console.
	 *
	 *  @return void
	 */
	dump: function() {
		if (typeof console != 'undefined') {
			console.log(document.cookie.split(';'));
		}
	}
}
/**
 * End - cookie.js
 */


 /**
  * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
  *
  * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
  * http://www.opensource.org/licenses/mit-license.php
  *
  * Begin - swfobject_source.js
  */
 if(typeof deconcept == "undefined") var deconcept = new Object();
 if(typeof deconcept.util == "undefined") deconcept.util = new Object();
 if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
 deconcept.SWFObject = function(swf, id, w, h, ver, c, quality, xiRedirectUrl, redirectUrl, detectKey) {
 	if (!document.getElementById) { return; }
 	this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
 	this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
 	this.params = new Object();
 	this.variables = new Object();
 	this.attributes = new Array();
 	if(swf) { this.setAttribute('swf', swf); }
 	if(id) { this.setAttribute('id', id); }
 	if(w) { this.setAttribute('width', w); }
 	if(h) { this.setAttribute('height', h); }
 	if(ver) { this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split("."))); }
 	this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
 	if (!window.opera && document.all && this.installedVer.major > 7) {
 		// only add the onunload cleanup if the Flash Player version supports External Interface and we are in IE
 		deconcept.SWFObject.doPrepUnload = true;
 	}
 	if(c) { this.addParam('bgcolor', c); }
 	var q = quality ? quality : 'high';
 	this.addParam('quality', q);
 	this.setAttribute('useExpressInstall', false);
 	this.setAttribute('doExpressInstall', false);
 	var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
 	this.setAttribute('xiRedirectUrl', xir);
 	this.setAttribute('redirectUrl', '');
 	if(redirectUrl) { this.setAttribute('redirectUrl', redirectUrl); }
 }
 deconcept.SWFObject.prototype = {
 	useExpressInstall: function(path) {
 		this.xiSWFPath = !path ? "expressinstall.swf" : path;
 		this.setAttribute('useExpressInstall', true);
 	},
 	setAttribute: function(name, value){
 		this.attributes[name] = value;
 	},
 	getAttribute: function(name){
 		return this.attributes[name];
 	},
 	addParam: function(name, value){
 		this.params[name] = value;
 	},
 	getParams: function(){
 		return this.params;
 	},
 	addVariable: function(name, value){
 		this.variables[name] = value;
 	},
 	getVariable: function(name){
 		return this.variables[name];
 	},
 	getVariables: function(){
 		return this.variables;
 	},
 	getVariablePairs: function(){
 		var variablePairs = new Array();
 		var key;
 		var variables = this.getVariables();
 		for(key in variables){
 			variablePairs[variablePairs.length] = key +"="+ variables[key];
 		}
 		return variablePairs;
 	},
 	getSWFHTML: function() {
 		var swfNode = "";
 		if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
 			if (this.getAttribute("doExpressInstall")) {
 				this.addVariable("MMplayerType", "PlugIn");
 				this.setAttribute('swf', this.xiSWFPath);
 			}
 			swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'"';
 			swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
 			var params = this.getParams();
 			 for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
 			var pairs = this.getVariablePairs().join("&");
 			 if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
 			swfNode += '/>';
 		} else { // PC IE
 			if (this.getAttribute("doExpressInstall")) {
 				this.addVariable("MMplayerType", "ActiveX");
 				this.setAttribute('swf', this.xiSWFPath);
 			}
 			swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'">';
 			swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
 			var params = this.getParams();
 			for(var key in params) {
 			 swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
 			}
 			var pairs = this.getVariablePairs().join("&");
 			if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
 			swfNode += "</object>";
 		}
 		return swfNode;
 	},
 	write: function(elementId){
 		if(this.getAttribute('useExpressInstall')) {
 			// check to see if we need to do an express install
 			var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
 			if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
 				this.setAttribute('doExpressInstall', true);
 				this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
 				document.title = document.title.slice(0, 47) + " - Flash Player Installation";
 				this.addVariable("MMdoctitle", document.title);
 			}
 		}
 		if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
 			var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
 			n.innerHTML = this.getSWFHTML();
 			return true;
 		}else{
 			if(this.getAttribute('redirectUrl') != "") {
 				document.location.replace(this.getAttribute('redirectUrl'));
 			}
 		}
 		return false;
 	}
 }

 /* ---- detection functions ---- */
 deconcept.SWFObjectUtil.getPlayerVersion = function(){
 	var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
 	if(navigator.plugins && navigator.mimeTypes.length){
 		var x = navigator.plugins["Shockwave Flash"];
 		if(x && x.description) {
 			PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
 		}
 	}else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0){ // if Windows CE
 		var axo = 1;
 		var counter = 3;
 		while(axo) {
 			try {
 				counter++;
 				axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+ counter);
// 				document.write("player v: "+ counter);
 				PlayerVersion = new deconcept.PlayerVersion([counter,0,0]);
 			} catch (e) {
 				axo = null;
 			}
 		}
 	} else { // Win IE (non mobile)
 		// do minor version lookup in IE, but avoid fp6 crashing issues
 		// see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
 		try{
 			var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
 		}catch(e){
 			try {
 				var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
 				PlayerVersion = new deconcept.PlayerVersion([6,0,21]);
 				axo.AllowScriptAccess = "always"; // error if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
 			} catch(e) {
 				if (PlayerVersion.major == 6) {
 					return PlayerVersion;
 				}
 			}
 			try {
 				axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
 			} catch(e) {}
 		}
 		if (axo != null) {
 			PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
 		}
 	}
 	return PlayerVersion;
 }
 deconcept.PlayerVersion = function(arrVersion){
 	this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
 	this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
 	this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
 }
 deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
 	if(this.major < fv.major) return false;
 	if(this.major > fv.major) return true;
 	if(this.minor < fv.minor) return false;
 	if(this.minor > fv.minor) return true;
 	if(this.rev < fv.rev) return false;
 	return true;
 }
 /* ---- get value of query string param ---- */
 deconcept.util = {
 	getRequestParameter: function(param) {
 		var q = document.location.search || document.location.hash;
 		if (param == null) { return q; }
 		if(q) {
 			var pairs = q.substring(1).split("&");
 			for (var i=0; i < pairs.length; i++) {
 				if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
 					return pairs[i].substring((pairs[i].indexOf("=")+1));
 				}
 			}
 		}
 		return "";
 	}
 }
 /* fix for video streaming bug */
 deconcept.SWFObjectUtil.cleanupSWFs = function() {
 	var objects = document.getElementsByTagName("OBJECT");
 	for (var i = objects.length - 1; i >= 0; i--) {
 		objects[i].style.display = 'none';
 		for (var x in objects[i]) {
 			if (typeof objects[i][x] == 'function') {
 				objects[i][x] = function(){};
 			}
 		}
 	}
 }
 // fixes bug in some fp9 versions see http://blog.deconcept.com/2006/07/28/swfobject-143-released/
 if (deconcept.SWFObject.doPrepUnload) {
 	if (!deconcept.unloadSet) {
 		deconcept.SWFObjectUtil.prepUnload = function() {
 			__flash_unloadHandler = function(){};
 			__flash_savedUnloadHandler = function(){};
 			window.attachEvent("onunload", deconcept.SWFObjectUtil.cleanupSWFs);
 		}
 		window.attachEvent("onbeforeunload", deconcept.SWFObjectUtil.prepUnload);
 		deconcept.unloadSet = true;
 	}
 }
 /* add document.getElementById if needed (mobile IE < 5) */
 if (!document.getElementById && document.all) { document.getElementById = function(id) { return document.all[id]; }}

 /* add some aliases for ease of use/backwards compatibility */
 var getQueryParamValue = deconcept.util.getRequestParameter;
 var FlashObject = deconcept.SWFObject; // for legacy support
 var SWFObject = deconcept.SWFObject;
/**
 * End - swfobject_source.js
 */

 /** Add function atob, if browser (e.g. IE) does not implement it */
 /** Source: http://www.stringify.com/static/js/base64.js */
 if (typeof atob == 'undefined') {
    function atob(str) {
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
        var invalid = {
            chars:  new RegExp('[^' + chars + ']').test(str),
            equals: (/=/.test(str) && (/=[^=]/.test(str) || /={3}/.test(str)))
        };

        if (invalid.chars || invalid.equals)
            throw new Error('Invalid base64 data');
        var decoded = [];
        var c = 0;
        while (c < str.length) {
            var i0 = chars.indexOf(str.charAt(c++));
            var i1 = chars.indexOf(str.charAt(c++));
            var i2 = chars.indexOf(str.charAt(c++));
            var i3 = chars.indexOf(str.charAt(c++));
            var buf = (i0 << 18) + (i1 << 12) + ((i2 & 63) << 6) + (i3 & 63);
            var b0 = (buf & (255 << 16)) >> 16;
            var b1 = (i2 == 64) ? -1 : (buf & (255 << 8)) >> 8;
            var b2 = (i3 == 64) ? -1 : (buf & 255);
            decoded[decoded.length] = String.fromCharCode(b0);
            if (b1 >= 0) decoded[decoded.length] = String.fromCharCode(b1);
            if (b2 >= 0) decoded[decoded.length] = String.fromCharCode(b2);
        }
        return decoded.join('');
   }
}

/**
 *	Availtracking
 **/
AvailHelper.doSaasTracking();


/*****
* FlyOut-Helper
******/
var FlyOutHelper = {

	// how long a fly out is displayed
	timeoutLN:300, // miliseconds
	timeoutSF:100,
	showingSemaphore:'',
	hidingSemaphore:'',
	hidingStartSemaphore:'',

	/**
	*	Hide selects so that the are not visible if a fly out is hovered
	*/
	hideSelects : function(flyout) {

		if (navigator.userAgent.indexOf( 'IE 6' ) == -1 ) {
			return;
		}

		var selects = $('main').getElementsBySelector( 'select' );

		for (var i = 0; i < selects.length; i++) {
			if (flyout.overlaps(selects[i]))
				selects[i].hide();
		}

	},

	/**
	*	Show select if fly out is closed
	*/
	showSelects : function() {

		if (navigator.userAgent.indexOf( 'IE 6' ) == -1 ) {
			return;
		}

		var selects = $('main').getElementsBySelector( 'select' );
		for (var i = 0; i < selects.length; i++) {
			if (!selects[i].visible())
				selects[i].show();
		}
	},

	/**
	* load the content specified by url and display it in the div with id
	* check if content previously was loaded, only do request once
	* check if other fly outs are open, close them first (this is a fallback cause in some circumstances a fly out could not be closed
	*
	*	@param url (String) : The url to load
	*	@param id (String) : The id of the div to update with loaded content
	*	@param parameter (Object) : request parameter (can be null)
	*
	*	@return if the element was loaded or not
	*/
	showFlyOut : function (id) {

		FlyOutHelper.stopHiding();

		FlyOutHelper.stopDisplaying();

		var leftNavFlyOut = $('leftNavFlyOut');
		if (leftNavFlyOut && leftNavFlyOut.visible())
			FlyOutHelper.hideFlyOut(leftNavFlyOut,FlyOutHelper.timeoutLN);

		var element = $(id);
		if (!element) {
			return;
		}

		var functionCall = "$('" + id + "').show(); FlyOutHelper.hideSelects($('" + id + "'));";
		window.setTimeout(functionCall, FlyOutHelper.timeoutSF);

	},

	hideArrows : function() {
		var leftMenu = $('leftMenu');
		if (leftMenu) {
			var spans = leftMenu.select('.permanent');
			for(var i = 0; i < spans.length; i++) {
				var span = spans[i];
				span.removeClassName('permanent');
			}
		}
	},

	isEmptyJSONObject : function(object) {

		for (var i in object) {
			return false;
		}
		return true;
	},

	/**
	*	Generates the markup for the left flyout
	*
	*	@param flyoutJSON (Object) : The JSON object containing the raw data
	*/
	generateFlyout : function(flyoutJSON) {
		try {
		var innerHTML = "";
		flyoutJSON = flyoutJSON.refinementvalue;
		var cgid = flyoutJSON.categoryID;
		var isDepartment = flyoutJSON.brandRefinements || flyoutJSON.themeRefinements;
		var onclick = "JSUtils.refineParameterAppend(this.href, JSParameterMap, true ); return false;";

		innerHTML += "<div ";
		if(isDepartment) {innerHTML += " class='departments'"; }
		innerHTML += ">";
		innerHTML += "<table><tr>";
		if(flyoutJSON.primaryRefinements) {
			var href = flyoutJSON.primaryRefinementURL;

			innerHTML += "<td class='category flyoutBox'>";
			innerHTML += "<h1>" + flyoutJSON.primaryDisplayName + "</h1>";
			innerHTML += "<div class='separator'> </div>";

			/*
			var showSaleItemLink = false;
			if(showSaleItemLink && isDepartment && JSParameterMap['scgid'] == null) {
				var saleHref = flyoutJSON.saleRefinementURL;
				innerHTML +="<a class='mainLinks' href='" + saleHref.replace(flyoutJSON.catIDPlaceHolder, cgid) + "' onclick='" + onclick + "'>" + flyoutJSON.saleDisplayName +"</a>";
				innerHTML += "<div class='separator'> </div>";
			}
			*/
			if(flyoutJSON.topFilters) {
				for (var topFilter in flyoutJSON.topFilters) {
					var topHref = flyoutJSON.topFilters[topFilter];
					innerHTML +="<a class='mainLinks' href='" + topHref + "'>" + topFilter +"</a>";
					innerHTML += "<div class='separator'> </div>";
				}
			}

			innerHTML += "<div class='categoryrefineNav'><ul>";
			for (var refinementValues in flyoutJSON.primaryRefinements) {
				var entry = flyoutJSON.primaryRefinements[refinementValues].refinements;
				innerHTML += "<li>";
				innerHTML += "<a href='" + href.replace(flyoutJSON.catIDPlaceHolder, entry.categoryID) + "' onclick='" + onclick + "'>";
				innerHTML += "<span class='catName'>";
				innerHTML += entry.displayName;
				if(entry.hitCount != -1) {
					innerHTML += " (" + entry.hitCount + ")";
				}
				innerHTML += "</span></a></li>";
			}

			innerHTML += "</ul></div>";
			innerHTML += "</td>";
		}

		if(flyoutJSON.themeRefinements && !FlyOutHelper.isEmptyJSONObject(flyoutJSON.themeRefinements)) {
			var href = flyoutJSON.themeRefinementURL;
			var themeCount = 0;
			innerHTML += "<td class='themes flyoutBox'>";
			innerHTML += "<h1>" + flyoutJSON.themeDisplayName + "</h1>";
			innerHTML += "<div class='separator'> </div>";


			innerHTML += "<div class='categoryrefineNav'><ul>";
			for (var refinementValues in flyoutJSON.themeRefinements) {
				themeCount++;
				var entry = flyoutJSON.themeRefinements[refinementValues].refinements;
				innerHTML += "<li>";
				innerHTML += "<a href='" + href.replace(flyoutJSON.catIDPlaceHolder, entry.categoryID) + "' onclick='" + onclick + "'>";
				innerHTML += "<span class='catName'>";
				innerHTML += entry.displayName;
				/*
				if(entry.hitCount != -1) {
					innerHTML += " (" + entry.hitCount + ")";
				}
				*/
				innerHTML += "</span></a></li>";

				if(themeCount > 20) {
					break;
				}
			}


			innerHTML += "</ul></div>";
			innerHTML += "</td>";
		}

		if(flyoutJSON.brandRefinements && !FlyOutHelper.isEmptyJSONObject(flyoutJSON.brandRefinements)) {
			var href = flyoutJSON.brandRefinementURL;

			innerHTML += "<td class='themes flyoutBox'>";
			innerHTML += "<h1>" + flyoutJSON.brandDisplayName + "</h1>";
			innerHTML += "<div class='separator'> </div>";


			innerHTML += "<div class='categoryrefineNav'><ul>";
			var brandCount = 0;
			for (var refinementValues in flyoutJSON.brandRefinements) {
				brandCount++;
				var entry = flyoutJSON.brandRefinements[refinementValues].refinements;
				innerHTML += "<li>";
				innerHTML += "<a href='" + href.replace(flyoutJSON.catIDPlaceHolder, entry.categoryID) + "' onclick='" + onclick + "'>";
				innerHTML += "<span class='catName'>";
				innerHTML += entry.displayName;
				/*
				if(entry.hitCount != -1) {
					innerHTML += " (" + entry.hitCount + ")";
				}
				*/
				innerHTML += "</span></a></li>";

				if(brandCount > 20) {
					break;
				}
			}


			innerHTML += "</ul>";
			if(flyoutJSON.moreBrandsURL != null && flyoutJSON.moreBrandsURL != "" && flyoutJSON.moreBrandsDisplayName != null && flyoutJSON.moreBrandsDisplayName != "") {
				innerHTML += "<div class='more'>"
				innerHTML += "<a href='" + flyoutJSON.moreBrandsURL + "'>";
				innerHTML += flyoutJSON.moreBrandsDisplayName;
				innerHTML += "</a>"
				innerHTML += "</div>"
			}

			innerHTML += "</div>";
			innerHTML += "</td>";
		}


		innerHTML += "</tr></table></div>";


		var divId = 'fly_out_' + cgid;
		var flyOutDiv = new Element('div', {'id':divId});
		$('flyOutParent').appendChild(flyOutDiv);
		flyOutDiv.hide();
		flyOutDiv.update(innerHTML);
		}
		catch(e) {
			//console.log('generateFly: %o', e);
		}
	},

	/**
	*	Get the category id from the given element. Load content for the fly out div with FlyOutHelper.showFlyOut
	*
	*	@param element (Element) : The element that has the id, maybe SPAN or A, so we need to go up
	*/
	showLeftNavFlyOut : function (element) {

		if(!$('leftNavFlyOut')) {
			return;
		}

		var startFlyOut = $('startFlyOut');
		if (startFlyOut && startFlyOut.visible())
			FlyOutHelper.hideFlyOut(startFlyOut,FlyOutHelper.timeoutSF);


		var rawDataContainer = null;
		var spanId = element.identify();
		var cgid = spanId.split('_');
		if(cgid == null || cgid.length != 2) {
			return;
		}

		var cgid = cgid[1];
		var emID = 'em_' + cgid;
		var divId = 'fly_out_' + cgid;
		var targetElement = $(emID);
		if(targetElement == null) {
			return;
		}
		if ($(divId) == null) {
			var rawData = targetElement.firstChild.nodeValue;
			var jsonObject = rawData.evalJSON();
			FlyOutHelper.generateFlyout(jsonObject);
		}

		FlyOutHelper.displayFlyout(divId, spanId);

	},

	/**
	*
	*/
	displayFlyout : function (divId, spanId) {

		FlyOutHelper.stopHiding();

		FlyOutHelper.stopDisplaying();

		var functionCall = "FlyOutHelper._displayFlyout('" + divId + "','" + spanId + "');";
		FlyOutHelper.showingSemaphore = window.setTimeout(functionCall, FlyOutHelper.timeoutLN);

	},

	/**
	*
	*/
	_displayFlyout : function (divId, spanId) {
		var divElement = $(divId);
		if (!divElement) {
			return;
		}

		var spanElement = $(spanId);
		if (!spanElement) {
			return;
		}

		FlyOutHelper.hideArrows();

		spanElement.addClassName('permanent');

		var leftNavFlyOut = $('leftNavFlyOut');
		if (!leftNavFlyOut) {
			return;
		}
		leftNavFlyOut.update(divElement.innerHTML);

		// Set the top position of main page. Important if using advertising around the main page.
		var containerTop		= 0;
		if ($('container')) {
			containerTop		= $('container').positionedOffset().top;
		}

		var topMargin			= 25;
		var flyOutHeight		= leftNavFlyOut.getDimensions().height;				// the height of current flyout
		var windowHeight		= document.viewport.getDimensions().height;			// the height of current browser window
		var scrollOffset		= document.viewport.getScrollOffsets().top;			// the offset value, if uses scrolling
		var flyOutOffset_gross 	= spanElement.positionedOffset().top - topMargin;	// the offset value, which move the flyout relative to the left selected menu
		var flyOutSum			= flyOutOffset_gross + flyOutHeight + containerTop;
		var flyOutOffset		= flyOutOffset_gross;

		// re-calculates the flyout offset, if the flyout sum bigger as the window size
		if ((flyOutSum) > (windowHeight + scrollOffset)) {
			var subValue = (flyOutSum + 10) - (windowHeight + scrollOffset);
			flyOutOffset = flyOutOffset_gross - subValue;
		}

		$('flyOutParent').setStyle('top: ' + flyOutOffset + 'px;');
		leftNavFlyOut.show();

		FlyOutHelper.hideSelects(leftNavFlyOut);

		if (FlyOutHelper.showingSemaphore != '') {
			FlyOutHelper.showingSemaphore = '';
		}
	},

	/**
	*
	*/
	stopDisplaying : function() {
		if (FlyOutHelper.showingSemaphore != '') {
			window.clearTimeout(FlyOutHelper.showingSemaphore);
			FlyOutHelper.showingSemaphore = '';
		}
	},

		/**
	*
	*/
	stopHiding : function() {
		if (FlyOutHelper.hidingSemaphore != '') {
			window.clearTimeout(FlyOutHelper.hidingSemaphore);
			//console.debug("FlyOutHelper.stopHiding window.clearTimeout.hiding:" + FlyOutHelper.hidingSemaphore);
			FlyOutHelper.hidingSemaphore = '';
		}
	},

	/**
	*
	*/
	hideFlyOut : function (element, timeout) {

		var functionCall = "FlyOutHelper._hideFlyOut('" + element.identify() + "');"
		if (element.identify() == 'leftNavFlyOut') {
			FlyOutHelper.stopHiding();
			FlyOutHelper.hidingSemaphore = window.setTimeout(functionCall, timeout);
			//console.debug("FlyOutHelper.hideFlyOut - set FlyOutHelper.hidingSemaphore:" + FlyOutHelper.hidingSemaphore);
		} else if (element.identify() == 'startFlyOut') {
			FlyOutHelper.hidingStartSemaphore = window.setTimeout(functionCall, timeout);
			//console.debug("FlyOutHelper.hideFlyOut - no FlyOutHelper.hidingSemaphore");
		}
	},

	/**
	*
	*/
	_hideFlyOut : function (id) {
		$(id).hide();
		FlyOutHelper.hideArrows();
		FlyOutHelper.showSelects();
		if (FlyOutHelper.hidingSemaphore != '') {
			FlyOutHelper.hidingSemaphore = '';
		}
		if (FlyOutHelper.hidingStartSemaphore != '') {
			FlyOutHelper.hidingStartSemaphore = '';
		}
	},

	/**
	*	This is the "advanced" version of hideFlyOut function.
	*	A check is done if the related element is not a child of the parent element. The parent element is the element that contains the flyout.
	*	The flyout only should be closed if the parent element is left.
	*
	*	@param id (String) - the id of the flyout to hide
	*	@param parentElement (Element) - the parent element
	*	@param relatedElement (Element) - the related element
	*	@param timeout (Number) - The timeout (if null, it will be set to 0)
	*/
	hideFlyOutAdvanced : function (id, parentElement, relatedElement, timeout) {

		var element = $(id);
		if (!element)
			return;

		if (timeout == null)
			timeout = 1;

		var isChildOf = DOMUtils.isChildOf(parentElement, relatedElement);
		if (!isChildOf) {
			FlyOutHelper.hideFlyOut(element, timeout);
		}

	}

};

var AddToWishList = Class.create();
AddToWishList.prototype = {
 	initialize: function(url) {
		var urlarguments = this.getURLArguments(url);
		urlarguments += (url.indexOf('?') < 0 ? '?' : '&') + 'view=ajax';
		new Ajax.Request( url + urlarguments, {method:'get',evalScripts: true, onComplete:this.handleResponse.bind(this)});
 	},

 	handleResponse: function( trans ) {
 		window.popup.setWidth( 586 );
 		window.popup.setExchangeContent( trans.responseText );
 		trans.responseText.evalScripts();
 		window.popup.showPopup();
 	},

 	getURLArguments : function (url) {
 		var urlarguments = '';

		var quantityField = $('Quantity');
		if (quantityField) {
			urlarguments += (url.indexOf('?') < 0 ? '?' : '&') + 'quantity=' + quantityField.value;
		}
		var customInputOneField = $('customInputOneValue');
		if (customInputOneField) {
			urlarguments += (url.indexOf('?') < 0 ? '?' : '&') + 'customInputOneValue=' + customInputOneField.value;
		}
		var customInputTwoField = $('customInputTwoValue');
		if (customInputTwoField) {
			urlarguments += (url.indexOf('?') < 0 ? '?' : '&') + 'customInputTwoValue=' + customInputTwoField.value;
		}

	return urlarguments;
 }

}


var TabBar = {

	init : function(root) {

		/*
		if (!root || root.up('.donotenhance') != undefined) {
			return;
		}
		*/

		var pds = $('productdetails');
		if(!pds) return;

		var tabbars = pds.select('.tabbar');
		var currentHash = window.location.hash;
		if(currentHash == null) {
			currentHash = '';
		}

		for(var i = 0; i < tabbars.length; i++) {
			var tabbar = tabbars[i];
			TabBar.clearSelection(tabbar);

			var contents = tabbar.select('.content');
			for(var k = 0; k < contents.length; k++) {
				var content = contents[k];
				var contentID = content.identify();
				if(contentID.indexOf('_') != 0) {
					content.id = '_' + contentID;
				}
			}

			TabBar.select(tabbar, '');
		}

		if(currentHash != null && currentHash != '') {
			TabBar.selectTab(currentHash.substring(1));
		}

	},

	select : function(tabbar, currentHash) {
		var anchors = tabbar.select('.toc A');
		for(var j = 0; j < anchors.length; j++) {
			var anchor = anchors[j];
			if(currentHash == '' || anchor.hash == currentHash) {
				var content = $('_' + anchor.hash.substring(1));
				if(content) {
					content.style.display = 'block';
				}
				var parentElement = anchor.parentNode;
				if(parentElement) {
					parentElement.addClassName('current');
				}
				break;
			}
		}
	},

	clearSelection : function(tabbar) {
		var items = tabbar.select('LI');
		for (var i = 0; i < items.length; i++) {
			var item = items[i];
			item.removeClassName('current');
		}

		var contents = tabbar.select('.content');
		for(var j = 0; j < contents.length; j++) {
			var content = contents[j];
			content.style.display = 'none';
		}
	},

	selectTab : function(elementID) {
		elementID = TabBar.getContentElementParent(elementID);
		var container = $('_' + elementID);
		if(!container) return;

		var parents = container.ancestors();
		var parent = null;
		for(var i = 0; i < parents.length; i++) {
			var tmp = parents[i];
			if(tmp.hasClassName('tabbar')) {
				parent = tmp;
				break;
			}
		}

		if(parent != null) {
			TabBar.clearSelection(parent);
			TabBar.select(parent, '#' + elementID);
		}
	},

	goTo : function(elementID) {

		elementID = TabBar.getContentElementParent(elementID);
		var container = $('_' + elementID);
		if(!container) return;

		var parents = container.ancestors();
		var parent = null;
		for(var i = 0; i < parents.length; i++) {
			var tmp = parents[i];
			if(tmp.hasClassName('tabbar')) {
				parent = tmp;
				break;
			}
		}

		if(parent != null) {
			TabBar.clearSelection(parent);
			TabBar.select(parent, '#' + elementID);
			parent.scrollIntoView(true);
		}
	},

	getContentElementParent : function(elementID) {

		var container = $('_' + elementID);
		if(container != null && container.hasClassName('content')) {
			return elementID;
		}

		if(container == null) {
			container = $(elementID);
		}

		if(container == null) {
			return elementID;
		}

		var parents = container.ancestors();
		for(var i = 0; i < parents.length; i++) {
			var parent = parents[i];
			if(parent.hasClassName('content')) {
				var parentID = parent.identify();
				if(parentID.indexOf('_') == 0) {
					return parentID.substring(1);
				}
			}
		}
	}
}

/**
*	A helper class for reloading the product listing page.
*/
var ProductListingReloadHelper = {

	failure: false,
	initialized: false,
	configuration: null,
	scrollingDetectingToken: '',
	scrollingDetectingTimeout: 1000,
	reloadAfter: 0.75,
	ptDiv: null,

	/**
	*	Initialize the ProductListingReloadHelper
	*/
	initialize: function() {

		if (ProductListingReloadHelper.initialized)
			return;

		var config = $('ProductListingReloadHelperConfiguration');
		if (config) {
			try {
				var content = config.innerHTML.replace(/\n/g,'');
				ProductListingReloadHelper.configuration = eval('('+content+')');
			} catch (e) {
				ProductListingReloadHelper.failure = true;
			}

			// only start scrolling detection if we found the configuration and scrolling is enabled
			if (ProductListingReloadHelper.configuration.scrollingDetectionEnabled) {
				ProductListingReloadHelper.startScrollingDetection();
				// just get the pt_catalog-DIV to define the height of the page
				ProductListingReloadHelper.ptDiv = $('pt_catalog');
			}

		} else {
			ProductListingReloadHelper.failure = true;
		}

		ProductListingReloadHelper.initialized=true;
	},

	/**
	*	Reload a content snipped based on configuration
	*/
	loadNext: function() {

		if (ProductListingReloadHelper.initialized==true && ProductListingReloadHelper.failure)
			return;

		var current = ProductListingReloadHelper.configuration.current + 1;
		var pc = ProductListingReloadHelper.configuration.pc;

		if (current >= pc) {
			return; // do nothing if current is greater than page count
		}

		var daknightrida = $('daknightrida');
		var listingContainer = $('searchContent');
		if (!listingContainer) return;

		var sz = ProductListingReloadHelper.configuration.sz;
		var start = current * sz;

		var url = DOMUtils.getMetaTagValueByName('BaseUrl').replace('PL-SN','Search-ProductListingAJAX');
		url += '?start=' + start + '&sz=' + sz;
		url = MiscUtils.appendAllParameters(url, JSParameterMap);
		url = JSUtils.appendRefinementParameters(url, JSParameterMap);
		var viewmodeInDOM =  MiscUtils.getSelectedViewMode();
		if (MiscUtils.getUrlParameterValueByUrl('viewMode', url) == "" && viewmodeInDOM != "")  {
			url += MiscUtils.appendParameter(url, 'viewMode', viewmodeInDOM)
		}
		// its actually a rollerbobsel not a knight rider
		$('daknightrida').show();


		new Ajax.Request(
			url,
			{
				evalScripts : true,
				method : 'get',
				asynchronous : true,
				onComplete : function(trans) {
					listingContainer.insert({bottom: trans.responseText});
					$('daknightrida').hide();
					ProductListingReloadHelper.startScrollingDetection();
				}
			}
		);
	},

	/**
	*	Increment the current page, that is evaluatet after every AJAX call
	*/
	incrementCurrent: function() {

		ProductListingReloadHelper.configuration.current++;
	},

	/**
	*	Start the intervall that calls the scrollingDetection function
	*/
	startScrollingDetection: function() {

		if (ProductListingReloadHelper.scrollingDetectingToken != '') {
			window.clearInterval(ProductListingReloadHelper.scrollingDetectingToken);
		}
		ProductListingReloadHelper.scrollingDetectingToken = window.setInterval('ProductListingReloadHelper.scrollingDetection();', ProductListingReloadHelper.scrollingDetectingTimeout);
	},

	/**
	*	Stop the intervall that calls the scrollingDetection function
	*/
	stopScrollingDetection: function() {

		if (ProductListingReloadHelper.scrollingDetectingToken != '') {
			window.clearInterval(ProductListingReloadHelper.scrollingDetectingToken);
			ProductListingReloadHelper.scrollingDetectingToken = '';
		}
	},

	/**
	*	Measure how far the user has scrolled down the page, if that reaches a specific amount, reload the next portion of content
	*/
	scrollingDetection: function() {

		if (!ProductListingReloadHelper.ptDiv)
			return;

		var ptDivHeight = ProductListingReloadHelper.ptDiv.getDimensions().height;
		var viewportScrollOffset = document.viewport.getScrollOffsets().top;
		var viewportHeight = document.viewport.getDimensions().height;

		if (((viewportScrollOffset + viewportHeight) / ptDivHeight) >= ProductListingReloadHelper.reloadAfter) {
			ProductListingReloadHelper.loadNext();
			ProductListingReloadHelper.stopScrollingDetection();
		}
	}
}


var QuickviewHelper = {

		shownQuickviews : new Array(),
		currentQuickviewLinkContainer : null,
		currentQuickviewLink : null,

		checkMouseOver : function(el) {

			if(QuickviewHelper.currentQuickviewLinkContainer == null) {

				var quickviewContainer = el;
				var quickview = null;
				if(!quickviewContainer.hasClassName('quickviewContainer')) {
					quickviewContainer = el.up('.quickviewContainer');
				}

				if(quickviewContainer) {
					quickview = quickviewContainer.down('.quickview');
				}

				if(!quickview) {
					return false;
				}

				if(quickview.visible()) {
					return false;
				}



				// quickview.addClassName('permanent');
				QuickviewHelper.currentQuickviewLinkContainer = quickviewContainer;
				QuickviewHelper.currentQuickviewLink = quickview;
				quickview.appear({ duration: 0.3, afterFinish: function() {
						QuickviewHelper.hideQuickviews();
						QuickviewHelper.shownQuickviews.push(quickview);
					}
				});
				// shownQuickviews.push(quickview);
			}
			else {
				if(!DOMUtils.isChildOf(QuickviewHelper.currentQuickviewLinkContainer, el)) {
					// QuickviewHelper.currentQuickviewLink.removeClassName('permanent');
					var tmpEl = QuickviewHelper.currentQuickviewLink ;
					QuickviewHelper.currentQuickviewLink = null;
					QuickviewHelper.currentQuickviewLinkContainer = null;
					tmpEl.fade({ duration: 0.3, afterFinish: function() {
							QuickviewHelper.shownQuickviews.remove(tmpEl);
							//QuickviewHelper.hideQuickviews();
						}
					});

				}
			}

			return false;
		},

		hideQuickviews : function() {
			while(QuickviewHelper.shownQuickviews.length > 0) {
				var element = QuickviewHelper.shownQuickviews[0];
				element.hide();
				QuickviewHelper.shownQuickviews.remove(element);
			}
		}
};

/*
transitions.js

Based on Easing Equations v2.0
(c) 2003 Robert Penner, all rights reserved.
This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html

Adapted for Scriptaculous by Ken Snyder (kendsnyder ~at~ gmail ~dot~ com) June 2006

usage: new Effect.BlindDown(el,{duration:2, transition:Effect.Transitions.Bounce});
*/

/*
Overshooting Transitions
*/
// Elastic (adapted from "EaseOutElastic")
Effect.Transitions.Elastic = function(pos) {
return -1*Math.pow(4,-8*pos) * Math.sin((pos*6-1)*(2*Math.PI)/2) + 1;
};
// SwingFromTo (adapted from "BackEaseInOut")
Effect.Transitions.SwingFromTo = function(pos) {
var s = 1.70158;
if ((pos/=0.5) < 1) return 0.5*(pos*pos*(((s*=(1.525))+1)*pos - s));
return 0.5*((pos-=2)*pos*(((s*=(1.525))+1)*pos + s) + 2);
};
// SwingFrom (adapted from "BackEaseIn")
Effect.Transitions.SwingFrom = function(pos) {
var s = 1.70158;
return pos*pos*((s+1)*pos - s);
};
// SwingTo (adapted from "BackEaseOut")
Effect.Transitions.SwingTo = function(pos) {
var s = 1.70158;
return (pos-=1)*pos*((s+1)*pos + s) + 1;
};

/*
Bouncing Transitions
*/
// Bounce (adapted from "EaseOutBounce")
Effect.Transitions.Bounce = function(pos) {
if (pos < (1/2.75)) {
return (7.5625*pos*pos);
} else if (pos < (2/2.75)) {
return (7.5625*(pos-=(1.5/2.75))*pos + .75);
} else if (pos < (2.5/2.75)) {
return (7.5625*(pos-=(2.25/2.75))*pos + .9375);
} else {
return (7.5625*(pos-=(2.625/2.75))*pos + .984375);
}
};
// BouncePast (new creation based on "EaseOutBounce")
Effect.Transitions.BouncePast = function(pos) {
if (pos < (1/2.75)) {
return (7.5625*pos*pos);
} else if (pos < (2/2.75)) {
return 2 - (7.5625*(pos-=(1.5/2.75))*pos + .75);
} else if (pos < (2.5/2.75)) {
return 2 - (7.5625*(pos-=(2.25/2.75))*pos + .9375);
} else {
return 2 - (7.5625*(pos-=(2.625/2.75))*pos + .984375);
}
};

/*
Gradual Transitions
*/
// EaseFromTo (adapted from "Quart.EaseInOut")
Effect.Transitions.EaseFromTo = function(pos) {
if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,4);
return -0.5 * ((pos-=2)*Math.pow(pos,3) - 2);
};
// EaseFrom (adapted from "Quart.EaseIn")
Effect.Transitions.EaseFrom = function(pos) {
return Math.pow(pos,4);
};
// EaseTo (adapted from "Quart.EaseOut")
Effect.Transitions.EaseTo = function(pos) {
return Math.pow(pos,0.25);
};
