var FwpMagnifier = new Class({
	Implements: Options,

	options: {
		elements: 'img'
	},

	initialize: function(options) {
		this.setOptions(options);

		$$(options.elements).each(function(el, index) {
			el.addEvents({
				'mouseover': function(e) {
					this.createImgMagnifier(el.getCoordinates(), el.get('src'));
				}.bind(this),

				'mouseout': function(e) {
					this.removeImgMagnifier();
				}.bind(this),

				'mousemove': function(e) {
					this.moveImgMagnifier(el.getCoordinates(), e);
				}.bind(this)
			});
		}.bind(this));
	},

	createImgMagnifier: function(coordinates, src) {
		coordinates.left += coordinates.width + 10;

		var el = new Element('div', {
			'id': 'fwp-image-magnifier'
		}).addClass('img-magnifier').setStyles(coordinates).setStyle('background-image', 'url(' + src + ')');

		el.inject(document.body);
	},

	removeImgMagnifier: function() {
		if ($defined($('fwp-image-magnifier'))) {
			$('fwp-image-magnifier').destroy();
		}
	},

	moveImgMagnifier: function(coordinates, event) {
		if (!$defined($('fwp-image-magnifier'))) {
			return;
		}

		var x = event.page.x - coordinates.left;
		var y = event.page.y - coordinates.top;

		var bgX = ((x / coordinates.width) * 100);
		var bgY = ((y / coordinates.height) * 100);

		var bgPos = bgX.toInt() + '% ' + bgY.toInt() + '%';

		$('fwp-image-magnifier').setStyle('background-position', bgPos);
	}
});
var FwpRating = new Class({
	Implements: Options,

	options: {
		container: null,
		amount: 5
	},

	initialize: function(options) {
		this.setOptions(options);

		if (!$defined($(this.options.container))) {
			return false;
		}

		//var container = $(this.options.container).getElements('a');
		var container = $('fwp-rating-elements').getElements('a');

		var myFx = new Fx.Morph($('prod-rate'), {
		    onComplete: function(){
		        //alert('complete');
		    }
		});

		if (navigator.appVersion.indexOf('MSIE 6.0') == '-1') {
			$('fwp-box-without-ss').setStyle('display','none');               /* Js weiche f�r user ohne JS. */
			$('fwp-prod-rating-background').removeClass('none');
			$('fwp-rating-elements').removeClass('none'); 	/*			*/
		}
		$('fwp-prod-rate').setStyle('width', (productRate*23));


		container.each(function(el, index) {
			el.addEvent('mouseover', function(e) {
				myFx.pause();
				myFx.start({
				    'width': [$('prod-rate').getStyle('width').toInt(), (23 * (index + 1))]
				});
			});

			el.addEvent('mouseout', function(e) {
				myFx.pause();
				myFx.start({
					'width': [$('prod-rate').getStyle('width').toInt(), (productRate*23)]
				});
			});

			el.addEvent('click', function(e) {
				e.stop();
				//$('Product_vote').send();
				//alert('erfolgreich abgestimmt');
				$('fwp-product_vote').getElements('select').set('value', (index + 1));
				document.vote.submit();
			});
		});
	}
});

var initRegisterMenu = function() {
	// hide all register boxes
	$$('.fwp-register').setStyles({
		'display' : 'none',
		'opacity' : 0
	});

	// show first element
	$$('.fwp-register')[0].setStyle('display', 'block').fade(1);

	var displayedRegister = 0;

	$$('.fwp-switch-button').each(function(el, index) {
		el.addEvent('click', function(e) {
			if (displayedRegister == index) {
				return;
			}

			this.morph('.activeSwitchButton');

			$$('.fwp-switch-button')[displayedRegister].morph('.switchButton');

			$$('.fwp-register')[index].setStyle('display', 'block').fade(1);
			$$('.fwp-register')[displayedRegister].setStyles({
				'display' : 'none',
				'opacity' : 0
			});

			displayedRegister = index;
		});
	});
}

var initSubMenu = function() {
	var mySliders    = [];
	var subMenus     = [];
	var defaultClass = 'notActiveSubMenu';
	var morphClass   = '.activeSubMenu';

	$$('.fwp-service-box ul li a').each(function(el, index) {
		if (el.getNext() != null) {
			// create a slider for each element, so we can slide down the sub menus
			mySliders[index] = new Fx.Slide(el.getNext());

			// hide every element
			mySliders[index].hide();

			// add a default class
			el.getParents()[0].addClass(defaultClass);
		}

		// on click, we have to show/hide the sub menu for this headline
		el.addEvent('click', function(e) {
            if (this.getNext() != null) {
                e.stop();
				if (this.getParents()[0].hasClass(defaultClass)) {
					this.getParents()[0].morph(morphClass).removeClass(defaultClass).addClass(morphClass);
				} else {
					this.getParents()[0].morph('.' + defaultClass).removeClass(morphClass).addClass(defaultClass);
				}

				mySliders[index].toggle();
			 }
		});
	});
}

var mySliders    = [];
var displayedSlider = 0;

var initCartCompareSubMenu = function() {
    var mySliderInput 	= [];
    var newCartItem 	= document.URL.indexOf('#prod');
    displayedSlider     = $$('.fwp-cart-compare-box ul li.fwp-sub-link a').length - 1;

    $$('.fwp-cart-compare-box ul li.fwp-sub-link a').each(function(el, index) {
        if (el.getParent().getNext() != null && el.getParent().getNext().get('html').trim() != '') {
            // create a slider for each element, so we can slide down the sub menus
            mySliders[index]		= new Fx.Slide(el.getParent().getNext());
            mySliderInput[index] 	= el.getParent().getNext();
            // hide every element
            mySliders[index].hide();

            if (mySliders[displayedSlider] != null) {
            	mySliders[displayedSlider].slideIn();
            }

            // on click, we have to show/hide the sub menu for this headline
            el.addEvent('click', function(e) {
                if (this.getParent().getNext() != null) {
                	e.stop();

                	mySliders[index].toggle();
                	if (mySliders[displayedSlider].open) {
                		mySliders[displayedSlider].slideOut();
                	}

                	displayedSlider = index;
                }
            });
        }


    	if (el.getParent().getNext() != null && el.getParent().getNext().get('html').trim() == '') {
    		el.getParent().getNext().destroy();
    	}

    	/** IE HACK **/
    	if (navigator.appVersion.indexOf("MSIE 6") != '-1' || navigator.appVersion.indexOf("MSIE 7") != '-1') {
    		el.getParent().setStyles({'margin-bottom':'-3'});
    	}
	});

	if (newCartItem != '-1') {
		mySliders[mySliders.length-1].slideIn();
	} // open Cartbox if there have a new element.
}

var initRecommend = function() {
	$('Product_recommend').addEvent('submit', function(e) {
		e.stop();
		this.set('action', 'ajax.php?sPage=recommend&ajax=1');
	});
}

var initLogin = function() {
    var errorDiv = $$('.fwp-login-err-msg').getLast();

	$('fwp-login-form').addEvent('submit', function(e) {
	     e.stop();
	     url = '';
	     if (this.getAttribute('action') != '') {
	     	url = this.getAttribute('action').substring(0,this.getAttribute('action').lastIndexOf('/')+1);
	     }
	     this.set('action', url + 'ajax.php?sPage=login&ajax=1');

	     if (errorDiv.hasClass('loginFailed')) {
			 errorDiv.removeClass('loginFailed').addClass('ajaxLoader').empty();
	     } else {
			 errorDiv.addClass('ajaxLoader');
	     }

	     this.set('send', {
	     	onComplete: function(response) {
	          if (response == 0) {
		 		errorDiv.removeClass('ajaxLoader').addClass('loginFailed');
				errorDiv.set('html', language["loginFailed"]);
	          } else {
	          	if (location.href.indexOf('order') != '-1') { // transfer the user if he log on at the order process
	          		location.href = 'index.php?sPage=order&sCurrentStep=delpaycoupon';
	          		return;
	          	}

	          	errorDiv.removeClass('ajaxLoader').addClass('loginSuccessful');
	          	return location.reload(true);
	          	/*
	          	is not soo good...
	          	loginMsg.removeClass('ajaxLoader').addClass('loginSuccessful');
	          	$('login_box').empty();

	          	var newH2 = new Element('h2', {
          			'text': frontClientAccount
          		});

	          	var newUL = new Element('ul', {
          			'class':'CustomerLinks bullet yelloworange'
          		});
	          	var newLI 	= new Element('li');
	          	var newA 	= new Element('a', {
          			'href': accountLink,
          			'text': basicAccount
          		});

          		newA.inject(newLI);
          		newLI.inject(newUL);

	          	var newLI 	= new Element('li');
	          	var newA 	= new Element('a', {
          			'href': accountLogout,
          			'text': basicLogout
          		});

          		newA.inject(newLI);
          		newLI.inject(newUL, 'bottom');

	          	newH2.inject($('login_box'));
	          	newUL.inject($('login_box'), 'bottom');
	          	*/
	          }
	     }});

	     this.send();
	});
}

var setEvent = function (e, typ) {
	if (typ == 'blur') {
		e.addEvent('blur', function(e) {
			checkPw('fwp-password-field', 'blur');
		});
	} else {
		e.addEvent('focus', function(e) {
			checkPw('fwp-password-field', 'focus');
		});
	}

}
var checkPw = function(id, typ) {
	var obj = $(id);
	if (typ != 'blur') {
		new Element('input', {
				'type' : 'password',
				'value': '',
				'name' : obj.get('name'),
				'tabindex' : '211',
				'id'   : obj.get('id')
			}).addClass(
				obj.get('class')
			).injectBefore(obj).focus();
			obj.destroy();
			setEvent($(obj.get('id')), 'blur'); /* for the stupid Internet explorer */
	} else {
		if (obj.value == '') {
			new Element('input', {
				'type' : 'text',
				'value': passwordValue,
				'name' : obj.get('name'),
				'onFocus' : "checkPw('fwp-password-field', 'focus');",
				'tabindex' : '211',
				'id'   : obj.get('id')
			}).addClass(
				obj.get('class')
			).injectBefore(
				obj
			);
			obj.destroy();
			setEvent($(obj.get('id')), 'focus'); /* for the stupid Internet explorer */
		}
	}
}


var addProductToSide = function(place, pName) {
	var el = new Element('div', {'class': 'naviCartRow'});
	var name = new Element('span', {'html': pName}).inject(el);
	el.inject(place);
}


var FwpMoveImageToCart = function() {
	$$('.fwp-move-product-pic-to-cart').addEvent('submit', function(e) {
		e.stop();
		var form = this;
		if ($$('.fwp-variant-textfield').length > 0) {
				var quantityOfProducts = 0;
				$$('.fwp-variant-textfield').each(function(el, index) {
					if(el.value > 0) {
						quantityOfProducts += el.value;
					}
				});

				if (quantityOfProducts == 0 || (this.getElements('input[name^=aiPVId]').length > 0 && this.getElements('input[name^=aiPVId]')[0].get('value') == 0)) {
					alert(language["noQuantityOfProducts"]);
					return false;
				}
		}

		if ($defined($$('.fwp-move-pic-to-cart img')[0])) {
			var imgClone = $$('.fwp-move-pic-to-cart img')[0].clone().addClass('imgMoveToCart').setStyles($$('.prodImg img')[0].getCoordinates()).inject($('body'));
		} else {
			var imgClone = new Element('div').addClass('noImgMoveToCart').setStyles(this.getCoordinates()).inject($('body'));
		}

		var oDestinationCoordinates = $$('.fwp-cart-compare-box').getLast().getCoordinates();

		var fx = new Fx.Morph(imgClone, {
			duration: 1000,
			wait: false,
			onComplete: function(){
				imgClone.fade(0);
				imgClone.destroy();
			}
		}).setOptions({
			transition: Fx.Transitions.linear
		}).start({
		    'height': 	10,
		    'width' : 	10,
		    'left'  :   oDestinationCoordinates.left+30,
		    'top'   :   oDestinationCoordinates.top+80

		});

		this.submit();
		return true;
	});
}
var initSmallToBigPhotoGallery = function() {
	/**
	* @todo recht unschoen, neu machen bei gelegenheit
	* anleitung
	* <a href="{$aProd.aImg.GALLERY_BIG.sPath}" rel="slimbox"> fuer das grosse Bild auf der Produktdetail seite
	* sowie rel="slimbox" von den Links aus den dem Galerie-Template meist "product_gallery_mini.box.tpl" entfernen.
	*/
	$$('.fwp-galerie a').each(function(el, index) {
		el.addEvent('click', function(e) {
			e.stop();

			$$('.fwp-galerie-small-to-big img').set('src', el.get('href'));
			$$('.fwp-galerie-small-to-big a').set('href', el.get('href'));
		});
	});
}
var FwpMoveImageToSidebar = function() {
	var compareButtons = [];

	$$('#middle .buttons').each(function(el, index) {
		// on click, we have to show/hide the sub menu for this headline
		var liButtons = el.getChildren();

		liButtons.each(function(el, index) {
			if (index == 0) {
				return;
			}

			el.addEvent('click', function(e) {
				var idLink 	 = this.getChildren('a')[0].get('id');

				if (idLink === null) {
					return;
				} else {
					return; // todo
				}

				e.stop();

				var itemId 	 = idLink.substring(idLink.indexOf('_') + 1);
				var handleId = idLink.substring(0,idLink.indexOf('_'));

				if ($defined($('img_' +  itemId))) {
					var imgClone = $('img_' +  itemId).clone();
					imgClone.addClass('imgMoveToCart').setStyles($('img_' +  itemId).getCoordinates());
				} else {
					var imgClone = new Element('div');
					imgClone.addClass('noImgMoveToCart').setStyles(this.getCoordinates());
				}

				imgClone.inject($('body'));

				var sideBox = $('cartCompareBox').getChildren('ul')[0];
				var topPic = 0;

				if (handleId == "notice") {

					//We can use one Request object many times.
					var req = new Request({
						url: $(idLink).get('href') + '?bAjax=1',
						data: 'bAjax=1',

						onSuccess: function(resp) {
							if (resp != 0) {
								var oDestinationCoordinates;
								oDestinationCoordinates = $('cartCompareBox').getCoordinates();

								var oCurrentCoordinates;
								oCurrentCoordinates = imgClone.getCoordinates();

								if (!mySliders[0].open) {
									mySliders[0].slideIn();
									mySliders[displayedSlider].slideOut();
									displayedSlider = 0;
								} else {
									mySliders[0].slideIn();
								}
								topPix = 10;

								var fx = new Fx.Morph(imgClone, {
									duration: 1000,
									wait: false,
									onComplete: function(){
										imgClone.fade(0);
										imgClone.destroy();
									}
								});

								fx.setOptions({
									transition: Fx.Transitions.linear
								});

								fx.start({
								    'height': 	[imgClone.getStyle('height'), 10],
								    'width': 	[imgClone.getStyle('width'), 10],
								    'left':		[oCurrentCoordinates.left, oDestinationCoordinates.left+topPix.toInt()],
								    'top':		[oCurrentCoordinates.top, oDestinationCoordinates.top+topPix.toInt()]

								});

								addProductToSide(sideBox.getChildren('div')[0].getChildren('li.subSlide')[0], resp);
							} else {
								alert('Bitte melden Sie sich an.');
							}
						}
					}).send();


				} else {
					addProductToSide(sideBox.getChildren('div')[1].getChildren('li.subSlide')[0], itemId);

					if (!mySliders[1].open) {
						mySliders[1].slideIn();
						mySliders[displayedSlider].slideOut();
						displayedSlider = 1;
					} else {
						var sideBox = $('cartCompareBox').getChildren('ul')[0].getChildren('div')[1];
						mySliders[1].slideIn();
						displayedSlider = 1;
					}

					topPix = 50;

					var oDestinationCoordinates;
					oDestinationCoordinates = $('cartCompareBox').getCoordinates();

					var oCurrentCoordinates;
					oCurrentCoordinates = imgClone.getCoordinates();

					var fx = new Fx.Morph(imgClone, {
						duration: 1000,
						wait: false,
						onComplete: function(){
							imgClone.fade(0);
							imgClone.destroy();
						}
					});
					fx.setOptions({
						transition: Fx.Transitions.linear
					});
					fx.start({
					    'height': 	[imgClone.getStyle('height'), 10],
					    'width': 	[imgClone.getStyle('width'), 10],
					    'left':		[oCurrentCoordinates.left, oDestinationCoordinates.left+topPix.toInt()],
					    'top':		[oCurrentCoordinates.top, oDestinationCoordinates.top+topPix.toInt()]

					});
				}
			});

		});
	});
};

var initNewDeliveryAddress = function() {
	var newDeliveryBox = new Fx.Slide($('fwp-new-delivery-address'));

	if ($('fwp-new-delivery-address').getStyle('display') == 'none') {
		$('fwp-new-delivery-address').setStyle('display', '');
		newDeliveryBox.hide();
	} else {
		newDeliveryBox.show();
	}

	$$('input[name=iDeliveryAddressId]').each(function(el, index) {
		el.addEvent('click', function(e) {
			if(el.value == 'new') {
				if (newDeliveryBox.open === false) {
					newDeliveryBox.slideIn();
				}
			} else {
				if (newDeliveryBox.open === true) {
					newDeliveryBox.slideOut();
				}
			}
		});
	});
};

var initCheckGTC =  function() {
	var Checkbox		= $$('input[name=bConfirmOrder]')[0].getParent().getElement('input[type=checkbox]');
	var submitButton 	= $$('input[name=bConfirmOrder]')[0].getParent().getElement('input[type=submit]');

	if (Checkbox.get('checked') != true) {
		submitButton.setStyle('opacity', '0.5');
	}

	Checkbox.addEvent('click', function(e) {
		if (Checkbox.get('checked') == true) {
			submitButton.fade(1);
		} else {
			submitButton.fade(0.5);
		}
	});

	submitButton.addEvent('click', function(e) {
		if (Checkbox.get('checked') != true) {
			alert(language["gtcRequired"]);
			e.stop();
		}

	});
}

var intCatProductPreview = function() {
	$$('.fwp-preview-img').each(function(el) {
      el.addEvents({
        'mouseenter' : function(e) {
         var el = new Element('img', {
            'src': this.getProperty('src'),
            'id' : 'fwp-preview-image-visible'
         }).setStyles({
            'position': 'absolute',
            'top': (e.page.y + 15),
            'left': (e.page.x + 35)
         });
         el.injectInside(document.body);

         this.addEvent('mousemove', function(e) {
            el.setStyles({
              'top': (e.page.y + 15),
              'left': (e.page.x + 35)
            });
         });
        },

        'mouseleave': function(e) {
            this.removeEvent('mousemove', function() {});

            if ($defined($('fwp-preview-image-visible'))) {
                 $('fwp-preview-image-visible').destroy();
            }
        }

      });
   });
}
var moveObject = function(oObject, iMoveLeft, iMoveTop) {
	oObject.setStyle('top', oObject.getStyle('top') + iMoveTop);
	oObject.setStyle('left', oObject.getStyle('left') + iMoveLeft);
};

var initHoverCompareRow = function() {
	/*
	$$('td.compare_headings').getElements('td').each(function(el, index) {
		el.addEvent('mouseenter', function(e) {
					this.addClass('mt-compareHover');
		});
		el.addEvent('mouseleave', function(e) {
					this.removeClass('mt-compareHover');
		});
	});

	$$('td.compare.column').each(function(el, index) {
		el.addEvent('mouseenter', function(e) {

		});
	}); */

}
compareCols = [];
var initComparePositionSwitcher = function() {
	compareCols.empty();
	$$('td.compare_column').each(function(el, index) {
		compareCols[index] = (el.get('id') == 'mt_' + index) ? el : el.set('id', 'mt_' + index);
	});

	if (compareCols.length > 0 && !compareCols[compareCols.length-1].hasClass('last-cell')) {
		compareCols[compareCols.length-1].addClass('last-cell');
	}
	initHoverCompareRow();
	$$('.compare_column a.mt-changePosition').each(function(elem, index) {
		elem.addEvent('click', function(e) {
			e.stop();
			var direction	= this.get('href').substring(1, this.get('href').length);
			var inOfCol 	= ($defined(this.getParents('td.compare_column')[0])) ? this.getParents('td.compare_column')[0].get('id').substring(3,this.getParents('td.compare_column')[0].get('id').length) : '' ;

			if (direction != 'left' && direction != 'right') {
				return '';
			}

			if (direction != "" && inOfCol != "") {
				if (direction == 'left')  	{ var newCol= inOfCol-1;
				} else { var newCol= (parseInt(inOfCol)+1); }
				if ($type(compareCols[newCol]) !== false) {
					var tempHtml = compareCols[inOfCol].get('html');
					compareCols[inOfCol].empty();
					compareCols[inOfCol].set('html',compareCols[newCol].get('html'));
					compareCols[newCol].set('html',tempHtml);
					initComparePositionSwitcher();
					initCompareDeleteLinks();
				} else {
					return false;
				}
			}
		});
	});
}

var initChangeCompareBoxes = function (direction, response) {
	var tempHtml;
	var newDirec;

	for (var i=0; i<compareCols.length;i++) {
		newDirec 		= (i - parseInt(direction));
		if (newDirec != '-1' && $defined(compareCols[i+1])) {
			tempHtml = compareCols[i+1].get('html');
			compareCols[newDirec].set('html', tempHtml);
		}
	}
	compareCols[compareCols.length-1].empty();
}


var initHideOverlay = function(elem, speed) {
	if (!$defined($('overLayContentBox'))) {
		return false;
	}

	if (typeof speed == 'undefined') {
		elem.setStyles({
			'visibility':'hidden',
			'display': 'none'
		});
		$('overLayContentBox').destroy();
	} else if (speed == 'slow') {
		$('overLayContentBox').setStyle('overflow', 'hidden');
		var morphFx = new Fx.Morph($('overLayContentBox'), {
			duration: 1000,
			wait: false,
			onComplete: function(){
				elem.setStyles({
					'visibility':'hidden',
					'display': 'none'
				});
				$('overLayContentBox').destroy();
			}
		});

		morphFx.start({
			'height': 0,
			'width' : 0
		});
	}

	return true;
}
var initOverLay = function() {
	if ($defined($('lbOverlay'))) {
		if (!$('lbOverlay').hasClass('compareUse')) {
			$('lbOverlay').addEvent('click', function(e) {
				e.stop();
			  	initHideOverlay(this);
			});
		}

		return $('lbOverlay').setStyles({
			'visibility':'visible',
			'display': 'block',
		   'width': window.getSize().x,
		   'height': window.getScrollHeight(),
		   'opacity': '0.5'
		}).addClass('compareUse');
	}
}
var initAjaxLoaderIcon = function(element) {
	new Element('div',{
	'id': 'temp-ajaxloader'
	}).addClass('mt-ajaxLoader').setStyles({
		'width' : '20px',
		'height': '20px',
		'top': (element.getSize().y/2)-20,
		'left': (element.getSize().x/2)-20
	}).injectInside(element);
	//(element.getStyle('left').toInt()+element.getStyle('margin-left').toInt()-element.getSize().x/2)
}
var initOverlayContentBox = function(middle, center) {
	if ($defined($('overLayContentBox'))) {
		return $('overLayContentBox');
	}
	return new Element('div', {
			'id' : 'overLayContentBox'
	}).addClass('compareContent').setStyles({
			'top': Math.max(0, middle - (200 / 2)) + 'px',
			'left': center + 'px'
    });

}


var startCompare = function (href) {
	    var win        = window;
		var middle 	   = win.getScrollTop() + (win.getHeight() / 2);
		var center 	   = (win.getWidth() / 2);
		var overlay    = initOverLay();
		var ContentBox = initOverlayContentBox(middle, center);

        var reqUrl = (href == null) ? 'ajax.php' : 'ajax.php' + href.substring(href.indexOf('?'), href.length);

        var host = '';
		if (language["accountLink"] != null) {
			host = language["accountLink"].substring(0, language["accountLink"].lastIndexOf('/')+1);
		}

		if (reqUrl.indexOf('compare') == '-1') {
        	reqUrl += '?sPage=compare';
        }

        if ($$('.fwp-product-compare-table').length > 0) {
        	$('overLayContentBox').getElements('table.fwp-product-compare-table').setStyle('opacity', '0.2');
        	initAjaxLoaderIcon($('overLayContentBox'));
        }

        var req = new Request({
            method: 'get',
            url: host + reqUrl,
            data: {
            	'ajax' : '1'
             },
            onRequest: function() {
            	overlay.injectInside(document.body);
       			ContentBox.injectInside(document.body);
        		initAjaxLoaderIcon(ContentBox);
            },
           onComplete: function(response) {
           		ContentBox.set('html', response);
           		if ($$('.fwp-product-compare-table').length == 0) {
                   return;
                }

                var compareTable = $$('.fwp-product-compare-table').getLast();

           		var iWidth  = compareTable.getElements('td.compare_column').length * 120 + 220;
           		/** 30 per row and 160 for the big picture **/
           		var iHeight	= compareTable.getElements('td.last-cell')[0].getElements('td').length * 30 + 160 ;

				ContentBox.setStyle('left',center);
           		compareTable.setStyle('display','none');
           		ContentBox.injectInside(document.body);
           		var morphFx = new Fx.Morph('overLayContentBox', {
					duration: 1000,
					wait: false,
					onComplete: function(){
						compareTable.setStyle('display','');
					}
				});
				morphFx.start({
			    		'height': 	[300, iHeight],
			    		'width': 	[200, iWidth],
			    		'margin-left': 	[-150, '-'+(iWidth/2)]
				});
				initCompareDeleteLinks();
           		initComparePositionSwitcher();
           }
        }).send();
}

var initCompareOverLayBox = function() {
	$$('.fwp-product-compare').each(function(el, index) {
		el.addEvent('click', function(e) {
			e.stop();
			startCompare(this.get('href'));
		});
	});

}

var resetBorder = function() {
	this.setStyle('border-collapse','collapse');
}

var initCompareDeleteLinks = function() {
	$$('.mt-deleteCompare').each(function(el, index) {
		el.addEvent('click', function(e) {
			e.stop();
			var req = new Request({
	            method: 'get',
		       data: { 'ajax' : '1' },
	            url: el.get('href'),
	            onRequest: function() {
					$('overLayContentBox').getElements('table.fwp-product-compare-table').setStyle('opacity', '0.2');
		        	initAjaxLoaderIcon($('overLayContentBox'));
	            },
	           onComplete: function(response) {
	            	$('temp-ajaxloader').destroy();
	           	$('overLayContentBox').getElements('table.fwp-product-compare-table').setStyle('opacity', '1');
	           	if (response == 1) {
		           	var tempBox = new Element('div', {
						'class' : 'mt-tempbox'
						}).setStyles({
							'overflow': 'hidden'
					});
					var compareCol = el.getParents('td.compare_column')[0];
					tempBox.injectInside(compareCol).set('html', compareCol.getFirst().get('html'));
					compareCol.getFirst().destroy();


					var morphFx = new Fx.Morph(tempBox, {
						duration: 1000,
						wait: false,
						onComplete: function() {
							compareCol.destroy();
							// if the is no item on the list, close the overlay
							if ($$('.compare_column').length < 1) {
								initHideOverlay($('lbOverlay'), 'slow');
							}
							// init the links etc. new
							initComparePositionSwitcher();
							// a hack for the Firefox to set the right border
							if (Browser.detect().name == 'gecko') {
								$$('table.fwp-product-compare-table')[0].setStyle('border-collapse','separate');
								resetBorder.delay(200,$$('table.fwp-product-compare-table')[0]);
							}

						}
					});
					morphFx.start({
						'height': 	[tempBox.getSize().y, 0],
						'width': 	[tempBox.getSize().x,0]
					});

	           	} else {
	           		return '';
	           	}

	           }
	        }).send();

		});
	})
}

var partingPoint = 3;
var setDotsToNumber = function (number, parting) {
	var parting = (typeof parting == 'undefined') ? parseInt(partingPoint) : parseInt(parting) ;
	var numLen  = number.indexOf(',');

	if (numLen > parting) {

		var i	= parseInt(numLen);

		while (i > 0) {
			if (i != numLen) {
				number = number.substring(0, i) + '.' + number.substring(i, number.length);
			}
			i -= parting;
		}

	}
	return number;
}

var setOptionPrice = function() {
	var reqUrl = 'ajax.php?sPage=getOptionPrice';
	$$('select[name^=iOptionId]').each(function(el, index) {
		el.addEvent('change', function(e) {
			var classes  = el.getProperty('class').split(' ');
			var iPVId    = classes[0].substring(classes[0].lastIndexOf('-')+1,classes[0].length);

			if (iPVId == '') {
				return;
			}

			var host = '';
			if (this.form.getAttribute('action') != '') {
				host = this.form.getAttribute('action').substring(0,this.form.getAttribute('action').lastIndexOf('/')+1);
			}

			var option   = new Array('', '', '');

			$$('.' + classes[0]).each(function(elem,i) {
				option[i] = elem.options[elem.selectedIndex].getAttribute('value');
			});

			var dQuantity = 0;

			if ($$('input[name^=aiPVId[' + iPVId + ']]').length > 0) {
				dQuantity = $$('input[name^=aiPVId[' + iPVId + ']]')[0].get('value');
			} else {
				dQuantity = $$('input[name=dQuantity]')[0].get('value');
			}

			var oldPrice = null;

			new Request({
	            method: 'post',
	            url: host + reqUrl,
	            data: {
	            	'ajax'       : '1',
	            	'iOptionId1' : option[0],
	            	'iOptionId2' : option[1],
	            	'iOptionId3' : option[2],
	            	'iPVId'      : iPVId,
	            	'dQuantity'  : dQuantity
	             },
	            onRequest: function() {
	            	if ($$('input[name=dQuantity]').length > 0) {
	            	    if ($$('p.fwp-price').length > 0) {
    	            		$$('p.fwp-price')[0].addClass('ajaxLoader').set('html', '&nbsp;&nbsp;&nbsp;&nbsp;');
                        }
	            	} else {

		           		$$('input[name^=aiPVId]').each(function(el, index) {
		           			if (el.get('name').indexOf('aiPVId[' + iPVId + ']') != '-1') {
		           				$('fwp-product-variant-price-' + index).getParent().addClass('ajaxLoader');
		           				oldPrice = $('fwp-product-variant-price-' + index).get('html');
		           				$('fwp-product-variant-price-' + index).set('html','');
		           			}
		           		});
	            	}
	            },
	           onComplete: function(response) {
	           		if (response == '0') {
	           			response = oldPrice;
	           		}

	            	if ($$('input[name=dQuantity]').length > 0) {
	            	    if ($$('.fwp-price').length > 0) {
	            		     $$('.fwp-price')[0].removeClass('ajaxLoader').set('html',response);
	            		}
	            	} else {
		           		$$('input[name^=aiPVId]').each(function(el, index) {
		           			if (el.get('name').indexOf('aiPVId[' + iPVId + ']') != '-1') {
		           				$('fwp-product-variant-price-' + index).getParent().removeClass('ajaxLoader');
		           				$('fwp-product-variant-price-' + index).set('html', response);
								initCalcVariantPrice();
								$$('input[name^=aiPVId[' + iPVId + ']]')[0].fireEvent('keyup');
								return;
		           			}
		           		});
	            	}
	           		return;
	           }
           }).send();
		});
	});

}

var initCalcVariantPrice = function() {
	var preis 		= [];
	var currIcon	= '';

	$$('.fwp-variant-textfield').each(function(el, index) {
		el.addEvent('keyup', function(event) {
			if ($type(preis[index]) === false) {
				if ($('fwp-product-variant-price-' + index).get('text').indexOf('.') == '-1') {
					preis[index] = $('fwp-product-variant-price-' + index).get('text').trim().split(' ');
				} else {
					preis[index] = $('fwp-product-variant-price-' + index).get('text').replace(/\./g,'').trim().split(' '); /* 'highlighting error */
					partingPoint = $('fwp-product-variant-price-' + index).get('text').indexOf(',')-1 - $('fwp-product-variant-price-' + index).get('text').lastIndexOf('.');
				}

				// set currency icon if the price is a number!!

				if (currIcon == '' && $type(preis[index][preis[index].length-2].replace(/,/g,'.').toFloat()) == 'number') {
					currIcon = preis[index].getLast();
				}

			}

			var gesamtSumme 	= 0;
			var gesamtAnzahl	= 0;
			for (var i=0; i < $$('.fwp-variant-textfield').length; i++) {
				if ($type($$('.fwp-variant-textfield')[i].get('value').toInt()) == 'number' && $type(preis[i]) !== false) {
					gesamtSumme  += ($type(preis[i][preis[i].length-2].replace(/,/g,'.').toFloat()) != 'number') ? 0 : $$('.fwp-variant-textfield')[i].get('value').toInt() * (preis[i][preis[i].length-2].replace(/,/g,'.'));
					gesamtAnzahl += $$('.fwp-variant-textfield')[i].get('value').toInt();
				}
			}

			$$('.fwp-variant-quantity').getLast().set('value', gesamtAnzahl);
			$('fwp-product-variant-price-all').set('text', setDotsToNumber(gesamtSumme.toFixed(2).replace(/\./g,',')) + ' ' + currIcon);
		});
	});
};

var closeLayer = function (e) {
		e.morph('.smallSubscriptionLayer');
			$$('.subscriptionLayer').morph('.smallSubscriptionLayer');
			    ( function(){
			      $$('.subscriptionLayer').destroy();
			    }).delay(500, this);
			return false;
	return false;
}

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
Slimbox.scanPage = function() {
	$$(document.links).filter(function(el) {
		return el.rel && el.rel.test(/^slimbox/i);
	}).slimbox({/* Put custom options here */}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
};
var initValidateVars = function () {
    if (typeof language != 'object') {
        return;
    }

    $each(language, function(value, index){
        language[index] = value.replace(/&amp;/g,'&');
    });

	if ($$('input[name=sSearch]').length == 1) {
		searchValue	= $$('input[name=sSearch]')[0].value;
	} else if ($$('input[name=sSearch]').length > 0) {
		searchValue	= $$('input[name=sSearch]').getLast().value;
	}

	if ($$('input[name=sMailAddressLogin]').length == 1) {
		emailValue 	  = $$('input[name=sMailAddressLogin]')[0].value;
		passwordValue = $$('input[name=sPasswordLogin]')[0].value;
	} else if ($$('input[name=sMailAddressLogin]').length > 0) {
		emailValue 	  = $$('input[name=sMailAddressLogin]').getLast().value;
		passwordValue = $$('input[name=sPasswordLogin]').getLast().value;
	}
}

var resetInputValues = function(param, value) {
	if ($$('input[name='+param+']').length == 1) {
		var el = $$('input[name='+param+']')[0];
	} else {
		var el = $$('input[name='+param+']').getLast();
	}

	el.addEvents({
        'focus' : function(e) {
    		if (this.value == value) {
    			this.value = '';
    		}
        },

        'blur' : function(e) {
    		if (this.value == '') {
    			this.value = value;
    		}
        }
	});
}

/** INIT VARS **/
var searchValue   = null;
var emailValue    = null;
var passwordValue = null;

window.addEvent('domready', function() {
	// Register funktion auf der Produktseite.
	if ($$('.fwp-register').length > 0) {
		initRegisterMenu();
	}

	if($defined($$('.fwp-galerie'))) {
		initSmallToBigPhotoGallery();
	}

	var searchField = $$('input[name="sSearch"]');

	if (searchField.length > 0) {
		var tmp = searchField[0].getParent();

		while(tmp.get('tag') != 'form') {
			tmp = tmp.getParent();
		}

		tmp.addEvent('submit', function(e) {
			if (searchField[0].get('value').trim() == 'Suchbegriff' || searchField[0].get('value').trim() == '') {
				new Event(e).stop();
				return false;
			}
		});
	}

	if ($defined(language["currentLanguage"])) {
		initValidateVars();
	}

	if (document.getElementsByName('sSearch').length > 0) {
		resetInputValues('sSearch', searchValue);
	}
	if ($$('.fwp-service-box').length > 0) {
		initSubMenu();
	}

	if ($$('.fwp-cart-compare-box').length > 0) {
		initCartCompareSubMenu();
	}

	if ($defined($('fwp-password-field'))) {
		$('fwp-password-field').addEvent('focus', function(e) {
			checkPw('fwp-password-field', 'focus');
		});
	}
	if ($defined($('fwp-login-form'))) {
		initLogin();
		resetInputValues('sMailAddressLogin', emailValue);
	}

	var mag = new FwpMagnifier({
		elements: '.fwp-magnifier img'
	});

    /**
	var productRating = new FwpRating({
    		container: 'fwp-prod-rate'
	});
	**/

	if($defined($('fwp-new-delivery-address'))) {
		initNewDeliveryAddress();
	}

	if ($defined($$('#compare'))) {
		//FwpMoveImageToSidebar();
	}

	if ($defined($$('.mt-preview-img'))) {
		intCatProductPreview();
	}

	if ($$('.fwp-move-product-pic-to-cart').length > 0) {
		FwpMoveImageToCart();
	}

	if ($$('input[name=bConfirmOrder]').length > 0) {
		initCheckGTC();
	}

	if ($$('.fwp-variant-textfield').length > 0) {
		initCalcVariantPrice();
	}

    /**
	if ($$('.compare_column').length > 0) {
		initComparePositionSwitcher();
	} **/

	if ($defined($$('.mt-pagebrowser'))) {
		initCompareOverLayBox();
	}

	if ($$('select[name^=iOptionId]').length > 0) {
		setOptionPrice();
	}

	// check for slimbox usage
	Slimbox.scanPage();

	if ($defined($('show-ps-layer')) && $defined($('ps-layer'))) {
		$('show-ps-layer').addEvent('mouseover', function(e) {
			var y = this.getCoordinates().top + 20;

			$('ps-layer').setStyles({
				'display': 'block',
				'top': '' + y + 'px',
				'left': '' + this.getCoordinates().left + 'px'
			});
		});

		$('show-ps-layer').addEvent('mouseout', function(e) {
			$('ps-layer').setStyle('display', 'none');
		});
	}
});
