/* -------------------------------------------------------------------
	=Variables
 ------------------------------------------------------------------ */
// array with configuration infos
var config = new Hash();

var currentTabs;
var activeDisplayLayer = null;
var activeElement = null; // active LI-Element
var activeElm = null;

// handler for dropper menus
var handle = null;
var handleID = null;

// array with anonymous init-functions
var initFunctions = new Array();

/*
	covered function:
 	 - showLoadingBox (shows the AJAX Loading Box)
 	 - hideLoadingBox (hides the AJAX Loading Box)
 	 - getPageSize (calculates content-dimensions)

*/

/* -------------------------------------------------------------------
	showLoadingBox
 ------------------------------------------------------------------ */
 function showLoadingBox () {
	var arrayPageSize = getPageSize();
	var overlay = $('lightbox-overlay');
	overlay.style.width = arrayPageSize[0]+"px";
	overlay.style.height = arrayPageSize[1]+"px";
	overlay.show();
	
	var top = 0;
	if (document.documentElement && document.documentElement.scrollTop) {
		top = document.documentElement.scrollTop; 
	}
	else if (window.pageYOffset) {
		top = window.pageYOffset; 
	}  
	top = parseInt(top) + parseInt(345);

	$('lightbox').style.top = top+"px";
	$('lightbox-wrap').show();
}
/* -------------------------------------------------------------------
	hideLoadingBox
 ------------------------------------------------------------------ */
function hideLoadingBox () {
	$('lightbox-overlay').hide();
	$('lightbox-wrap').hide();
}

/* -------------------------------------------------------------------
	getPageSize
 ------------------------------------------------------------------ */
function getPageSize(){

  var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		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
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			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 = xScroll;
	} else {
		pageWidth = windowWidth;
	}

	return [pageWidth,pageHeight];
}

/*
	covered classes:
	- Pulldown (Base for all Pulldown-Menus)
	- MetaNavPulldown (Class for Pulldown-Menus in Metanav)
	- ImageCarousel (paging-handler for product-presentation images)
	- RadioButtonLayer ( toogles it )
	- FavoriteChainstore ( toggles the favorite chainstore )
	- TimeoutLayer ( shows a layer after a defined timeout)
	- TooltipImage ( shows a tooltip image )
	- ProductComparer ( activates the productComparer on defined links
	- ShoppingList ( handles all action in the shoppinglist ) 
	- Dropdown ( layer looking like selectbox )
	- Showcase2Pager
*/


/* -------------------------------------------------------------------
	=Pulldown
 ------------------------------------------------------------------ */
var Pulldown = Class.create({
	initialize: function(handle, params){
		this.handle			= $(handle);
		this.handleID	 	= this.handle.id;

		this.pulldownID		= this.handleID+'-pd';
		this.pulldown		= $(this.pulldownID);

		// params
		this.origTop 		= params.top ? params.top : 0; // hardcoded dependency to layout: needed for animations
		this.activation		= params.activation && ['mouseover','click'].indexOf(params.activation)>-1 ? params.activation : 'click';
		this.openAnimation	= params.animation ? ['open','both'].indexOf(params.animation)>-1 : false;
		this.closeAnimation	= params.animation ? ['close','both'].indexOf(params.animation)>-1 : false;

		// constants and status-vars
		this.animatingDirection	= 0; // 1=opening, -1=closing
		this.origHeight 		= 0; //this.pulldown.getHeight();
		this.currentPos			= 0; // 0=closed, 1=opened

		this.closeTimer			= null;
		this.openTimer			= null;
		this.need2Init			= 'n';
		this.startedActive		= $$('#'+this.handleID+' a')[0].hasClassName('active');

		// animation config
		this.pxPerSecond		= 750; // higher = faster
		this.fps				= 40;

		// bound function
		if (this.openAnimation || this.closeAnimation){
			this.boundClipIt 			= this.clipIt.bind(this);
			//this.initAnimation();
			this.need2Init = 'y';
		}

		this.boundClosePulldown = this.startClosePulldown.bind(this);
		this.boundOpenPulldown 	= this.startOpenPulldown.bind(this);
		this.boundMouseOver		= this.mouseover.bind(this);
		this.boundMouseOut		= this.mouseout.bind(this);

		this.initEventHandler();
	},
	initAnimation: function(){
		this.origHeight 			= this.pulldown.getHeight();
		this.transition			= Effect.Transitions.EaseFromTo ? Effect.Transitions.EaseFromTo : Effect.Transitions.sinoidal;

		// animation calc shortcuts
		this.durationInSeconds	= this.origHeight/this.pxPerSecond;
		this.secondsPerStep		= 1/this.fps;
		this.percentStepWidth 	= 1/(this.fps*this.durationInSeconds);
	},
	initEventHandler: function(){
		if (this.activation=='click'){
			$$('#'+this.handleID+' a')[0].href = 'javascript: void(0);';
			this.handle.observe('click', this.click.bind(this));
		}

		this.handle.observe('mouseover', this.boundMouseOver);
		this.handle.observe('mouseout', this.boundMouseOut);

		if (!this.handle.down('#'+this.pulldownID)){
			this.pulldown.observe('mouseover', this.boundMouseOver);
			this.pulldown.observe('mouseout', this.boundMouseOut);
		}

		this.handle.observe('pulldown:opened', this.pulldownOpenListener.bind(this));
	},
	mouseover: function(e){
		if (this.openTimer)
			window.clearTimeout(this.openTimer);
		if (this.closeTimer)
			window.clearTimeout(this.closeTimer);
		if (this.activation=='mouseover')
			if (this.currentPos!=1)
				this.openTimer = this.boundOpenPulldown.delay(0.1);
	},
	mouseout: function(e){
		if (this.openTimer)
			window.clearTimeout(this.openTimer);
		if (this.closeTimer)
			window.clearTimeout(this.closeTimer);
		this.closeTimer = this.boundClosePulldown.delay(0.1);
	},
	click: function(e){
		if (this.currentPos==1){
			this.startClosePulldown();
		} else if (this.currentPos==0){
			this.startOpenPulldown();
		} else {
			if (this.animatingDirection!=1){
				this.startOpenPulldown();
			} else {
				this.startClosePulldown();
			}
		}

		if (this.openTimer)
			window.clearTimeout(this.openTimer);
		if (this.closeTimer)
			window.clearTimeout(this.closeTimer);
	},
	// callback-listener, when a pulldown opens
	pulldownOpenListener: function(e){
		if (this.currentPos!=0 && e.memo.id!=this.handleID){
			this.startClosePulldown();
		}
	},
	startOpenPulldown: function(){

		if (this.need2Init=='y'){
			this.need2Init = 'n';
			this.initAnimation();
		}

		if (this.openTimer)
			window.clearTimeout(this.openTimer);
		if (this.closeTimer)
			window.clearTimeout(this.closeTimer);

		if (this.openAnimation){
			if (this.animatingDirection!=1){
				this.animatingDirection = 1;
				this.openPulldown();
				if ((this.currentPos==0) || (this.currentPos==1))
					this.clipIt();
			}
		} else {
			this.currentPos = 1;
			this.animatingDirection = 0
			this.openPulldown();
			if (this.closeAnimation)
				this.clipIt();
		}
	},
	startClosePulldown: function(){
		if (this.openTimer)
			window.clearTimeout(this.openTimer);
		if (this.closeTimer)
			window.clearTimeout(this.closeTimer);

		if (this.closeAnimation){
			if (this.animatingDirection!=-1){
				this.animatingDirection = -1;
				if (this.currentPos==1)
					this.clipIt();
			}
		} else {
			this.currentPos = 0;
			this.animatingDirection = 0
			this.closePulldown();
		}
	},
	openPulldown: function(){
		this.pulldown.show();

		var link = this.handle.down('a');
		if (!this.startedActive)
			link.addClassName('active');
		link.blur();

		var hdname = this.handleID;
		$$('.pd-handle').each(function(e){
			e.fire('pulldown:opened', {id: hdname});
		});
		showKillIframe(this.pulldown);
	},
	closePulldown: function(){
		if (!this.startedActive)
			$$('#'+this.handleID+' a')[0].removeClassName('active');
		this.pulldown.hide();
		//hideKillIframe();
	},
	clipIt: function() {
		this.currentPos 	= Math.max(0, Math.min(1, this.currentPos + this.animatingDirection*this.percentStepWidth));
		var factor 			= 1-this.transition(this.currentPos);
		var crop 			= Math.ceil(factor*this.origHeight);

		if (this.currentPos==0){
			this.closePulldown();
		}

		this.pulldown.setStyle({clip: 'rect('+crop+'px, auto, auto, auto)', top: (this.origTop-crop)+'px'});
		if ( (this.currentPos<1 && this.animatingDirection>0) || (this.currentPos>0 && this.animatingDirection<0) ){
			this.boundClipIt.delay(this.secondsPerStep);
		}
	}
});

/* -------------------------------------------------------------------
	=MetaNavPulldown
 ------------------------------------------------------------------ */
var MetaNavPulldown = Class.create(Pulldown, {
	startOpenPulldown: function($super){
		// specific
		if (this.handle.getWidth() > this.pulldown.getWidth()+6 ){
			this.pulldown.setStyle({width: (this.handle.getWidth() + 6) + 'px'});
		}
		$super();
	}
});

/* -------------------------------------------------------------------
	=ImageCarousel
 ------------------------------------------------------------------ */
var ImageCarousel = Class.create({
	initialize: function(elm){
		this.elm			= elm;
		this.elmID 		= elm.id;

		this.conf		= config.get(this.elmID);

		this.elmWidth	= 41;
		this.shownElms	= 8;
		this.animating	= false;

		// define the Buttons to move
		this.lft 		= elm.down('.sub-lft a');
		this.rgt 		= elm.down('.sub-rgt a');
		this.lft.href = 'javascript: void(0);';
		this.rgt.href = 'javascript: void(0);';

		this.overlay = this.elm.down('.sub-overlay');
		this.overlay.setOpacity(50);

		this.boundFinishedCallback = this.finishedCallback.bindAsEventListener(this);

		this.resetList();
		
	},
	resetList: function(){
		this.ul			= this.elm.down('ul');
		this.elms		= this.ul.childElements();
		this.maxHeight 	= this.elms.max(function(prod){
			return prod.getHeight();
		});

		//this.elmsPerPage = Math.max(0, Math.min(this.elms.length-this.shownElms, this.shownElms));
		this.elmsPerPage = 1;
		this.lftIndex	= 0;

		// add 2 cause of the border
		this.elm.down('.sub-mask').setStyle({height: this.maxHeight + 'px'});

		if (this.elms.length<=this.shownElms){
			this.lft.style.background = "url(/images/slider/left.gif)";
			this.rgt.style.background = "url(/images/slider/right.gif)";
		} else {
			this.lft.show();
			this.rgt.show();
			this.initEventHandler();
		}

		this.ul.observe('pager:finished', this.boundFinishedCallback);
	},
	initEventHandler: function(){
		this.lft.observe('click', this.turnpage.bindAsEventListener(this, 'lft'));
		this.rgt.observe('click', this.turnpage.bindAsEventListener(this, 'rgt'));
	},
	turnpage: function(e, direction){
		if (this.animating) // is false
			return;
		this.animating = true;
		var left = this.elmLeft(direction);
		for(var i=0; i<this.elmsPerPage-left; i++){
			this.move(direction);
		}

		var newPos = parseInt(this.ul.getStyle('left'))+((direction=='rgt' ? -1 : 1)*this.elmWidth*this.elmsPerPage);

		var that = this;
		this.ul.morph('left:'+newPos+'px', {
			delay: 0.4,
			duration: this.elmsPerPage * 0.35,
			transition: Effect.Transitions.EaseFromTo ? Effect.Transitions.EaseFromTo : Effect.Transitions.sinoidal,
			afterFinish: function() {
				that.ul.fire('pager:finished');
			}
		});
	},
	finishedCallback: function(e){
		this.animating = false;
	},
	elmLeft: function(direction){
		if (direction=='lft'){
			return -1*(parseInt(this.ul.getStyle('left')) / this.elmWidth);
		} else {
			return Math.max(0, this.elms.length-this.shownElms+(parseInt(this.ul.getStyle('left')) / this.elmWidth));
		}
	},
	move: function(direction){

		if (direction=='lft'){
			var elmIndex2Remove = this.lftIndex-1;
			if (elmIndex2Remove<0)
				elmIndex2Remove = this.elms.length-1;
			this.lftIndex = elmIndex2Remove;

			var current = parseInt(this.ul.getStyle('left'));
			this.ul.setStyle({left: current-this.elmWidth+'px'});
			this.ul.insert({ top: this.elms[elmIndex2Remove].remove()});
		} else {
			var elmIndex2Remove = this.lftIndex;
			this.lftIndex++;
			if (this.lftIndex>this.elms.length-1)
				this.lftIndex = 0;
			var current = parseInt(this.ul.getStyle('left'));
			this.ul.setStyle({left: current+this.elmWidth+'px'});
			this.ul.insert({ bottom: this.elms[elmIndex2Remove].remove()});
		}
	}
});

/* -------------------------------------------------------------------
	=TooltipImage
 ------------------------------------------------------------------ */
var TooltipImage = Class.create(Pulldown, {

	initialize: function(handle, params){
		this.handle				= $(handle);
		this.handleID	 		= this.handle.id;
		this.pos	 			= parseInt(this.handleID.substring(this.handleID.indexOf('symbol')+6))-1;

		this.pulldownID			= 'symbollayer';
		this.pulldown			= $(this.pulldownID);

		this.pulldownImage		= this.pulldown.firstChild;

		// params
		this.origTop 		= params.top ? params.top : 0; // hardcoded dependency to layout: needed for animations
		this.activation		= params.activation && ['mouseover','click'].indexOf(params.activation)>-1 ? params.activation : 'click';
		this.openAnimation	= params.animation ? ['open','both'].indexOf(params.animation)>-1 : false;
		this.closeAnimation	= params.animation ? ['close','both'].indexOf(params.animation)>-1 : false;

		// constants and status-vars
		this.animatingDirection	= 0; // 1=opening, -1=closing
		this.origHeight 			= 0; //this.pulldown.getHeight();
		this.currentPos			= 0; // 0=closed, 1=opened

		this.closeTimer			= null;
		this.openTimer				= null;
		this.need2Init				= 'n';
		this.startedActive		= $$('#'+this.handleID+' a')[0].hasClassName('active');

		// animation config
		this.pxPerSecond			= 200;
		this.fps						= 25;

		// bound function
		if (this.openAnimation || this.closeAnimation){
			this.boundClipIt 			= this.clipIt.bind(this);
			//this.initAnimation();
			this.need2Init = 'y';
		}

		this.boundClosePulldown = this.startClosePulldown.bind(this);
		this.boundOpenPulldown 	= this.startOpenPulldown.bind(this);
		this.boundMouseOver		= this.mouseover.bind(this);
		this.boundMouseOut		= this.mouseout.bind(this);

		this.initEventHandler();

	},

	mouseover: function(e){
		// get Image per AJAX?
		var node = null;

		if ( this.handle.firstChild && this.handle.firstChild.firstChild ){
			node = this.handle.firstChild.firstChild;
		}
		// check if node is Element
		if (node.nodeType != 1) {
			return;
		}

		// change the image src
		this.pulldownImage.src = node.src.substring (0, node.src.indexOf('40')) + '80.' + node.src.substring(node.src.length-3);

		var top = ((parseInt((this.pos / 7))+1) * 50 ) +10;
		var left = (this.pos % 7)  * 53 + 10;

		this.pulldown.setStyle ({top: '-10px', left: left+'px'}); 

		if (this.openTimer)
			window.clearTimeout(this.openTimer);
		if (this.closeTimer)
			window.clearTimeout(this.closeTimer);
		if (this.activation=='mouseover')
			if (this.currentPos!=1)
				this.openTimer = this.boundOpenPulldown.delay(0.25);
	},
	mouseout: function(e){
		if (this.openTimer)
			window.clearTimeout(this.openTimer);
		if (this.closeTimer)
			window.clearTimeout(this.closeTimer);
		this.closeTimer = this.boundClosePulldown.delay(0);
		this.pulldownImage.src = '';
	}
});

/* -------------------------------------------------------------------
	=RadioButtonLayer
 ------------------------------------------------------------------ */
var RadioButtonLayer = Class.create({
	initialize: function(elm, params){
		this.elm = elm;
		this.elmID = elm.id;

		this.showFirst = (params && params.showFirst) ? params.showFirst: false;
		this.activeClassName = (params && params.activeClassName) ? params.activeClassName: "selected";
		this.appendID = (params && params.appendID) ? params.appendID: null;

		this.radioButtons = $$('#'+this.elmID + ' input.radiobutton');
		this.activeHandle = null;
		for (var i=0;i<this.radioButtons.length;i++) {
			if (this.radioButtons[i].checked == true) {
				this.activeHandle = this.getLayerIdByButton(this.radioButtons[i]);
			}
		}
		this.initLayer();

		this.boundClick = this.click.bind(this);
		this.initEventHandler();
	},
	initEventHandler: function () {
		for (var i=0;i<this.radioButtons.length;i++) {
			this.radioButtons[i].observe('click', this.boundClick);
		}
	},
	click: function(e){
		var layerid = this.getLayerIdByButton(e.element());
		if (this.activeHandle != layerid ) {
			if (this.activeHandle) {
				var nod = $(this.activeHandle).parentNode;
				this.removeClassName(nod, this.activeClassName);
				$(this.activeHandle+"-pd").style.display = 'none';
			}

			this.appendChild($(layerid+"-pd").parentNode);
			//$(layerid+"-pd").appendChild($("fairpay"));
			this.addClassName($(layerid).parentNode, this.activeClassName);
			$(layerid+"-pd").style.display = '';
			// change StyleClass

			this.activeHandle = layerid;
		}
	},
	appendChild: function (elem) {
		if (this.appendID != null ) {
			$(this.appendID).show();
			$(this.appendID).removeClassName("nojs");
			elem.appendChild($(this.appendID));
		}
	},
	addClassName: function (nod, name) {
		nod.className = nod.className + " " + name;
	},
	removeClassName: function (nod, name) {
		nod.className = nod.className.replace(new RegExp("(^|\\s+)" + name + "(\\s+|$)"), ' ').strip();
	},
	initLayer: function () {
		// hide all Layer
		$$('.content-tab .layer').each(function(elm){
			if (elm) {
				elm.hide();
			}
		});
		// show layer with selected input-elem
		if (this.activeHandle) {
			this.addClassName($(this.activeHandle+"-pd").parentNode, this.activeClassName);
			this.appendChild($(this.activeHandle+"-pd").parentNode);
			$(this.activeHandle+"-pd").show();
		}
		else {
			// show first due config
			if (this.showFirst) {
				this.addClassName($(this.getLayerIdByButton(this.radioButtons[0])+"-pd").parentNode, this.activeClassName);
				this.appendChild($(this.getLayerIdByButton(this.radioButtons[0])+"-pd").parentNode);
				$(this.getLayerIdByButton(this.radioButtons[0])+"-pd").show();
			}
			else {
				if (this.appendID) {
					$(this.appendID).hide();
				}
			}
		}
	},
	getLayerIdByButton: function (but) {
		return (but.parentNode.id);
	}
});

/* -------------------------------------------------------------------
	=ProductComparer
 ------------------------------------------------------------------ */
var ProductComparer = Class.create({
	initialize: function(elm, params){
		this.elm = elm;
		this.elmID = elm.id;
		this.elmChecked = null;

		this.comparePrexix = (params && params.comparePrexix) ? params.comparePrexix : "compare_";
		this.methodAdd = (params && params.methodAdd) ? params.methodAdd : "add";
		this.methodDelete = (params && params.methodDelete) ? params.methodDelete : "delete";

		this.code = this.elmID.substring(this.elmID.indexOf(this.comparePrexix)+this.comparePrexix.length);
		this.categorycode = $('compare_catcode_'+this.code).value;

		this.updateStatus();

		this.boundClick = this.click.bind(this);
		this.initEventHandler();
	},
	initEventHandler: function () {
		this.elm.observe('click', this.boundClick);
	},
	click: function(e){
		this.updateStatus();
		this.ajaxCall(((this.elmChecked) ? this.methodAdd : this.methodDelete));
	},
	updateStatus: function () {
		this.elmChecked = (this.elm.checked) ? true : false;
	},
	ajaxCall: function (method) {
		var that = this;
		var params = new Hash();
		params.set(method);
		params.set("productcode", this.code);
		params.set("categorycode", this.categorycode);
		params.set("xml", "1");

		new Ajax.Request(configuration.actionProductsCompare, {
			parameters: params,
			method: 'get',
			onSuccess: that.ajaxSuccess.bind(that),
			onFailure: that.ajaxSuccess.bind(that)
		});
	},
	ajaxFailure: function (x) {
		//alert("failure");
		//TODO: Ausgabe erzeugen?
	},
	ajaxSuccess: function (response) {
		//alert("success");
	}
});

/* -------------------------------------------------------------------
	=PrefilledInput
 ------------------------------------------------------------------ */
var PrefilledInput = Class.create({
	initialize: function(elm){
		this.elm 		= elm;
		this.origValue = this.elm.title;

		// no title, no need
		if (!this.origValue)
			return;

		this.elm.observe('focus', this.focus.bind(this));
		this.elm.observe('blur', this.blur.bind(this));
	},
	focus: function(e){
		if (this.elm.value==this.origValue)
			this.elm.value='';
	},
	blur: function(e){
		if (this.elm.value=='')
			this.elm.value=this.origValue;
	}
});




/* -------------------------------------------------------------------
	=FavoriteChainstore
 ------------------------------------------------------------------ */
var FavoriteChainstore  = Class.create({
	initialize: function(handle, params){
		this.area			= $(handle);
		this.areaID	 		= this.area.id;

		this.layerID		= params.layerID ? params.layerID : "Layer"; // hardcoded dependency to layout: needed for animations
		this.layer			= $(this.layerID);

		this.selectID		= params.selectID ? params.selectID : "Select"; // hardcoded dependency to layout: needed for animations
		this.selectBox		= $(this.selectID);

		// constants and status-vars
		this.currentPos			= 0; // 0=closed, 1=opened

		this.boundMouseOver		= this.mouseover.bind(this);
		this.boundMouseOut		= this.mouseout.bind(this);
		this.boundClick			= this.click.bind(this);

		this.initEventHandler();
	},

	click: function () {
		for ( var i=0; i<this.selectBox.options.length;i++) {
			if (this.selectBox[i].value == this.area.id ) {
				this.selectBox[i].selected = true;
			}
		}
	},

	initEventHandler: function(){

		this.area.observe('mouseover', this.boundMouseOver);
		this.area.observe('mouseout', this.boundMouseOut);
		this.area.observe('click', this.boundClick);
		this.area.observe('pulldown:opened', this.pulldownOpenListener.bind(this));
	},
	mouseover: function(e){
		$$('#' + this.layerID + " .layerCity")[0].innerHTML = $("city." + this.area.id).firstChild.data;
		var html = $("address." + this.area.id).innerHTML;
		var control = $$('#' + this.layerID + " .layerAdress")[0];
		control.innerHTML = html;
		this.layer.show();
	},
	mouseout: function(e){
		this.layer.hide();
	},
	// callback-listener, when a pulldown opens
	pulldownOpenListener: function(e){
		if (this.currentPos!=0 && e.memo.id!=this.handleID){
			this.startClosePulldown();
		}
	},

	openPulldown: function(){
		this.pulldown.show();

		var link = this.handle.down('a');
		if (!this.startedActive)
			link.addClassName('active');
		link.blur();

		var hdname = this.handleID;
		$$('.pd-handle').each(function(e){
			e.fire('pulldown:opened', {id: hdname});
		});
	}
});

/* -------------------------------------------------------------------
	=RemoveButton
 ------------------------------------------------------------------ */
var RemoveButton  = Class.create({
	initialize: function(handle, params){
		this.link		= handle;
		this.href		= handle.href;

		this.link.href = "javascript:void(null)";

		this.layerId 	= params.layerId ? params.layerId : 'removeLayer';
		this.layer	= $(this.layerId);

		if (!this.layer) {
			//alert("CC hat vergessen den DeleteLayer zu inkludieren!");
		}

		this.targetLink = $$('#'+this.layerId + ' .confirmButton')[0];

		this.boundClick			= this.click.bind(this);
		this.boundClose			= this.close.bind(this);

		this.initEventHandler();
	},
	initEventHandler: function(){
		this.link.observe('click', this.boundClick);
	},
	click: function (e) {
		var y = 258; // top pos from content
		var x = 590; // width from content
		if ($('full')) {
			x = 790;
		}

		var diffX = parseInt((getPageSize()[0] - x) / 2);
		var left = ((e.clientX - diffX) > 200) ? e.clientX - diffX - 200 : e.clientX - diffX ;

		// correcr left positions
		if (left < 0) {
			left = 0;
		}
		else if (left > 540) {
			left = 540;
		}

		this.targetLink.href = this.href;

		this.layer.style.left = left+"px";
		this.layer.style.top = (e.pageY-y)+"px";
		var that = this;

		$$('#'+this.layerId + ' .closeButton').each(function(elm){
			elm.observe('click', that.boundClose);
		});
		this.layer.show();
	},
	close: function(e){
		this.layer.hide();
	}
});

/* -------------------------------------------------------------------
	=TimeoutLayer
 ------------------------------------------------------------------ */
var TimeoutLayer = Class.create({
	initialize: function(handle, params){
		this.handle			= $(handle);
		this.handleID	 	= this.handle.id;
		this.pulldownID		= this.handleID+'-pd';
		this.pulldown		= $(this.pulldownID);
		
		this.moveIframe		= params.moveIframe ? params.moveIframe : false;
		
		this.handleWidth	= this.handle.width;
		this.handleHeight	= this.handle.height;
		//this.pulldown.style.top = eval(-2*this.handleHeight) + "px";
		
		// constants and status-vars
		this.currentPos			= 0; // 0=closed, 1=opened

		this.closeTimer			= null;
		this.openTimer			= null;

		this.boundClosePulldown = this.startClosePulldown.bind(this);
		this.boundOpenPulldown 	= this.startOpenPulldown.bind(this);
		this.boundMouseOver		= this.mouseover.bind(this);
		this.boundMouseOut		= this.mouseout.bind(this);

		this.initEventHandler();
	},
	initEventHandler: function(){
		this.handle.observe('mouseover', this.boundMouseOver);
		this.handle.observe('mouseout', this.boundMouseOut);

		if (!this.handle.down('#'+this.pulldownID)){
			this.pulldown.observe('mouseover', this.boundMouseOver);
			this.pulldown.observe('mouseout', this.boundMouseOut);
		}

		this.handle.observe('pulldown:opened', this.pulldownOpenListener.bind(this));
	},
	mouseover: function(e){
		if (this.openTimer)
			window.clearTimeout(this.openTimer);
		if (this.closeTimer)
			window.clearTimeout(this.closeTimer);
		if (this.currentPos!=1)
			this.openTimer = this.boundOpenPulldown.delay(0.5);
	},
	mouseout: function(e){
		if (this.openTimer)
			window.clearTimeout(this.openTimer);
		if (this.closeTimer)
			window.clearTimeout(this.closeTimer);
		this.closeTimer = this.boundClosePulldown.delay(0.1);
	},
	// callback-listener, when a pulldown opens
	pulldownOpenListener: function(e){
		if (this.currentPos!=0 && e.memo.id!=this.handleID){
			this.startClosePulldown();
		}
	},
	startOpenPulldown: function(){

		if (this.openTimer)
			window.clearTimeout(this.openTimer);
		if (this.closeTimer)
			window.clearTimeout(this.closeTimer);

		this.currentPos = 1;
		this.animatingDirection = 0
		this.openPulldown();
		if (this.moveIframe)
			showKillIframe(this.pulldown);
	},
	startClosePulldown: function(){
		if (this.openTimer)
			window.clearTimeout(this.openTimer);
		if (this.closeTimer)
			window.clearTimeout(this.closeTimer);

		this.currentPos = 0;
		this.animatingDirection = 0
		this.closePulldown();
	},
	openPulldown: function(){
		this.pulldown.show();

		var hdname = this.handleID;
		$$('.pd-handle').each(function(e){
			e.fire('pulldown:opened', {id: hdname});
		});
	},
	closePulldown: function(){
		this.pulldown.hide();
		if (this.moveIframe)
			hideKillIframe();
	}
});

/* -------------------------------------------------------------------
	=ShoppingList
 ------------------------------------------------------------------ */
var ShoppingList = Class.create({
	initialize: function(elm, params) {
		this.layer 			= elm;
		this.layerID 		= elm.id;
		this.activationClass = (params.activationClass) ? params.activationClass : null;
		this.activationElms = null;
		
		this.action = params.action;

		this.productCode = null;
		this.shoppinglistName = null;
		this.closeLinks = null;
		this.insert = null;

		if (this.activationClass)  {
			this.activationElms = $$("." + this.activationClass);
		}

		this.boundClose			= this.close.bind(this);
		this.boundOpen			= this.show.bind(this);
		this.renderContent		= this.renderContent.bind(this);
		
		this.initEventHandler();
	},
	initEventHandler: function () {
		for (var i=0;i<this.activationElms.length;i++) {
			this.activationElms[i].observe('click', this.boundOpen);
		}
		// add close Buttons
		this.closeLinks = $$("#" + this.layerID + ' .closer');
		for (var i=0;i<this.closeLinks.length;i++) {
			this.closeLinks[i].observe('click', this.boundClose);
		}
	},
	show: function(e) {

		if (this.action == "addProduct") {
			this.determineProductCode(e);
			if (!configuration.loginstatus) {		
				//this.renderContent(configuration.shoppingListLogin+'?productcode='+this.productCode+'&insert=63&curl='+escape(document.location.href));
				this.renderContent(configuration.actionShoppingListLogin+'&productcode='+this.productCode+'&insertkennzeichen='+this.insert+'&curl='+escape(document.location.href));
			}
			else {
				this.renderContent(configuration.actionAddProductToShoppingList+'&productcode='+this.productCode+'&insertkennzeichen='+this.insert+'&curl='+escape(document.location.href));
			}
			this.layer.show();
		}
		else if (this.action == "saveCart") {
			this.determineShoppingListName();
			if (this.shoppinglistName != "") {
				if (!configuration.loginstatus) {					
					//this.renderContent(configuration.shoppingListLogin+'?shoppinglistname='+escape(this.shoppinglistName));
					this.renderContent(configuration.actionShoppingListLogin+'&shoppinglistname='+escape(this.shoppinglistName));
				}
				else {
					this.renderContent(configuration.actionSaveCartToSL+'?saveCartToShoppingList&shoppinglistname='+escape(this.shoppinglistName));
				}
				$("WishlistSave").hide();

				// update name
				//$('shoppinglistSavedName').innerHTML = this.shoppinglistName;
				//$("WishlistConfirm").show();
				//this.layer.hide();
				this.layer.show();
			}
		}
	},
	close: function(e){
		this.layer.hide();
		this.productCode = null;
		$('iframeContent').innerHTML = "";
	},
	determineProductCode: function (e) {		
		this.productCode = e.element().id.substring(e.element().id.indexOf("mc_txtlnk_")+10, e.element().id.lastIndexOf("-"));		
		if (!this.productCode) {
			this.productCode = $('plFormSku').value;			
		}
		this.insert = e.element().id.substring(e.element().id.indexOf("-")+1, e.element().id.lastIndexOf("_"));		
	},
	determineShoppingListName: function (e) {
		this.shoppinglistName = $('shoppingListInputName').value;

		// check for shoppinglistname!
		if (this.shoppinglistName == "") {
			// Update error message
			$('shoppingListInputNameError').show();
		}
		else {
			$('shoppingListInputNameError').hide();
		}
	},
	
	renderContent: function (srcdata) {
		var iframe = document.createElement("iframe");

		var src = document.createAttribute("src");
		src.nodeValue = srcdata;
		iframe.setAttributeNode(src);

		var id = document.createAttribute("id");
		id.nodeValue = "shoppingListLoginFrame";
		iframe.setAttributeNode(id);

		var height = document.createAttribute("height");
		height.nodeValue = "266";
		iframe.setAttributeNode(height);

		var width = document.createAttribute("width");
		width.nodeValue = "576";
		iframe.setAttributeNode(width);

		var scrolling = document.createAttribute("scrolling");
		scrolling.nodeValue = "no";
		iframe.setAttributeNode(scrolling);

		var frameborder = document.createAttribute("frameborder");
		frameborder.nodeValue= "0";
		iframe.setAttributeNode(frameborder);
		
		globalIframe = iframe;
		window.setTimeout("$('iframeContent').appendChild(globalIframe);", 250);
	}
});
var globalIframe = null; 


/* -------------------------------------------------------------------
	=Dropdown
 ------------------------------------------------------------------ */
var Dropdown = Class.create({
	initialize: function(elm){
		this.elm		= elm;
		this.elmID 		= elm.id;

		this.handle		= this.elm.down('.handle');
		this.list		= this.elm.down('.list');
		this.ul			= this.list.down('ul');
		this.elms		= this.ul.childElements();

		this.elm.list	= this.list;

		this.boundOpen = this.open.bindAsEventListener(this);
		this.boundOpening = this.doOpen.bindAsEventListener(this);
		this.boundClose = this.close.bindAsEventListener(this);
		this.boundClosing = this.doClose.bindAsEventListener(this);

		this.initEventHandler();
	},
	initEventHandler: function(){
		this.handle.observe('click', this.boundOpen);
	},
	open: function(e){
		this.boundOpening.delay(0.15);
	},
	doOpen: function () {
		this.list.show();
		handle = this.elm;
		handleID = this.elmID;

		this.handle.stopObserving('click');
		this.handle.observe('click', this.boundClose);

		if (handle) {
			body =$$('body')[0];
			body.observe('mouseup', this.boundClose);
		}
	},
	close: function (e) {
		if (handle == this.elm && (e.element().className == 'opener')) {
			this.boundClosing.delay(0);
		}
		else if (handle && !e.element().up('#'+handleID)) {
			this.boundClosing.delay(0);
		}
	},
	doClose: function () {
		var body =$$('body')[0];
		this.handle.stopObserving('click');
		if (handle)
			handle.list.hide();
		handle = null;
		body.stopObserving('mouseup');
		this.handle.observe('click', this.boundOpen);
	} 
});


/* -------------------------------------------------------------------
	=Showcase2Pager
 ------------------------------------------------------------------ */
var Showcase2Pager = Class.create({
	initialize: function(elm, params){
		this.elm		= elm;
		this.elmID 		= elm.id;
		this.lftBut = params.leftBut;
		this.rgtBut = params.rightBut;
		this.rgtFirstBut = params.rightFirstBut;

		this.elmWidth	= 588;
		this.shownElms	= 1;

		this.ul			= this.elm.down('ul');

		this.imageCount = $$('#' + this.elmID + ' ul img').length;
		this.position = 0;

		// define the Buttons to move
		this.lftContainer 		= elm.down('.sub-lft');
		this.rgtContainer 		= elm.down('.sub-rgt');
		this.lft 		= elm.down('.sub-lft a');
		this.rgt 		= elm.down('.sub-rgt a');
		this.lft.href = 'javascript: void(0);';
		this.rgt.href = 'javascript: void(0);';

		if (this.rgtFirstBut) {
			this.rgt.firstChild.src = this.rgtFirstBut;
		}

		this.buttonToggler = this.toggleButtons.bindAsEventListener(this);

		this.resetList();
		this.initEventHandler();
	},
	resetList: function() {
		this.ul			= this.elm.down('ul');
		this.elms		= this.ul.childElements();
		this.maxHeight 	= this.elms.max(function(prod){
			return prod.getHeight();
		});

		this.lft.firstChild.src = this.lftBut;

		this.elmsPerPage = 1;
		this.lftIndex	= 0;

		this.lftContainer.hide();
		if( this.elms.length < 2) {
			this.rgtContainer.hide();
		}
 		else { 
 			this.rgtContainer.show(); 
 		} 
	},
	initEventHandler: function(){
		this.lft.observe('click', this.turnpage.bindAsEventListener(this, 'lft'));
		this.rgt.observe('click', this.turnpage.bindAsEventListener(this, 'rgt'));
	},
	turnpage: function(e, direction){
		for(var i=0; i<this.elmsPerPage; i++){
			this.move(direction);
		}
	}, 
	toggleButtons: function () {
		if ( this.position > 0 ) {
			this.lftContainer.show();
			this.rgtContainer.firstChild.src = this.rgtBut;
		}
		else {
			this.lftContainer.hide();
			this.rgtContainer.firstChild.src = this.rgtFirstBut;
		}

		if (this.position+1 == this.elms.length ) {
			this.rgtContainer.hide();
		}
		else {
			if (this.imageCount > 1) {
				this.rgtContainer.show();
			}
		}
	},
	move: function(direction){
		var current = parseInt(this.ul.getStyle('left'));
		var newPos;

		if (direction=='lft'){
			this.position--;

			var elmIndex2Remove = this.lftIndex-1;
			if (elmIndex2Remove<0)
				elmIndex2Remove = this.elms.length-1;
			this.lftIndex = elmIndex2Remove;

			newPos = current+this.elmWidth;
		}
		else {
			this.position++;

			var elmIndex2Remove = this.lftIndex;
			this.lftIndex++;
			if (this.lftIndex>this.elms.length-1)
				this.lftIndex = 0;

			newPos = current-this.elmWidth;

		}

		var that = this; 
		this.ul.morph('left:'+newPos+'px', {
			beforeStart: function () { that.rgtContainer.hide();that.lftContainer.hide(); }, /* Ticket #1744 */
			delay: 0.0, 
			duration: 0.4, 
			transition: Effect.Transitions.EaseFromTo ? Effect.Transitions.EaseFromTo : Effect.Transitions.spring,
			afterFinish : that.buttonToggler
		});
	}
});


// big standard-initfunction
initFunctions.push(function(){
	/* Navigation */
	$$('#nav .pd-handle').each(function(elm){
		if (elm) { 
			new Pulldown(elm, {top: 27, activation: 'mouseover', animation: 'both'});
		}
	});
	/* MetaNavigation */
	$$('#metanav .pd-handle').each(function(elm){
		if (elm) {
			new MetaNavPulldown(elm, {top: 5, activation: 'mouseover', animation: 'both'});
		}
	});
	/* Init von inputfields */
	$$('.hintcontent').each(function(elm){
		if (elm) {
			new PrefilledInput(elm);
		}
	});
	/* shows a deleteLayer before executing the link */
	$$('.removeButton').each(function(elm){
		if (elm) {
			new RemoveButton(elm, {layerId: 'deleteLayer' } );
		}
	});
	/* inits the toggling mechanism in Checkout */
	$$('#tabeledContentCheckout').each(function(elm){
		if (elm) {
			new RadioButtonLayer(elm);
		}
	});
	/* Beginn: initialiserung aktivierung Produktvergleich */
	$$('.articlelist input.checkbox').each(function(elm){
		if (elm) {
			new ProductComparer(elm, { comparePrexix: 'compare_', methodAdd: 'add', methodDelete: 'delete' } );
		}
	});
	$$('.articlelist_TwoCol input.checkbox').each(function(elm){
		if (elm) {
			new ProductComparer(elm, { comparePrexix: 'compare_', methodAdd: 'add', methodDelete: 'delete' } );
		}
	});
	$$('.articlelist_varCol input.checkbox').each(function(elm){
		if (elm) {
			new ProductComparer(elm, { comparePrexix: 'compare_', methodAdd: 'add', methodDelete: 'delete' } );
		}
	});
	/* Ende: Produktvergleich */


	/* Aktivierung ShoppingList */
	$$('#content #ShoppingListLayer').each(function(elm){
		if (elm) {
			new ShoppingList(elm, {activationClass: "WishlistRegister", loginFormId: "LoginForm", action: "addProduct"});
		}
	});
	$$('#ShoppingListLayer').each(function(elm){
		if (elm) {
			new ShoppingList(elm, {activationClass: "ShoppingListSave", loginFormId: "LoginForm", action: "saveCart"});
		}
	});
	/* Ende: Aktivierung ShoppingList */


	/* Aktivierung Dropsown-Layer */
	$$('.dropdown').each(function(elm){
		if (elm) { 
			new Dropdown(elm, {top: 27, activation: 'mouseover', animation: 'both'});
		}
	});


	for (i=1; i<=150; i++){
		// change to 'dropdown_layer_{x}'
		if ($('dlayer_'+i)){
			dropper_check('dlayer_'+i, 'dlayer_'+i+'_menu', 'dlayer_'+i+'_dropdown');
		}
	}
});

/* initializing on dom:loaded... */
document.observe('dom:loaded', function(){
	if (!window._init){
		// save, that init-process already done
		window._init = true;

		for (var i=0; i<initFunctions.length; i++){
			initFunctions[i]();
		}
	}
});
/* ...  or if not available also window.load */
Event.observe(window, 'load', function(){
	if (!window._init){
		window._init = true;
		
		for (var i=0; i<initFunctions.length; i++){
			initFunctions[i]();
		}
	}
});