var Obi = jQuery.extend(Obi || {}, {

	 /**
	 * darkMask  
	 * This function manipulate the soft darken of the screen
	 * @param pos - no parameters
	 */
	darkMask: {
		flag: {},
		darkMaskEvent: function() { // turn on or off the soft dark mask
			var softDarkMask = $('#darkMask');
			$('#darkMask').stop(true);
			if (arguments[0]) {
				softDarkMask.css({'height':document.body.offsetHeight, 'zIndex': arguments[0]});
				softDarkMask.show();
			}
			else {
				softDarkMask.hide();
			}
		}
	}
});

var Event = function()
{
	var EventColl = [];
	var counter = 0;
	
	function Event()
	{
		var self = this;
		
		this.addEvent = function(oElement, handler, callback, capture)
		{
			if(oElement) {
				if (oElement.addEventListener)
				{
					oElement.addEventListener(handler, callback, capture);
				}
				else if(oElement.attachEvent)
				{
					var prop = [handler, callback].join("");
					if (oElement[prop]) { return; }
					
					if (!EventColl[oElement._eventid])
					{
						oElement._eventid = counter++;
						EventColl[oElement._eventid] = {'oElement' : oElement};
					}
					EventColl[oElement._eventid][prop] = [handler, callback];
					
					oElement[prop] = function()
					{
						callback.call(oElement, event);
					};
					oElement.attachEvent('on' + handler, oElement[prop]);
				}
			}
		};
		
		this.removeEvent = function(oElement, handler, callback, capture)
		{
			if (oElement.removeEventListener)
			{
				oElement.removeEventListener(handler, callback, capture);
			}
			else if (oElement.detachEvent)
			{
				var prop = [handler, callback].join("");
				if (oElement[prop])
				{
					oElement.detachEvent('on' + handler, oElement[prop]);
					oElement[prop] = null;
					EventColl[oElement._eventid][prop] = null;
				}
			}
		};
		
		function breakEventLeak()
		{
			var curr = null;
			var j = null;
			for (var i = 0, len = EventColl.length; i < len; i++)
			{
				curr = EventColl[i];
				for (j in curr)
				{
					if (j != 'oElement')
					{
						self.removeEvent(curr.oElement, curr[j][0], curr[j][1]);
					}
				}
				curr.oElement._eventid = null;
			}
			EventColl = null;
			counter = null;
		}
		//if (window.attachEvent) window.attachEvent('onunload', breakEventLeak);
	}
	return new Event();
}();

Event.preventDefault = function(event)
{
	event.returnValue = false;
	if (event.preventDefault)
	{
		event.preventDefault();
	}
};

Event.stopPropagation = function(event)
{
	if (event.stopPropagation)
	{
		event.stopPropagation();
		return;
	}
	event.cancelBubble = true;
};

function center(elementbox) {
	
	var wrap = $('body'),
		wnd = $(window), 
		doc = $(document),
		pTop = doc.scrollTop(),
		pLeft = doc.scrollLeft(),
		minTop = pTop;
	elementbox = $('#'+elementbox);
				
	pLeft += (wrap.width() - elementbox.outerWidth()) / 2;
	pTop += (wnd.height() - elementbox.outerHeight()) / 2.5;
	pTop = Math.max(pTop, minTop);
	elementbox.css({top: pTop, left: pLeft});
}


function TabsMenu(properties)
{
	var active_class = properties.active_class || 'active_tab';
	var active_index = properties.active_tab_index || 0;
	var tabs_holder = document.getElementById(properties.tabs_root_id);
	
	if (!tabs_holder) { return; }
	
	var tabs = tabs_holder.getElementsByTagName(properties.tabs_tag_name);
	var change_event = properties.change_event || 'click';
	var onChange = properties.onChange;
	var replacer = new RegExp('\\s*' + active_class + '\\s*');
	var self = this;
	
	this.setActiveTab = function(index)
	{
		if (index < 0 || index >= tabs.length) { return; } 
		
		if (typeof onChange == 'function')
		{
			onChange(properties.tabs_root_id, index, active_index); 
		}
		
		$(tabs).removeClass(active_class);
		$(tabs[index]).addClass(active_class);
				
		active_index = index;
		Cufon.refresh('.tabs_menu a');
	};
	
	this.nextTab = function()
	{
		var curr = active_index;
		this.setActiveTab((++curr >= tabs.length ? 0 : curr)); 
	};
	
	this.prevTab = function()
	{
		var curr = active_index;
		this.setActiveTab((--curr < 0 ? tabs.length - 1 : curr));
	};
	
	
	for (var i = 0, len = tabs.length; i < len; i++)
	{
		Event.addEvent(tabs[i], change_event, 
			(function(index){
				return function(e){self.setActiveTab(index); Event.preventDefault(e);};
			})(i), false);
	}
	var button_obj = null;
	if (button_obj == document.getElementById(properties.prev_button_id))
	{
		Event.addEvent(button_obj, change_event, function(e){self.prevTab(); Event.preventDefault(e);}, false);
	}
	if (button_obj == document.getElementById(properties.next_button_id))
	{
		Event.addEvent(button_obj, change_event, function(e){self.nextTab(); Event.preventDefault(e);}, false);
	}
	
	this.setActiveTab(active_index);
	
	this.getActiveTab = function()
	{
		return active_index;
	};
}

/* 
	- Implements optgroup
	- Implements remove Option
	- Implements parse html select
	-Fix selected for IE
	-Implements disabled select
*/

function getOffsetElement(element)
{
	var top = 0, 
		left = 0;
	while(element)
	{
		top += element.offsetTop;
		left += element.offsetLeft;
		element = element.offsetParent;
	}
	
	var offset = [left, top];
	return offset;
}

function OptionItem(properties)
{
	var option = document.createElement('option');
	for (var i in properties) {
		option[i] = properties[i];
	}
	return option;
}

var ComboBox = function()
{
	var instance = false;
	var instance_coll = [];
	
	function ComboBox(properties, html_select)
	{		
		var custom_combo_box = document.createElement('div');
			custom_combo_box.className = properties.className || 'comboBox';
			if (properties.width) { custom_combo_box.style.width = properties.width + 'px'; }
			if (properties.height) { custom_combo_box.style.height = properties.height + 'px'; }
			custom_combo_box.innerHTML = '<span class="dd_arrow"></span><label></label>';
			
		var combo_box = html_select || document.createElement('select');
			combo_box.className = 'hidden_component';
			if (properties.name) { combo_box.name = properties.name; }
			if (properties.id) { combo_box.id = properties.id; }
			if (properties.onChange || html_select.onchange) { combo_box.onchange_listener = html_select.onchange || properties.onChange; }
			combo_box.custom_combo_box = custom_combo_box;
			custom_combo_box.select = combo_box;
		var curr_parent = combo_box;
		
		this.addOption = function(OptionItem)
		{
			if (window.addEventListener)
			{
				curr_parent.appendChild(OptionItem);
				return;
			}
			combo_box.add(OptionItem);
		};
		
		/*this.addOptgroup = function(label_text)
		{
			curr_parent = document.createElement('optgroup');
			curr_parent.label = label_text || '';
			combo_box.appendChild(curr_parent);
		}*/
		
		this.flushOptions = function()
		{
			combo_box.options.length = 0;
		};
		
		this.renderComboBox = function(parentCombo)
		{
			var parent_combobox = document.getElementById(parentCombo) || parentCombo;
			ComboBox.setUpdateText.call(combo_box, null, true);
			
			if (combo_box.addEventListener)
			{
				combo_box.addEventListener('keyup', combo_box.blur, false);
				combo_box.addEventListener('keyup', combo_box.focus, false);
			}
			
			Event.addEvent(combo_box, 'change', ObserverDropDown.moveKeySelected, false);
			Event.addEvent(combo_box, 'change', ComboBox.setUpdateText, false);
			Event.addEvent(combo_box, 'keydown', ObserverDropDown.checkKey, false);
			Event.addEvent(combo_box, 'focus', ComboBox.focus, false);
			Event.addEvent(combo_box, 'blur', ComboBox.blur, false);
			
			parent_combobox.appendChild(combo_box);
			
			Event.addEvent(custom_combo_box, 'click', ObserverDropDown.showDropDown, false);
			
			parent_combobox.appendChild(custom_combo_box);
		};
		
		if (!instance)
		{
			if (document.body)
			{
				ObserverDropDown.initDropDown();
			}
			else 
			{
				Event.addEvent(window, 'load', ObserverDropDown.initDropDown, false);
			}
			
			instance = true;
		}
		
		if (!window.XMLHttpRequest)
		{
			instance_coll[instance_coll.length] = custom_combo_box;
		}
	}
	
	/*Prevent memory leak in IE6*/
	if (!window.XMLHttpRequest)
	{
		window.attachEvent('onunload', function()
		{
			for (var i = 0, len = instance_coll.length; i < len; i++)
			{
				instance_coll[i].select.custom_combo_box = null;
				instance_coll[i].select = null;
			}
		});
	}
	
	return ComboBox;
}();

ComboBox.setUpdateText = function(event, onchange_flag)
{
	if (this.selectedIndex >= 0)
	{
		var option = this.options[this.selectedIndex];
		this.custom_combo_box.getElementsByTagName('label')[0].innerHTML = 
		(option.title ? '<img src="' + option.title + '" alt="" />' : '') + option.text;
		if (!onchange_flag && this.onchange_listener instanceof Function)
		{
			this.onchange_listener(this);
		}
	}
};

ComboBox.setSelectedIndex = function(index)
{
	if (index >= 0)
	{
		this.selectedIndex = index;
		
		ComboBox.setUpdateText.call(this);
	}
};

ComboBox.focus = function()
{	
	this.custom_combo_box.getElementsByTagName('label')[0].className = 'combo_box_focus';
};

ComboBox.blur = function()
{
	this.custom_combo_box.getElementsByTagName('label')[0].className = '';
};

var ObserverDropDown = function()
{
	function ObserverDropDown()
	{
		var drop_down_id = 'dropDownComboBox';
		var selected_class_name = 'selectedIndex';
		
		var drop_down = null;
		var curr_combo_box = null;
		var default_selected_index = null;
		var old_selected_index = null;
		var self = this;
		
		this.initDropDown = function()
		{
			drop_down = document.createElement('div');
				drop_down.id = drop_down_id;
			var drop_down_style = drop_down.style;
				drop_down_style.position = 'absolute';
				drop_down_style.zIndex = '100000';
				drop_down_style.display = 'none';
				
				Event.addEvent(drop_down, 'scroll', self.focusSelect, false);
				
			document.body.appendChild(drop_down);
		};
		
		this.showDropDown = function(event)
		{
			this.select.focus();
			if (this != curr_combo_box)
			{
				curr_combo_box = this;
				drop_down.className = curr_combo_box.select.id+'_drop_down';
				default_selected_index = old_selected_index = curr_combo_box.select.selectedIndex;
				positionResizeDropDown();
				renderOptions();
				drop_down.style.display = 'block';
				drop_down.scrollTop = getSelectedOffset();
				Event.stopPropagation(event);
				
				curr_combo_box.style.position = 'relative';
				curr_combo_box.style.zIndex = '1000';
				$('.box.navi').toggleClass('inactive');
				if ( $(this).hasClass('select_dark_mask') ) {
					Obi.darkMask.darkMaskEvent(550);					
				}
								
				Event.addEvent(document, 'click', self.hideDropDown, false);
				Event.addEvent(window, 'resize', self.hideDropDown, false);
			}
		};
		
		this.hideDropDown = function(event) 
		{
			drop_down.style.display = 'none';
			if (curr_combo_box)
			{
				if (curr_combo_box.select.selectedIndex != default_selected_index)
				{
					curr_combo_box.select.selectedIndex = default_selected_index;
				}
				curr_combo_box.select.focus();
				curr_combo_box.style.position = 'static';
				curr_combo_box = null;
				$('.box.navi').toggleClass('inactive');
				//Obi.darkMask.darkMaskEvent();					
				
				Event.removeEvent(document, 'click', self.hideDropDown, false);
				Event.removeEvent(window, 'resize', self.hideDropDown, false);
			}
		};
		
		this.moveSelected = function(index)
		{
			if (index != old_selected_index)
			{
				var obj = drop_down.getElementsByTagName('label');
				obj[old_selected_index].className = '';
				obj[index].className = selected_class_name;
				curr_combo_box.select.selectedIndex = old_selected_index = index;
			}
		};
		
		this.moveKeySelected = function()
		{
			if (curr_combo_box)
			{
				default_selected_index = curr_combo_box.select.selectedIndex;
				self.moveSelected(default_selected_index);
				drop_down.scrollTop = getSelectedOffset();
			}
		};
		
		this.setSelectedIndex = function(index)
		{
			default_selected_index = index;
			ComboBox.setSelectedIndex.call(curr_combo_box.select, index);
			curr_combo_box.getElementsByTagName('label')[0].id = 'label_'+index;
		};
		
		this.checkKey = function(event)
		{
			var code = event.keyCode; 
			if (curr_combo_box && (code == 9 || code == 13))
			{
				self.hideDropDown();
			}
		};
		
		this.focusSelect = function()
		{
			curr_combo_box.select.focus();
		};
		
		function positionResizeDropDown()
		{
			var pos = getOffsetElement(curr_combo_box);
			drop_down.style.left = pos[0] + 'px';
			drop_down.style.top = pos[1] + curr_combo_box.offsetHeight + 'px';
			drop_down.style.width = curr_combo_box.clientWidth + 'px';
		}
		
		function getSelectedOffset()
		{
			if (default_selected_index > -1)
			{
				var obj = drop_down.getElementsByTagName('label')[curr_combo_box.select.selectedIndex];
				var scroll = drop_down.scrollTop;
				var obj_top = obj.offsetTop;
				var obj_height = obj.offsetHeight + 2;
				
				if (obj_top < scroll)
				{
					return obj_top;
				}
				
				if (obj_top > scroll + drop_down.offsetHeight - obj_height)
				{
					return obj_top - (drop_down.offsetHeight - obj_height);
				}
				return scroll;
			}
		}
		
		function renderOptions()
		{
			var index = -1;
			var option = null;
			function replaceOption(match)
			{
				index++;
				option = curr_combo_box.select.options[index];
				return '<label id="label_'+index+'" onmouse' + (window.ActiveXObject ? 'over' : 'move') + '=ObserverDropDown.moveSelected(' + index + ') onclick=ObserverDropDown.setSelectedIndex(' + index + ')>' + 
				(option.title ? '<img src="' + option.title + '" alt="" />' : '');
			}
			
			var html_code = curr_combo_box.select.innerHTML;
			html_code = html_code.replace(/<option[^>]*>/ig, replaceOption);
			html_code = html_code.replace(/<\/option/ig, '</label');
			drop_down.innerHTML = html_code;
			if (index > -1)
			{
				drop_down.getElementsByTagName('label')[curr_combo_box.select.selectedIndex].className = selected_class_name;
			}
			
		}
		
	}

	return new ObserverDropDown();
}();

function parseFormElements()
{
	var obj = document.getElementsByTagName('select');
	var felem = null;
	var combo_box = null;
	for (var i = 0, len = obj.length; i < len; i++)
	{
		if (!obj[i].multiple && !(/hidden_component/.test(obj[i].className)))
		{
			combo_box = new ComboBox({'className' : obj[i].className}, obj[i]);
			combo_box.renderComboBox(obj[i].parentNode);
		}
	}
}
Event.addEvent(window, 'load', parseFormElements, false);

function jQueryTabChanger(root_id, active_index, old_index)
{
	document.getElementById(root_id + '_' + old_index).style.display = 'none';
	document.getElementById(root_id + '_' + active_index).style.display = 'block';
	if($.browser.msie) {
		parseFormElements();
	}
}


/*Show Hide fields*/
function showHideFields(thisValue, id) 
{
	$(id).toggle('fast');
	$('span', thisValue).toggle();
	return false;
}

function showHideElement(id_el, show, centering)
{
	if(document.getElementById(id_el)) {
		var obj = document.getElementById(id_el);
		var overlay = $('#darkMask');
		var style = obj.style;
		if (show)
		{
			if (id_el == "mini_basket") {
					style.display = 'block';
					Obi.darkMask.darkMaskEvent(600);
					$('.custom_scroll_container').jScrollPane();
					var basketHTML = $('ul#headnav .end_link span').html();
					$('#basket_button').html('<span>'+basketHTML+'</span>');
			}
			else {
				style.display = 'block';
				Obi.darkMask.darkMaskEvent(600);
			}
			
			if (centering) {
				center(id_el);
			}
			
			
			overlay.click(function ()
			{
				$('.generic_popup').hide();
				$(this).unbind('click').hide();
			});
			
			/* BASKET FUNCTION*/
			if (id_el == "mini_basket") {
				var myTimeout =	$('#mini_basket');
				$('#mini_basket').mouseover( function() {
					clearTimeout(myTimeout);
				});
				$('#mini_basket').mouseleave( function() {
					clearTimeout(myTimeout);
					myTimeout = setTimeout(function() {
						Obi.darkMask.darkMaskEvent();
						$('.generic_popup').hide();
					}, 1000);
				});
			}
			/* END BASKET FUNCTION*/
		}
		else 
		{
			style.display = 'none';
			overlay.unbind('click').hide();
		}
	}
	return false;
}

function Carousel(params)
{
	this.root = params.root;
	this.length = this.root.getElementsByTagName(params.tagName).length;
	this.itemWidth = params.itemWidth;
	this.itemHeight = params.itemHeight;
	this.onChange = params.onChange;
	
	if (params.visibleItems)
	{
		this.visibleItems = params.visibleItems;
	}
	
	this.root.style.width = (this.length * this.itemWidth) + 20 + 'px'; 
	this._initHandlers(params.prevButton, params.nextButton);
}

Carousel.prototype = {
	constructor : Carousel,
	activeIndex : 0,
	visibleItems : 2,
	
	_initHandlers : function(prev, next)
	{
		var self = this;
		if (prev)
		{
			Event.addEvent(prev, 'click', function(e){self.movePrev(); Event.preventDefault(e);}); 
		}
		if (next)
		{
			Event.addEvent(next, 'click', function(e){self.moveNext(); Event.preventDefault(e);});
		}
		prev = next = null;
	},
	
	setActiveIndex : function(index)
	{
		if (this.activeIndex !== index)
		{
			this.activeIndex = index;
			if (this.onChange)
			{
				this.onChange.call(this);
			}
		}
	},
	
	movePrev : function()
	{
		var index = this.activeIndex - this.visibleItems;
		if (index >= 0)
		{
			this.setActiveIndex(index);
		}
		else {
			this.setActiveIndex(0);
		}
	},
	
	moveNext : function()
	{
		if (this.length > this.visibleItems)
		{
			var index = this.activeIndex + this.visibleItems;
			if (this.length - index > this.visibleItems)
			{
				this.setActiveIndex(index);
			}
			else {
				this.setActiveIndex(this.length - this.visibleItems);
			}
		}
	}
};


function carouselChange()
{
	$(this.root).stop(true, true).animate({left : -(this.activeIndex * this.itemWidth)}, 500);
}




var lastCategories = {};
(function($){
	lastCategories.deleteAll = function(params){
		this.$link = $(params.link);
		this.type = (params.type || 'GET');
		this.url = (params.url || this.$link.attr('href'));
		
		this.ctx = this.$link;
		while(!this.ctx.hasClass('box')) {
			this.ctx = this.ctx.parent();
		}
		this.ctx.fadeTo('fast', 0.5);
		$.ajax({
			url: this.url,
			context: this.ctx,
			data: {ajax:true},
			type: this.type,
			success: function(data) {
				$(this).stop().fadeTo('fast', 0, function(){
					$(this).remove();
				});
			},
			error: function() {
				$(this).stop().fadeTo('fast', 1);
			}
		});
	};
})($);


/* ********* FROM HEADER ********* */
// global get ajax content function
function getByAjax(idStr, urlStr) {
	var el = $('#'+idStr);
	el.css({ 'visibility' : 'hidden' });
	el.load(urlStr, function() {
		Cufon.refresh();
		el.css({ 'visibility' : 'visible' });
	});
}

/* ----------------------------------------------------------------------- Product Popup ---------*/
function ProductPopup() {
	var activePopup,
		PopupProduct = $('.products_list a.img_holder.product_popup'),
		hint = $('#product_hint');

	PopupProduct.mouseover(function(event) {
		if (!activePopup) {
			PopupProduct.removeClass('Active-Popup');
			var thePopupLink = $('em.hint', this).attr('title'),
				myPosi = $(this).offset(),
				infoText = $('em.hint', this).text();
			$(this).addClass('Active-Popup');
			hint.html('<a href="'+thePopupLink+'">'+infoText+'<a>')
				.show()
				.css({
				left : myPosi.left - 5 + 'px',
				top  : myPosi.top + 75 + 'px'
			});
		}
	})
	.mouseout(function() {
		HideShowHint(false,false);
	});
	hint.mouseover(function() {
		HideShowHint(false,true);
	})
	.mouseout(function() {
		HideShowHint(false,false);
	});
	function HideShowHint(imageOut, overHint) {
		if (overHint === true) {$('#product_hint').show(); }
		if (imageOut === false && overHint === false) { $('#product_hint').hide();}
	}
	$('#product_hint a').live('click', function(event) {
		if (activePopup === this) {
			return;
		}
		$('#product_hint').hide();
		var thisPopupProduct = $('.products_list a.img_holder.product_popup.Active-Popup');
		
		var parentEl = $(thisPopupProduct).parent();
		parentEl.css({'zIndex' : 550, 'position' : 'relative'});
		$(thisPopupProduct).append('<img class="productLoadImg" src="images/ajax-loader.gif" alt="Loading..." />');
		/*------------ Get Product Popup by Ajax ----------------*/
		var productPopupUrl = $(this).attr('href'); // Produkt Popup inhalt URL (popup-productinfo.php) wird aus dem 'href' tag geholt (kann auch abgeändert werden)
		$.ajax({
			url: productPopupUrl,
			cache: false,
			success: function(data){ 
				$('body').append(data); // bei erfolg in den body laden
			},
			complete: function(){ 
				Cufon.refresh('.price');
				parseFormElements();
				showProductpopup();
				closeProductpopup();
				Obi.darkMask.darkMaskEvent(549);
				$('.productLoadImg').remove();
			}
		});	
		/*------------------------------------------------------*/
		function showProductpopup(){
			var popUp = $('#product_popup');
			var pos = $('.products_list a.img_holder.product_popup.Active-Popup').offset();
			popUp.show().css({
				'left': pos.left - 170 + 'px', 
				'top': pos.top + 120 + 'px'
			});
		}
		function closeProductpopup(){
			$('#darkMask, #product_popup .close_btn').click( function() {
				parentEl.css({'zIndex': 0, 'position': 'static'});
				Obi.darkMask.darkMaskEvent();
				//$(this).unbind('click');
				$('#product_popup').remove();
				activePopup = null;
				return false;
			});
		}
		activePopup = this;
		event.preventDefault();
		return false;
	});
}
/* ----------------------------------------------------------------------- END Product Popup ---------*/

/* --------- Post Data */
var PostForms = "form#filter, form#contentForm"; 
// Post Funktion 
function filterPost() {
	var sort_by = $('#sort_products').val();
	$("form#contentForm input#sort_by").val(sort_by);
	
	$('.content').html('<div class="loadimg"><img src="images/ajax-loader-transparent.gif" alt="Loading..." /></div>'); // Loading Bild
	
	var PostInfo = $(PostForms).serialize();
	
	var productUrl = $('form#contentForm').attr('action'); // Angabe wohin die daten Gepostet werden sollen.
	$.ajax({
			url: productUrl,
			data: PostInfo,
			type: 'POST',
			cache: false,
			success: function(data){ 
				$('.content').html(data); // Daten in den Conten packen.
			},
			complete: function(){ 
				Cufon.refresh(".price"); // Cufon update
				Cufon.refresh(".content h1"); // Cufon update
				Cufon.refresh(".tabs_menu a.cufon"); // Cufon update
				Cufon.refresh(".product_icon .cufon_bold"); // Cufon update
				Cufon.refresh(".next_page .cufon_bold"); // Cufon update
				parseFormElements(); // Combox neu ausführen
				ProductPopup();  // Produkt Popups ausführen
			}
	});	
}
/* --------- ENDE Post Data */

/* ------------------- AJAX POPUP ------------------------*/
function showHideDynamicElementAjax(objLink, id_el, show, newpopup, withscrollbox) {

	var overlay = $('#darkMask'),
		elementbox = $('#'+id_el);
	if (show) {
		if (newpopup) {
			//$('<div id="popup"><img class="loadimg" src="images/ajax-loader.gif" alt="Loading..." /></div>').appendTo(".wrapper");
			$('<div id="popup"><img class="loadimg" src="images/ajax-loader.gif" alt="Loading..." /></div>').appendTo("body");
			Obi.darkMask.darkMaskEvent(600);
		}
		center('popup');
		var PostInfo = $('#popup form').serialize();
		$.ajax({
			url: objLink,
			data: PostInfo,
			type: 'POST',
			cache: false,
			success: function(data){ 
				$("#popup").html(data);
				$('#'+id_el).css('display', 'block');
				center('popup');
				if (withscrollbox) {
					$('.custom_scroll_container_popup').jScrollPane();
				}
			},
			complete: function(){ 
				Cufon.refresh('.cufon');
				Cufon.refresh('.cufon strong');
				Cufon.refresh('.cufon b');
				Cufon.refresh(".price");
				parseFormElements();
			}
		});	
	}
	else {
		$("#popup").remove();
		overlay.hide();
	}
	$('#darkMask').click(function(){ 
		$("#popup").remove(); overlay.hide(); 
	});
}
function showHideElementAjax(id_el, show, newpopup, withscrollbox)
{
	showHideDynamicElementAjax("popup-"+id_el+".html", id_el, show, newpopup, withscrollbox);
}
function showHidePopup(objLink, id_el, show, newpopup, withscrollbox) {

	var overlay = $('#darkMask'),
		elementbox = $('#'+id_el);
	if (show) {
		if (newpopup) {
			//$('<div id="popup"><img class="loadimg" src="images/ajax-loader.gif" alt="Loading..." /></div>').appendTo(".wrapper");
			$('<div id="popup"><img class="loadimg" src="images/ajax-loader.gif" alt="Loading..." /></div>').appendTo("body");
			Obi.darkMask.darkMaskEvent(600);
		}
		$('#popup').addClass(id_el);
		center('popup');
		var PostInfo = $('#popup form').serialize();
		$.ajax({
			url: objLink,
			data: PostInfo,
			type: 'GET',
			cache: false,
			success: function(data){ 
				$("#popup").html(data);
				$('#'+id_el).css('display', 'block');
				center('popup');
				if (withscrollbox) {
					$('.custom_scroll_container_popup').jScrollPane();
				}
			},
			complete: function(){ 
				Cufon.refresh('.cufon');
				Cufon.refresh('.cufon strong');
				Cufon.refresh('.cufon b');
				Cufon.refresh(".price");
				parseFormElements();
			}
		});	
	}
	else {
		$("#popup").remove();
		overlay.hide();
	}
	$('#darkMask').click(function(){ 
		$("#popup").remove(); overlay.hide(); 
	});
}
/* ------ Formular Funktion ------------------*/
function formSubmit(theForm, theURL, productPage) {
	var PostInfo = $(theForm).serialize();
	$(theForm).html('<div class="loadimg"><img src="images/ajax-loader-transparent.gif" alt="Loading..." /></div>'); // Loading Bild
	$.ajax({
			url: theURL,
			data: PostInfo,
			type: 'POST',
			cache: false,
			success: function(data){ 
				$(theForm).html(data); // Daten in den Content packen.
			},
			complete: function(){ 
				if (productPage) {
					var NewPrice = $('#current_price').val();
					$('.pricebox .price, #product_popup .price').html(NewPrice);
					}
				Cufon.refresh(".cufon");
				Cufon.refresh('.cufon strong');
				Cufon.refresh('.cufon b');
				Cufon.refresh(".price");
				Cufon.refresh(".product_icon .cufon_bold");
				parseFormElements();
				ProductPopup();
			}
	});	
}
/* ------ END Formular Funktion --------------*/

/* ------ In den Warenkorb Funktion ------------------*/
function AddCart(theForm, theURL) {
	var PostInfo = $(theForm).serialize();
	$.ajax({
			url: theURL,
			data: PostInfo,
			type: 'POST',
			cache: false,
			success: function(data){
				 showHideElementAjax('addcart', true, true);
			}
	});	
}
/* ------ ENDE In den Warenkorb Funktion ------------------*/

/* ---------- Ajax Carousel ---------- */
var AjaxCarousel = function(options) {
	var base = this;
	
	base.options = $.extend({
		wrap: 'div',
		viewable: 5,
		pagers: '.pager',
		offset: 0,
		items: 0,
		box: 'div',
		url: 'index.html'
	}, options);
	
	base.$wrap = $(base.options.wrap);
	base.$box = base.$wrap.find(base.options.box);
	base.$pageLinks = base.$wrap.find(base.options.pagers);
	
	base.$pageLinks.each(function(){
		var $this = $(this);
		if($this.hasClass('next')) {
			$this.click(function() { 
				base.getNewPage('next');
				return false;
			});
		}
		if($this.hasClass('prev')) {
			$this.click(function(){
				base.getNewPage('prev');
				return false;
			});
		}
	});
	
	base.getNewPage = function(direction) {
		if(direction=='prev') {
			base.options.offset -= base.options.viewable;
			//if(base.options.offset<0) base.options.offset = 0;
		} else {
			base.options.offset += base.options.viewable;
			//if(base.options.offset > base.options.items) base.options.offset -= base.options.viewable;
		}
		base.$box.animate(
			{
				opacity: 0.5
			}, 
			'fast',
			function(){
				base.$box.load(base.options.url.replace('{offset}', base.options.offset), function(){
					base.$box.animate({
						opacity: 1
					}, 'fast');			
				});
			}
		);
	};
	
	return base;
};
/* --- end Ajax Carousel --- */

/* LOGIN LAYER */
var Login = {
	elm: '#login',
	binder: false,
	focusbinder: false,
	init: function() {
		$('ul li a#login-button').hover(
			function () { Login.open(); }, 
			function () { Login.abort(); }
		);
	},
	open: function() {
		$(Login.elm).delay(1000).animate({opacity: 1}, 0, function() {
			Obi.darkMask.darkMaskEvent(600);
			$(Login.elm).css('display', 'block');
			Login.focusbinder = false;
			Login.binder = true;
			Login.close(5000);
			Login.handler();
		});
	},
	abort: function() {
		if(Login.binder === false) {
			$(Login.elm).stop(true, false);
			Login.init();
		}
	},
	close: function(time) {
		$(Login.elm).delay(time).animate({opacity: 1}, 0, function() {
			Obi.darkMask.darkMaskEvent();
			$(Login.elm).css('display', 'none');
			Login.binder = false;
			Login.init();
		});
	},
	handler: function() {
		$(Login.elm).hover(
			function () { $(Login.elm).stop(true, false); $('ul li#loginWrapper').unbind('hover'); },
			function () { if(Login.focusbinder === false) { Login.close(1000); } }
		);
		$(Login.elm + ' input').focus(function() {
			Login.focusbinder = true;
			$(Login.elm).stop(true, false); $('ul li#loginWrapper').unbind('hover');
		});
	},
	password: function(objLink) {
		var oldContent = $(Login.elm);
		$.ajax({
			url: objLink,
			type: 'GET',
			cache: false,
			success: function(data){ 
				$(Login.elm).replaceWith(data);
				$('#passwort_vergessen').css('display', 'block');
				$('#passwort_vergessen').addClass('login');
				$('.close_btn').live('click', function() {
					$('#passwort_vergessen').replaceWith(oldContent);
					oldContent.css('display', 'none');
					Login.init();
				});
				$('#darkMask').click(function() {
					$('#passwort_vergessen').replaceWith(oldContent);
					oldContent.css('display', 'none');
					Login.init();
				});
			},
			complete: function(){ 
				Cufon.refresh('.cufon');
				Cufon.refresh('.cufon strong');
				Cufon.refresh('.cufon b');
				Cufon.refresh(".price");
				parseFormElements();
			}
		});
	}
};
/* END LOGIN LAYER */

/* MERKZETTEL LAYER */
var Merkzettel = {
	elm: '#notepad',
	cnt: '#notepadContent',
	binder: false,
	actionBinder: false,
	init: function() {
		$('ul li a#wishlist-button').hover(
			function () { Merkzettel.open(); }, 
			function () { Merkzettel.abort(); }
		);
	},
	open: function() {
		$(Merkzettel.elm).delay(1000).animate({opacity: 1}, 0, function() {
			Obi.darkMask.darkMaskEvent(600);
			$(Merkzettel.elm).css('display', 'block');
			$('.custom_scroll_container_popup').jScrollPane();
			Merkzettel.actionBinder = false;
			Merkzettel.binder = true;
			Merkzettel.close(5000);
			Merkzettel.handler();
		});
	},
	abort: function() {
		if(Merkzettel.binder === false) {
			$(Merkzettel.elm).stop(true, false);
			Merkzettel.init();
		}
	},
	close: function(time) {
		$(Merkzettel.elm).delay(time).animate({opacity: 1}, 0, function() {
			Obi.darkMask.darkMaskEvent();
			$(Merkzettel.elm).css('display', 'none');
			Merkzettel.binder = false;
			Merkzettel.init();
		});
	},
	handler: function() {
		$(Merkzettel.elm).hover(
			function () { $(Merkzettel.elm).stop(true, false); $('ul li a#wishlist-button').unbind('hover'); },
			function () { if(Merkzettel.actionBinder === false) { Merkzettel.close(1000); } }
		);
	},
	loadContent: function(mUrl) {
		$.ajax({
			url: mUrl,
			type: 'GET', 
			cache: false,
			success: function(data) {
				$(Merkzettel.elm).replaceWith(data);
				$('.close_btn').live('click', function() {
						$(Merkzettel.elm).css('display', 'none');
						Merkzettel.init();
				});
				$('.f_left_abort').live('click', function() {
						$(Merkzettel.elm).css('display', 'none');
						Merkzettel.init();
				});
				$('#darkMask').click(function() {
					$(Merkzettel.elm).css('display', 'none');
					Merkzettel.init();
				});
			},
			complete: function() {
				Cufon.refresh('.cufon');
				Cufon.refresh('.cufon strong');
				Cufon.refresh('.cufon b');
				Cufon.refresh(".price");
				parseFormElements();
			}
		});
	},
	deleteContent: function(mUrl) {
		Merkzettel.actionBinder = true;
		$.ajax({
			url: mUrl,
			type: 'GET',
			cache: false,
			success: function(data) {
				$(Merkzettel.cnt).html(data);
			},
			complete: function() {
				Cufon.refresh('.cufon');
				Cufon.refresh('.cufon strong');
				Cufon.refresh('.cufon b');
				Cufon.refresh('.price');
				parseFormElements();
			}
		});
	}
};
/* END MERKZETTEL LAYER */
/* LISTVIEW */
var ListShop = {
	listitem: '.product_item',
	link: '.product_popup',
	init: function(elm) {
		var _this = this;
		$(elm + ' ' + this.listitem + ' ' + this.link).live('click', function(event) {
			_this.activeElement = $(this);
			_this.parentElement = _this.activeElement.parents(_this.listitem);
			_this.parentElement.css({'zIndex' : 550, 'position' : 'relative'});
			_this.loadData(_this.activeElement.attr('rel'));
			event.preventDefault();
			return false;
		});
	},
	loadData: function(popupurl) {
		var _this = this;
		$.ajax({
			url: popupurl,
			cache: false,
			success: function(data){ 
				$('body').append(data);
			},
			complete: function(){ 
				Cufon.refresh('.price');
				parseFormElements();
				_this.showProductPopup();
				_this.closeProductPopup();
				Obi.darkMask.darkMaskEvent(549);
				$('.productLoadImg').remove();
			}
		});	
	},
	showProductPopup: function() {
		var _this = this;
		var popUp = $('#product_popup');
		var pos = _this.parentElement.offset();
		popUp.show().css({
			'left': pos.left + 116 + 'px', 
			'top': pos.top + 171 + 'px'
		});
	},
	closeProductPopup: function() {
		var _this = this;
		$('#darkMask, #product_popup .close_btn').click( function() {
			_this.parentElement.css({'zIndex': 0, 'position': 'static'});
			Obi.darkMask.darkMaskEvent();
			$('#product_popup').remove();
			return false;
		});
	}
};
/* END LISTVIEW */
/* QUICKSHOP CART */

var QuickshopCart = {
	beenSubmitted : false,
	init: function(form, url) {
		var _this = this;
		$('#'+form).submit(function() {
			if (QuickshopCart.beenSubmitted === true){
				return false;
			} else {
				QuickshopCart.beenSubmitted = true;
			};
			_this.submitForm(this, url);
			return false;
		});
	},
	submitForm: function(form, cartUrl) {
		$('<div id="popup"><img class="loadimg" src="images/ajax-loader.gif" alt="Loading..." /></div>').appendTo("body");
		center('popup');
		var PostInfo = $(form).serialize();
		if($('li.product_item').length) {
			//$('.product_box li.product_item').css({'position': 'static'});
			$('li.product_item').removeAttr('style');
			$('#product_popup').remove();
			Obi.darkMask.darkMaskEvent();
		}
		$.ajax({
			url: cartUrl,
			data: PostInfo,
			type: 'POST',
			cache: false,
			success: function(data) {
				Obi.darkMask.darkMaskEvent(600);
				$("#popup").html(data);
				$('#addcart').css('display', 'block');
				center('popup');
				ProductPopup();
			},
			complete: function() {
				Cufon.refresh('.cufon');
				Cufon.refresh('.cufon strong');
				Cufon.refresh('.cufon b');
				Cufon.refresh(".price");
				QuickshopCart.beenSubmitted = false;
				parseFormElements();
			}
		});
	},
	updateCartHeader: function(price, quantity) {
		var _this = this;
		$('#cartHeader').replaceWith('<span id="cartHeader">'+quantity+' Artikel<br/>€ '+price+'</span>');
		return false;
	}
};
/* END QUICKSHOP CART */

/* CARTLAYER */

var CartLayer = {
	openButton: '#cartButton',
	closeButton: '.close_btn',
	cartLayer: '#mini_basket',
	cartLayerCnt: '#mini_basket_cnt',
	init: function () {
		var _this = this;
		var timer;
		$(_this.openButton).hover(function() {
			var obj = this;
			if(typeof(timer) != 'undefined') {
				clearTimeout(timer);
			}
			timer = setTimeout(function() {
				_this.open(obj);
			}, 1000);
		}, function() {
			clearTimeout(timer);
		});
		$(_this.cartLayer + ' ' + _this.closeButton).live('click', function() {
			_this.close(this);
			return false;
		});
	},
	open: function(obj) {
		var _this = this;
		$(_this.cartLayerCnt).html('<img class="loadimg" src="images/ajax-loader.gif" alt="Loading..." style="padding: 20px; display: block; width: 32px; margin: 0 auto;" />');
		Obi.darkMask.darkMaskEvent(600);
		$(_this.cartLayer).show();
		var basketHTML = $('ul#headnav .end_link span').html();
		$('#basket_button').html('<span>'+basketHTML+'</span>').click(function(){
			document.location.href = $(obj).attr('href');
		});
		var noCache = "?_="+ (new Date()).getTime();
		$(_this.cartLayerCnt).load($(obj).attr('rel')+noCache, function() {
			Cufon.refresh('.cufon');
			Cufon.refresh('.cufon strong');
			Cufon.refresh('.cufon b');
			Cufon.refresh(".price");
			parseFormElements();
			$('.custom_scroll_container').jScrollPane();
			_this.timer(obj);
		});
		
	},
	timer: function(obj) {
		var _this = this;
		
		var myTimeout =	$('#mini_basket');
		$(_this.cartLayer).mouseover( function() {
			clearTimeout(myTimeout);
		});
		$(_this.cartLayer).mouseleave( function() {
			clearTimeout(myTimeout);
			myTimeout = setTimeout(function() {
				_this.close(obj);
			}, 1000);
		});
	},
	close: function(obj) {
		Obi.darkMask.darkMaskEvent();
		$('.generic_popup').hide();
	}
};

/* ENDE CARTLAYER */

/* LASTVIEWED */

var LastViewed = {
	buttons: '.deleteLastViewed',
	init: function() {
		var _this = this;
		//console.log(_this.buttons);
	}
};

/* --------- Filter Auswahl alle */
(function($){ 
    $.fn.extend({  
        chooseAll: function(options) {
			$(this).each(function() {
				/* default settings */
				settings = jQuery.extend({
					elm: 'input[rel!=all]',
					alle: 'input[rel=all]'
				}, options);
				/* set settings to function global */
				
				var id = '#'+$(this).attr('id');
				
				this.elm = settings.elm;
				this.alle = settings.alle;
				
				var _this = $(this);
				
				$(id+' '+this.alle).change(function() { _this.setAll(id); });
				$(id+' '+this.elm).change(function() { _this.setElm(id); });
				
			});
		},
		setAll: function(id) {
			$(this).each(function() {
				if($(id+' '+this.alle).attr('checked') === false) {
					$(id+' '+this.alle).attr('checked', true);
				}
				$(id+' '+this.elm).attr('checked', false);
			});
		},
		setElm: function(id) {
			$(this).each(function() {
				_this = $(this);
				_this.flag = false;
				$(id+' input').each(function() {
					if($(this).attr('checked') === true) {
						_this.flag = true;
					}
				});
				if(_this.flag === true) {
					$(id+' '+this.alle).attr('checked', false);
				} else {
					$(id+' '+this.alle).attr('checked', true);
				}
			});
		}
	});
})(jQuery);
/* --------- ENDE Filter Auswahl alle */

/* START Produkttabs auf Homepage */

var ProductTabs = {
	arrows: '.arrow',
	tabs: '.product_home_tabs li a',
	inpSortBy: '#sort_by',
	inpPage: '#page',
	init: function(id) {
		var _this = this;
		this.id = id;
		_this.handler();
	},
	handler: function() {
		var _this = this;
		// init tabs
		$(_this.tabs).live('click', function() {
			$(_this.id + ' ' + _this.inpSortBy).val($(this).attr('rel'));
			_this.submitData();
			return false;
		});
		// init arrows
		$(_this.id + ' ' + _this.arrows).live('click', function() {	
			$(_this.id + ' ' + _this.inpPage).val($(this).attr('href'));
			_this.submitData();
			return false;
		});
	},
	submitData: function() {
		var _this = this;
		formSubmit(_this.id, $(_this.id).attr('action'));
	}
};

/* ENDE Produkttabs auf Homepage */

/* ADDRESS TOGGLE */

var AddressToggle = {
	toggleGroup: '.addressToggle',
	inputElm: '.toggleAdr',
	extAddress: '.adr',
	box: '.box_max',
	init: function() {
		var _this = this;
		$(_this.toggleGroup + ' ' + _this.extAddress).hide();
		var radioID = $(_this.toggleGroup + ' ' + _this.inputElm + ':checked').attr('id');
		$(_this.toggleGroup + ' label[for='+radioID+'] ' + _this.extAddress).show();
		
		_this.setHeight();
		$(_this.toggleGroup + ' ' + _this.inputElm).live('change', function() {
			$(_this.toggleGroup + ' ' + _this.extAddress).hide();
			$(this).next('label').children(_this.extAdress).show();
			_this.setHeight();
		});
	},
	setHeight: function() {
		var _this = this;
		var maxHeight = 0;
		$(_this.toggleGroup).each(function() {
			if($(this).height() > maxHeight) {
				maxHeight = $(this).height();
			}
		});
		$(_this.box).css('height', maxHeight+'px');
	}
};

/* END ADDRESS TOGGLE */

/*---------- Kaufberater */

function Kaufberater(id)
{
	var KbForm = $('#'+id+' form');
	var KbContainer = $('#'+id);
	this._init(id, KbForm, KbContainer);
}

Kaufberater.prototype = {
	
	constructor : Kaufberater,
	prevSelector : '.previous_step',
	resultSelector: '.showResults',
	
	
	_init: function(id, KbForm, KbContainer) {
		this.id = id;
		this.KbForm = KbForm;
		this.KbContainer = KbContainer;
		this.ResultButton = $(this.resultSelector);
		var self = this;
		KbForm.submit(function() {
			var KbUrl = $(this).attr('action');
			var KbData = $(this).serializeArray();
			KbContainer.css({visibility: 'hidden'});
			self.formSubmit(KbUrl, KbData);
			return false;
		});
		self.ResultButton.click(function() {
			var formular = $(this).parents("form");
			self.showResults($(this).attr('href'), formular.serializeArray());
			return false;
		});
	},
	formSubmit: function(KbUrl, KbData) {
		var self = this;
		$.ajax({
			url: KbUrl, 
			data: KbData, 
			type: 'POST',
			success: function(response) {
				self.KbContainer.html(response);
				for(i=0; i<=KbData.length -1; i++) {
					$('#'+self.id+' form').append('<input type="hidden" class="kbCache" name="'+KbData[i]['name']+'" id="'+KbData[i]['name']+'" value="'+KbData[i]['value']+'" />');
				}
				Cufon.refresh();
				self.KbContainer.css({ 'visibility' : 'visible' });
				$(self.prevSelector).click(function() {
					self.KbContainer.css({visibility: 'hidden'});
					//self.previousPage($(this).attr('href'));
					var formular = $(this).parents("form");
					self.formSubmit($(this).attr('href'), formular.serializeArray());		
					return false;
				});
			}
		});
	},
	showResults: function(url, resultData) {
		var self = this;
		$('.content').html('<div class="loadimg"><img src="images/ajax-loader-transparent.gif" alt="Loading..." /></div>'); // Loading Bild
		$.ajax({
			url: url, 
			type: 'POST',
			data: resultData, 
			success: function(response) {
				$('.content').html(response);
			},
			complete: function(){ 
				Cufon.refresh(".price");
				Cufon.refresh(".content h1");
				Cufon.refresh(".tabs_menu a.cufon");
				Cufon.refresh(".product_icon .cufon_bold");
				Cufon.refresh(".next_page .cufon_bold");
				parseFormElements();
				ProductPopup();
			}
		});
	},
	previousPage: function(url) {
		var self = this;
		$.ajax({
			url: url, 
			success: function(response) {
				self.KbContainer.html(response);
				Cufon.refresh();
				self.KbContainer.css({ 'visibility' : 'visible' });
			}
		});
	}
};

/*---------- /Kaufberater */

/*---------- / ADS Rechner - Laminat  */
function neue_menge() {
	var neuemenge = $('#output span').text();
	$("select[name='menge']").val(neuemenge);
}
/*---------- ENDE / ADS Rechner  */

function formatNumber(zahl) {
	if(!/^\d+(\.+)?([\d]{0,2})?$/.test(zahl)) {
		return zahl;
	}
	zahl = String(zahl);
	var fullInt = zahl;
	var strlen = zahl.length;
	
	//console.log(fullInt+': '+strlen);
	if(String(fullInt).indexOf('.') > 0) { 
		fullInt = parseInt(String(fullInt).split('.')[0]); 
		strlen = parseInt(String(fullInt).split('.')[0].length);
	}
	
	//console.log(fullInt+': '+strlen);
	if(strlen>3) {
		var intArray = [];
		while(fullInt.length>3) {
			//console.log(fullInt, fullInt.substr((fullInt.length-3), 3), fullInt.substring(0, (fullInt.length-3)));
			intArray.push(fullInt.substr((fullInt.length-3), 3));
			fullInt = fullInt.substring(0, (fullInt.length-3));
		}
		intArray.push(fullInt);
		intArray.reverse();
		fullInt = intArray.join('.');
		//console.log(fullInt);
	}
	if(String(zahl).split('.').length > 1) {
		strlen = String(zahl).split('.')[1].length;
		if(strlen == 1) {
			return fullInt + ',' + String(zahl).split('.')[1];
		} else if(strlen==2) {
			return fullInt + ',' + String(zahl).split('.')[1];
		}
	} else {
		return fullInt;
	}
}

var RevHeader = {
	changeLoginHeader: function(url, securityUrl, username) {
		var _this = this;
		$('#weMeLoginPart').replaceWith('<li id="welcomeMessageWrapper"><span class="welcomeMessage">Hallo '+username+'.</span><a id="my_obi_link" href="'+url+'">Mein OBI.de</a> |</li><li><a id="logout-button" href="'+securityUrl+'">Ausloggen</a> |</li>');
		return false;
	}
};

/* ********************** Document Ready Function ******************** */
$(function(){

/*---------- Slider - Einstellungen für die Silder. */
	if($("#price_slider").length) {
		var price_min = parseInt($("#price_min").val()), // Min Start Preis
			price_max = parseInt($("#price_max").val()), // Max Start Preis
			price_start = parseInt($("#price_start").val()), // Aktuell ausgewaehlter Preis Min
			price_end = parseInt($("#price_end").val()); // Aktuell ausgewaehlter Preis Max
		$("#handle_1").text(formatNumber(price_start)); 
		$("#handle_2").text(formatNumber(price_end));
		$("#price_slider").slider({
				animate: true,
				max: price_max,
				min: price_min,
				range: true,
				step: 1,
				values : [price_start, price_end],
				slide: function(event, ui) {
					//console.log(ui.values[0], ui.values[1]);
					$("#price_start").val(ui.values[0]);
					$("#price_end").val(ui.values[1]);
					$("#handle_1").text(formatNumber(ui.values[0]));
					$("#handle_2").text(formatNumber(ui.values[1]));
				},
				//change: function(event, ui) { filterPost(); }
				stop: function(event, ui) { filterPost(); }
		});
	}
	
	if($("#stars_slider").length) {
		var stars1 = $('#handle_3 span'),
			stars2 = $('#handle_4 span'),
			stars_start = parseInt($("#stars_start").val()),
			stars_end = parseInt($("#stars_end").val());
			stars1.addClass('star-'+stars_start);
			stars2.addClass('star-'+stars_end);
		$("#stars_slider").slider({
			animate: true,
			distance: 0,
			min: 0,
			max: 5,
			range: true,
			step: 1,
			values: [stars_start, stars_end],
			slide: function(event, ui) {
				$("#stars_start").val(ui.values[0]);
				$("#stars_end").val(ui.values[1]);
				setstar(ui.values[0], ui.values[1]);
			},
			change: function(event, ui) {
				$("#stars_start").val(ui.values[0]);
				$("#stars_end").val(ui.values[1]);
				setstar(ui.values[0], ui.values[1]);
			},
			stop: function(event, ui) { filterPost(); }
		});
		function setstar(min_star, max_star) {
			min_star = parseInt(min_star);
			max_star = parseInt(max_star);
			stars1.removeClass();
			stars1.addClass('star-'+min_star);
			stars2.removeClass();
			stars2.addClass('star-'+max_star);
		}
		if($('.stars_holder .stars-handle a').length) {
			$('.stars_holder .stars-handle a').live('click', function() {
				var relValue = $(this).attr('rel').split('|');
				var handleVal = parseInt(relValue[0]);
				var stepVal = parseInt(relValue[1]);
				var leftVal = $("#stars_start").val();
				var rightVal = $("#stars_end").val();
				if((handleVal == 0 && stepVal <= rightVal) || (handleVal == 1 && stepVal >= leftVal)) {
					$("#stars_slider").slider("values", handleVal, stepVal);
				}
				return false;
			});
		}
	}
	
	if($("#power_slider").length) {
		var watt_min = parseInt($("#watt_min").val());
			watt_max = parseInt($("#watt_max").val());
			watt_start = parseInt($("#watt_start").val());
			watt_end = parseInt($("#watt_end").val());
			
		$("#handle_5").text(watt_start);
		$("#handle_6").text(watt_end);
		$("#power_slider").slider({
				animate: true,
				max: watt_max,
				min: watt_min,
				range: true,
				step: 1,
				values : [watt_start, watt_end],
				slide: function(event, ui) {
					$("#watt_start").val(ui.values[0]);
					$("#watt_end").val(ui.values[1]);
					$("#handle_5").text(ui.values[0]);
					$("#handle_6").text(ui.values[1]);
				},
				//change: function(event, ui) { filterPost(); }
				stop: function(event, ui) { filterPost(); }

		});
	}
/*---------- ENDE Slider - Einstellungen für die Silder. */

/* --------- Darstellung Ergebnisse */
// Gesamten Merkzettel löschen
$('#merkzettel_dell').live('click', function() {
		$("form#contentForm input#dell_merkzettel").val("dell");
		filterPost();
});
// Listen- / Bildansicht
$('.image_view').live('click', function() {
		$("form#contentForm input#darstellung_ergebnis").val("grid");
		filterPost();
});
$('.listview').live('click', function() {
		$("form#contentForm input#darstellung_ergebnis").val("list");
		filterPost();
});
// Artikel pro Seite
$('.pager_list a').live('click', function() {
		var item_on_page = $(this).text();
		$("form#contentForm input#item_on_page").val(item_on_page);
		filterPost();
});
// Paging
$('.paging.ajax a').live('click', function() {
		var clicked_page =  $(this).attr('href');
		$("form#contentForm input#current_page").val(clicked_page);
		filterPost();
		return false;
});
$('.paging a').live('click', function() {
	var clicked_page =  $(this).text();
	if (clicked_page == "Zurück") {
		clicked_page = parseInt($("form#contentForm input#current_page").val()) - 1;
	}
	if (clicked_page == "Nächster") {
		clicked_page = parseInt($("form#contentForm input#current_page").val()) + 1;
	}
	$("form#contentForm input#current_page").val(clicked_page);
	filterPost();
});
// Next Page
$('.next_page a').live('click', function() {
		var clicked_page = parseInt($("form#contentForm input#current_page").val()) + 1;
		$("form#contentForm input#current_page").val(clicked_page);
		filterPost();
});
$('.next_page_long a').live('click', function() {
	var clicked_page = parseInt($("form#contentForm input#current_page").val()) + 1;
	$("form#contentForm input#current_page").val(clicked_page);
	filterPost();
});
// Sortierer
$('.sort_products_drop_down label').live('click', function() {
		filterPost();
});
// Sortierer 'Bestellungen der letzten'
$('.bestellungen_der_letzten_drop_down label').live('click', function() {
		var sort_by = $(this).text();
		$("form#contentForm input#bestellungen_der_letzten").val(sort_by);
		filterPost();
});
// Formular Reset
$('#resetForm').live('click', function() {
	/* Price Slider  Reset */
	var price_min = parseInt($("#price_min").val()), // Min Start Price
		price_max = parseInt($("#price_max").val()); // Max Start Price
	$("#handle_1").text(price_min);
	$("#handle_2").text(price_max);
	$("#price_start").val(price_min);
	$("#price_end").val(price_max);
	$("#price_slider").slider({	values : [price_min, price_max] });
	/* Stars Slider Reset */
	if($("#stars_slider").length) {
		$("#stars_start").val(0);
		$("#stars_end").val(5);
		setstar(0, 5);
		$("#stars_slider").slider({	values : [0, 5] });
	}
	/* Power Slider Reset */
	if($("#power_slider").length) {
		var watt_min = parseInt($("#watt_min").val());
		var	watt_max = parseInt($("#watt_max").val());
		$("#watt_start").val(watt_min);
		$("#watt_end").val(watt_max);
		$("#handle_5").text(watt_min);
		$("#handle_6").text(watt_max);
		$("#power_slider").slider({	values : [watt_min, watt_max] });
	}
	/* Reset dynamic generated sliders */
	if(null != numericFilterCodes && numericFilterCodes.length > 0){
		for(var i=0; i<numericFilterCodes.length; i++){
			var filterCode = numericFilterCodes[i];
			var sliderId = filterCode + "_slider";
			if($("#" + sliderId).length) {
				var sliderMin = parseInt($("#" + filterCode + "MinValue").val());
				var	sliderMax = parseInt($("#" + filterCode + "MaxValue").val());
				$("#" + filterCode + "StartValue").val(sliderMin);
				$("#" + filterCode + "EndValue").val(sliderMax);
				$("#" + filterCode + "_1").text(sliderMin);
				$("#" + filterCode + "_2").text(sliderMax);
				$("#" + sliderId).slider({values : [sliderMin, sliderMax]});
			}
		}
	}
	
	/* Post */
	filterPost();
});
// Postbefehl ausführen beim ändern von input val
$(PostForms).change(function () { filterPost(); }); 
/* --------- ENDE Darstellung Ergebnisse */

/* --------- Tabsmenu Hauptwaren */
	if($('#tabs_menu_haupwaren').length) {
		new TabsMenu({
			'tabs_root_id' : 'tabs_menu_haupwaren',
			'tabs_tag_name' : 'a',
			'active_tab_index' : 0,
			'change_event' : 'click',
			'onChange' : jQueryTabChanger
		});
	}
/* --------- ENDE Tabsmenu Hauptwaren */

/* --------- Main Actions */
	$('.main_actions input.edit_field').keyup( function() {
		var pos = getOffsetElement(this);
		$('#searchbar').css({'left': pos[0] - 1 + 'px', 'top': pos[1] + 45 + 'px'});
	});

	$('.main_actions input.edit_field').keyup( function() {
		if(this.value.length > 0) {
			this.value = 'Kam';
			$(this).parent().css('zIndex', 551);
			$('#searchbar').show();
			Obi.darkMask.darkMaskEvent(550);
		}
		else {
			$(this).parent().css('zIndex', 1);
			$('#searchbar').hide();
			Obi.darkMask.darkMaskEvent();
		}
	});
/* ---------  ENDE Main Actions */

/*------------ Accordion Form */
	if($("#accordion_form").length) {
		$("#accordion_form").accordion({autoHeight: false, collapsible: false, active: false});
		$('#accordion_form').bind('accordionchangestart', function(event, ui) {
			ui.newHeader.parent().addClass('accordion-parent-active');
			ui.oldHeader.parent().removeClass('accordion-parent-active');
			ui.newHeader.children('input[type=radio]').attr('checked', true);
		});
	}
/*------------ ENDE Accordion Form */

/*------------ TabsMenu */
	$('.teaser_nav').each(function () {
			new TabsMenu({
				'tabs_root_id' : this.id,
				'tabs_tag_name' : 'li',
				'active_class' : 'active_teaser_tab',
				'active_tab_index' : 0,
				'change_event' : 'mouseover',
				'onChange' : jQueryTabChanger
			});	
	});
/*------------ END TabsMenu */

/*------------ Marks Carousel */
if ($('#marks_carousel_item').length){
	$('#marks_carousel_item').jcarousel({
		wrap: 'circular',
		buttonNextHTML: '<a id="marks_carousel_next" class="arrow r_arrow" href="javascript:;"></a>',
		buttonPrevHTML: '<a id="marks_carousel_prev" class="arrow" href="javascript:;"></a>'
	});
}	 
/*------------ ENDE Marks Carouse */
	
/*------------ Footer "OBI im Überblick" Function */
	var zindex = 100;

	$('#footer .ueberblick .inner > ul > li > a:not(.noarrow)').hover(function() {
		var list = $(this).siblings();
		$(this).parent().css('z-index', zindex++);
		$("#footer .ueberblick ul div").hide();
		list.show();
		var timer = $("#footer .ueberblick ul div");
		$(list).mouseleave(function(){
			clearTimeout(timer);
			timer = setTimeout(function() {list.hide();}, 100);
		});
		$(this).mouseleave(function(){
			clearTimeout(timer);
			timer = setTimeout(function() {list.hide();}, 100);
		});
		$(list).mouseover(function(){
			clearTimeout(timer);
		});
		$(this).mouseover(function(){
			clearTimeout(timer);
		});
		return false;
	});
/*------------ ENDE Footer "OBI im Überblick" Function */
	
/*------------ Tab Menu Funktion */
	$('.tabs_menu li a').click(function () {
		$('.tabs_menu li a').removeClass("active_tab");
		$(this).addClass("active_tab");
		Cufon.refresh();
	});
/*------------ ENDE Tab Menu Funktion */

/*------------------ Mein OBI Markt Funktion */
	$('.box.markt_teaser .boxContent').css("display", "none");
	$('.box.markt_teaser .footer').css("display", "none");
	
	$('.box.markt_teaser h3 a').toggle(
		function() {
			$('.box.markt_teaser .boxContent').show(300);
			$('.box.markt_teaser .footer').show(300);
			$(this).addClass("active");
		},
		function () {
			$('.box.markt_teaser .boxContent').hide(300);
			$('.box.markt_teaser .footer').hide(300);
			$(this).removeClass("active");
		}
	);
/*------------------ ENDE Mein OBI Markt Funktion */

/*------------------ box fold functions */
	$('a.fold').click(function(){
		$(this).parent('.box').toggleClass('closed');
		return false;
	});
/*------------------ ENDE box fold functions */

/*------------------ rating-list scripts */
	var $active = null;
	var $list = $('ul.star-rating');
	var $input = $('#'+$list.attr('rel'));
	//console.log($list, $input);
	if($list.length && $input.length) {
		$(window).load(function(){
			if($input.attr('value').length) {
				$active = $list.find('li:nth-child('+$input.attr('value')+')');
				$active.addClass('active');
			}
			$list.find('a').click(function(event) {
				event.preventDefault();
				$input.attr('value', $(this).html());
				$('ul.star-rating li').removeClass('active');
				$active = $(this).parent();
			});
			$list.hover(function(){
				if($active) { $active.removeClass('active'); }
			},function(){
				if($active) { $active.addClass('active'); }
			});
		});
	}
/*------------------ ENDE rating-list scripts */
	
/*------- SET Height for the "Product" Boxes */
	if($('.products_list .product_item .product_foot a')) {
		var maxH = 14,
		box_foot = $('.product_foot a');
		box_foot.each(function(indexO) {
			if($(this).height() >= maxH) { maxH = $(this).height(); }
		});
		if (maxH > 14) {
			box_foot.css("height", maxH+"px");
		}
	}
/*------- ENDE SET Height for the "Product" Boxes */

/*------ Newsletter "Add Recipient" Funktion */
	$(".tellafriend-add").click(function(){
		var all_boxes = $(".tellafriend_receiver").size();		
		$('<div class="tellafriend_receiver"><fieldset><div class="form_group"><label for="newsletter_tellafriend_form_name_'+all_boxes+'">Name*</label><input type="text" name="newsletter_tellafriend_form_name[]" id="newsletter_tellafriend_form_name_'+all_boxes+'" /></div><div class="form_group"><label for="newsletter_tellafriend_form_email_'+all_boxes+'">E-Mail-Adresse*</label><input type="text" name="newsletter_tellafriend_form_email[]" id="newsletter_tellafriend_form_email_'+all_boxes+'" /></div></fieldset><div class="hr"><hr /></div></div>').appendTo(".tellafriend_receiver_wrapper");
	});
/*------ ENDE Newsletter "Add Recipient" Funktion */

/* ------ Bewertungs Toggle Funktion ------------------*/
	$(".bt_toggle_bewertung_text").live('click', function() {
		$(".bt_toggle_bewertung_text, .open_bewertung").text('Ganze Bewertung lesen');
		$(".open_bewertung").addClass('bt_toggle_bewertung_text').removeClass('open_bewertung');
		$(".toggle_bewertung_text").removeClass('active');
		$(this).addClass('klicked');
		$(".column_2:has(.klicked)").find(".toggle_bewertung_text").addClass('active');
		$(this).text('Ganze Bewertung schließen');
		$(this).removeClass().addClass('open_bewertung');
	});
									
	$(".open_bewertung").live('click', function() {
		$(this).text('Ganze Bewertung lesen');
		$(".toggle_bewertung_text").removeClass('active');
		$(this).removeClass().addClass('bt_toggle_bewertung_text');
	});
/* ------ENDE Bewertungs Toggle Funktion ------------------*/

/* ------ Abweichende Lieferanschrift Toggle Funktion -----*/
if($('.addressToggle').length){
	AddressToggle.init();
}
/* ------ ENDE Abweichende Lieferanschrift Toggle Funktion ----*/

/* ------ Start Product POPup Funktion ---- */
ProductPopup();
/* ------ ENDE Start Product POPup Funktion ---- */

/* ------ADS Tooltip ---- */
if($('.qmeterShow')) {
	$('.qmeterShow div.comboBox').live('mouseenter' , function(){
		$('.qmeterShow #tooltip').prependTo(this).show('blind', 100);
	}).live('mouseleave', function(){
		$('#tooltip', this).css('display','none');
	});
}
/* ------ENDE / ADS Tooltip ---- */

/* ------ADS Laminat Rechner ---- */
$('#flaeche_berechnen').live('click', function() {
	var qm2in = $('#qmeter').val(),
		qm2 = $('#quadratmeter').val(),
		qm2 = qm2.replace(/[,]/,'.'), // ersetze Komma mit Punkt
		qm2 = parseFloat(qm2),  // konvertiere zu Float
		pakete = Math.ceil(qm2 / qm2in);
	$('#output span').text(pakete);
});
/* ------ENDE / ADS Laminat Rechner ---- */

/* ------ADS Tapeten Rechner ---- */
$('#tapete_berechnen').live('click', function() {
	var Tb = $('#Tb').val(),
		Th = $('#Th').val();
		
	var	ansatz = $('#ansatz').val();
		
	var	Wb =  $('#Wb').val(),
		Wb = Wb.replace(/[,]/,'.'), // ersetze Komma mit Punkt
		Wb = parseFloat(Wb);
		
	var	Wh = $('#Wh').val(),
		Wh = Wh.replace(/[,]/,'.'), // ersetze Komma mit Punkt
		Wh = parseFloat(Wh);
	if (ansatz !== 0) {
		var Wh = Math.ceil(Wh / ansatz)*ansatz;
	}
		
	var anzahl_bahnen = Math.ceil(Wb / Tb),
		bahnen_pro_rolle = Math.floor(Th / Wh),
		rollen = Math.ceil(anzahl_bahnen / bahnen_pro_rolle);
		
	$('#output span').text(rollen);	
});
/* ------ENDE / ADS Laminat Rechner ---- */

$('#saveThisStore1').live("click", function() {
	var link = $(this);
	$.ajax({
		url: link.attr('href'),
		type: 'GET',
		cache: false,
		success: function(data) {
			link.text('Bestätigt');
			$('#saveThisStore2').text('Bestätigt');
		},
		complete: function(){
		}
	});
	return false;
});
$('#saveThisStore2').live("click", function() {
	var link = $(this);
	$.ajax({
		url: link.attr('href'),
		type: 'GET',
		cache: false,
		success: function(data) {
			link.text('Bestätigt');
			$('#saveThisStore1').text('Bestätigt');
		},
		complete: function(){
		}
	});
	return false;
});

/* INITIALIZE THE METANAV LAYERS BOX */
Login.init();
Merkzettel.init();
CartLayer.init();
/* END METANAV LAYERS BOX */


/* Form helper */
	$('textarea[maxlength]').live("keyup", function(){
		var max = parseInt($(this).attr('maxlength'));
		if($(this).val().length > max){
			$(this).val($(this).val().substr(0, max));
		}
	});
	
	
	$('.numbersOnly').keyup(function () { 
	    this.value = this.value.replace(/[^0-9\.]/g,'');
	});


/*  /Form helper */
});

/* ********************** ENDE Document Ready Function ******************** */
