function RepositionLayer(element)
{
}

function getElementPosition(element)
{
	var position = new Object();
	var tmpElement = element;
	position.x = 0;
	position.y = 0;
	
	if (tmpElement.offsetParent)
	{
		while (tmpElement.offsetParent)
		{
			position.x += tmpElement.offsetLeft
			tmpElement = tmpElement.offsetParent;
		}
	}
	else if (tmpElement.x)
	{
		position.x += tmpElement.x;
	}

	// reset
	tmpElement = element;
	if (tmpElement.offsetParent)
	{
		while (tmpElement.offsetParent)
		{
			position.y += tmpElement.offsetTop
			tmpElement = tmpElement.offsetParent;
		}
	}
	else if (tmpElement.y)
	{
		position.y += tmpElement.y;
	}
	
	return position;
}	

function suchestartneu(x) {
	if ((document.getElementById("searchff_form").query.value != 'Artikelnr./ Begriff') && (document.getElementById("searchff_form").query.value != '')) {
		var sstr = document.getElementById("searchff_form").query.value;
		var egb1 = sstr.slice(3,4);
		if(egb1=='.') {
			var egb2 = sstr.slice(7,8);
			if(egb2=='.') {
				sstr = sstr.substring(0,3)+sstr.substring(4,7)+sstr.substring(8);
				document.getElementById("searchff_form").query.value = sstr;
			}
		}
		if (x == "sub") {
			return true;
		} else {
			document.getElementById("searchff_form").query.value = document.getElementById("searchff_form").query.value.toLowerCase();
			document.getElementById("searchff_form").submit();
		}
	} else {
		// document.suche.Query_Text.value = '';
		alert('Geben Sie bitte einen Suchbegriff ein.');
	}
}

var suggest;

function createNewFFSuggest(searchURL, searchResultsURL) {
		suggest					= new FFSuggest();
	var searchURL				= searchURL; 
	var searchResultsURL		= searchResultsURL;
	var formname				= "searchff_form";
	var divLayername			= "searchSuggest";
	var debugMode				= false;
	suggest.init(searchURL, formname, divLayername, debugMode, searchResultsURL,'','','searchInput');
	document.onmousedown = suggest.hideLayerOutsideCall;
}

function FFSuggest() {

	var pRequest;
	var pLayer;
	var pDebug					= false;
	var pInstanceName			= "";
	var pSearchURL				= "";
	var pSearchResultsURL 		= "";
	var inputQueryField			= "";
	var pFormId 				= "";
	var pLayerName				= "";
	var pQueryInput;
	var pSuggest				= new Array();
	var pLastQuery;
	var pCurrentSelection		= 0;
	var submitted				= false;
	
	this.init = function(searchURL, formId, divLayername, debugMode, searchResultsURL, mandantParamName, mandant, queryInputId) {
		pSearchURL						= searchURL;
		pSearchResultsURL				= searchResultsURL;
		pFormId							= formId;
		pMandantParamName				= mandantParamName;
		pMandant						= mandant;
		pLayerName						= divLayername;
		pDebug							= false;
		
		if (pSearchURL == "") {		
			if (pDebug) alert("no searchurl defined");
			return null;
		} else if (pFormId == "") {
			if (pDebug) alert("no formId defined");
			return null;
		} else if (queryInputId == "") {
			if (pDebug) alert("no queryInputId defined");
			return null;
		} else if (pLayerName == "") {
			if (pDebug) alert("need a layer for output");
		}
		pQueryInput 					= document.getElementById(queryInputId);
		pQueryInput.onkeyup				= handleKeyPress;
		pQueryInput.onfocus				= showLayer;
		pQueryInput.onblur				= hideLayer;
		
		document.getElementById(pFormId).onsubmit 	
										= handleSubmit;
	}

	function handleSubmit() {
		submitted = true;
		if (pSuggest[pCurrentSelection] != undefined) {
			if ((typeof(pSearchResultsURL) != 'undefined') && (pSearchResultsURL != null))
				document.getElementById(pFormId).action = pSearchResultsURL;
			
			if (pSuggest[pCurrentSelection].split('###')[1] == "Kategorie") {
				document.getElementById(pFormId)["filterkategorie"].value = "__" + pSuggest[pCurrentSelection].split('###')[0] + "__";
				pQueryInput.value = "";
			}
			else {
				pQueryInput.value = pSuggest[pCurrentSelection].split('###')[0];
			}
		}
	}
	
	this.handleClick = function(pos) {
		if (pSuggest[pos] != undefined) {
			pCurrentSelection = pos;
			handleSubmit();
			document.getElementById(pFormId).submit();
		}
	}
	
	this.handleMouseOver = function(pos) {
		pCurrentSelection = pos;
	}
	
	this.handleMouseOut = function(pos) {	
		pCurrentSelection = -1;	
	}	
	
	function handleKeyPress(evt) {
		evt = (evt) ? evt : ((event) ? event : null);
		var keyCode = evt.keyCode;
		if (keyCode == 38) {
			moveSelection("up")
		} else if (keyCode == 27) {	
			hideLayer();
			pLastQuery = "";
		} else if (keyCode == 40) {
			moveSelection("down");
		} else {
			if (pQueryInput.value == "") {
				pLastQuery	= "";
				pSuggest	= new Array();
				
				hideLayer();
				if (pLayer != null) {
					removeChildren();
				}	
				return null;
			}
			if (pLastQuery != pQueryInput.value && pQueryInput.value.length > 1) startAjax();
			
			pLastQuery = pQueryInput.value;
		}
	}
	
	function moveSelection(direction) {
		var pos = pCurrentSelection;
		if (direction == "up") {
			pos--;
		} else {
			pos += 1;
		}
		
		if (pos < 0) {
			pQueryInput.focus();
			pCurrentSelection	= -1;
			highLight(-1);
		} else if(pos < pSuggest.length) {
			 	highLight(pos);
				pCurrentSelection = pos;
			}
		
		var query 			= pQueryInput.value;
		pQueryInput.value 	= "";
		pQueryInput.focus();
		pQueryInput.value 	= query; 
	}
	
	function highLight(pos) {
		for (var i =0; i <  $(pLayer).children().children().length; i++) {
			$(pLayer).children().children()[i].style.backgroundColor = '#FFFFFF';
		}
		
		if(pos>=0) {
			$(pLayer).children().children()[pos].style.backgroundColor = '#FFEECC';
		}
	}
	
	
	
	function removeChildren() {
		if ( $(pLayer).children().size() > 0 ) {
			$(pLayer).children().remove();
		}
	}
	function startAjax() {
		var query = pQueryInput.value;
		var requestURL = pSearchURL +  escape(query) ;
		
		try {
			if( window.XMLHttpRequest ) {
				pRequest = new XMLHttpRequest();
			} else if( window.ActiveXObject ) {
				pRequest = new ActiveXObject( "Microsoft.XMLHTTP" );
			} else {
				if (pDebug) alert( "" );
			}
			
			pLayer = document.getElementById(pLayerName);
			if (pLayer != null) {
				if (query != "") {

					pRequest.open( "GET", requestURL, true );
					pRequest.onreadystatechange = callbackAjax;
					pRequest.send( null );
				} else {
					hideLayer();
				}
			} else {
				if (pDebug) alert( "no layer for output found" );
			}
		} catch( ex ) {
			hideLayer();
			if (ex == undefined) {
				if (pDebug) alert( "Error: " + ex.getmessage );
			} else {
				if (pDebug) alert( "Error: " + ex );
			}
		}
	}
	
	function hideLayer() {
		if(document.getElementById(pLayerName).style.display != "none"
		&& document.getElementById(pLayerName).style.display != '') {
			jsUI.showSelectsForIE6();
			hideTopLayer('#' + pLayerName, $(this));
		}
	}
	
	this.hideLayerOutsideCall = function() {
		hideLayer();
	}
	
	function showLayer() {
		if (pSuggest != null && pSuggest.length >= 1) {
			if(document.getElementById(pLayerName).style.display != "block") {
				jsUI.hideSelectsForIE6();
				showTopLayer('#' + pLayerName, $(this));
			}
		}
	}
	
	function callbackAjax() {
		if (submitted == false) {
			if (pRequest.readyState == 4) {
				if (pRequest.status != 200) {
					hideLayer();
					if (pDebug) alert( "Error (" + pRequest.status + "): " + pRequest.statusText );
				} else {
					handleResponse(pRequest.responseText);
					/* For debugging only 
					if(pQueryInput.value.length > 3)
						handleResponse("Hanteln & Co.###14 Produkte###Kategorie###1664540\n");
					else
						handleResponse("Hanteln & Co.###14 Produkte###Kategorie###1664540\nHalstücher###126 Produkte###Kategorie###2722972\nHosenrock###8 Produkte###Kategorie###2115736\nHandys###306 Produkte###Kategorie###2290606\nHaarglätter###81 Produkte###Kategorie###3003725\nHotpants###51 Produkte###Kategorie###1354254\nHocker###635 Produkte###Kategorie###1776159\nHimmelbetten###6 Produkte###Kategorie###1847972\nHandtücher###33 Produkte###Kategorie###2948848\nKüche & Haushalt###159 Produkte###Kategorie###2737477\n");
					*/
				}
			}
		}
    }
	
	function funcRef(func, i) {
		return function() {
			func(i);
		};
	}	
		
	function handleResponse(text) {
		pCurrentSelection 			= -1;
		pSuggest 					= new Array();
		pSuggest 					= text.split("\n");
		
		var pNewSuggest 			= new Array();
		
		for (var i in pSuggest) {
			var firstChar = pSuggest[i].charCodeAt(0);
			if (firstChar != 13 && firstChar != 10 && pSuggest[i].length >= 1) {
				pNewSuggest.push(pSuggest[i]);
			}
		}
		
		pSuggest 					= pNewSuggest;
		var query 					= pQueryInput.value;
		var ulElement 				= document.createElement('ul');
		
		for (var i in pSuggest) {
			pSuggestParts 			= new Array();
			pSuggestParts 			= pSuggest[i].split("###");
			
			var pSuggestion			= pSuggestParts[0].replace(new RegExp("("+query+")","ig"),"<span class=\"highlightText\">$1</span>");
			var pQuantity 			= pSuggestParts[1];
			var pCategory 			= pSuggestParts[2];
			var pImageName 			= pSuggestParts[3];
			
			var listElement 		= document.createElement('li');
			
	        if (listElement.addEventListener) {
	        	listElement.addEventListener('click',funcRef(suggest.handleClick,i),false);
	        	listElement.addEventListener('mousedown',funcRef(suggest.handleClick,i),false);
	        	listElement.addEventListener('mouseover',funcRef(suggest.handleMouseOver,i),false);
	        	listElement.addEventListener('mouseout',funcRef(suggest.handleMouseOut,i),false);
	        }
	        else if (listElement.attachEvent) {
	        	listElement.attachEvent('onclick',funcRef(suggest.handleClick,i));
	        	listElement.attachEvent('onmousedown',funcRef(suggest.handleClick,i));
	        	listElement.attachEvent('onmouseover',funcRef(suggest.handleMouseOver,i));
	        	listElement.attachEvent('onmouseout',funcRef(suggest.handleMouseOut,i));
	        }

			var pImage 				= document.createElement('img');
			pImage.src				='http://image01.otto.de/pool/formate/'+pImageName+'.jpg';
			
			var spanCategory 		= document.createElement('span');
			spanCategory.className 	= 'cat';
			
			spanCategory.appendChild(document.createTextNode(pCategory));
			
			var strongElm 			= document.createElement('strong');
			var aLink 				= document.createElement('a');

			var brElm 				= document.createElement('br');
			var brElm2 				= document.createElement('br');
			var brClear				= document.createElement('br');
			
			brClear.className		= 'clear';
			
			listElement.appendChild(pImage);
			listElement.appendChild(spanCategory);
			listElement.appendChild(brElm);
			listElement.appendChild(strongElm);
			
			strongElm.appendChild(aLink);

			aLink.innerHTML = pSuggestion;
			
			if(pSuggestParts[1] != null && pSuggestParts[1].length>0){
				listElement.appendChild(brElm2);
				listElement.appendChild(document.createTextNode('('+ pQuantity +')'));
			}
			else {
				listElement.appendChild(brClear);
			}

			ulElement.appendChild(listElement);
		}
		
		if (pSuggest.length >= 1) {
			removeChildren();
			pLayer.appendChild(ulElement);
			showLayer();
		} else {
			hideLayer();
			removeChildren();
		}
	}
}


window.jsUI = {
	/** 
	 * Gives nested UL lists or something similar the behavior of a
	 * hover menu (of course the CSS styles have to be set properly).
	 * You just have to pass the jQuery selector expression for the main
	 * items of the menu, the class name of the 'hover' class and optionally
	 * the time in milliseconds the submenu's showing up shall be delayed
	 * (default is 0).
	 */
	hoverMenu: function(itemsSelector, hoverClass, delayTime) {
		var $ = jQuery;

		if ($.trim(itemsSelector) !== '' && $.trim(hoverClass) !== '') {
			$(function() {
				var delay = 0;

				if (delayTime > 0) {
					delay = delayTime;
				} // end: if

				var defaultDelay = delay;
				var items = $(itemsSelector);

				// Timer1 is responsible to delay the 
				// showing up of the submenus.
				var timer1 = null;

				// Timer2 is responsible to reset the delay from
				// 0 milliseconds to the default delay time (as
				// moving from one main item to the other should
				// result in a delayed show up of the submenus.
				var timer2 = null;

				// Safe version of clearTimeout.
				var clearTimer = function(timer) {
					try {
						clearTimeout(timer)
					} catch (_) {
					} // end: try
				} // end: function clearTimer

				items.each(function(idx, item) {
					// Add event handlers for each main item.
					item = $(item);

					item.mouseover(function() {
						clearTimer(timer1);
						//alert("here");

						timer1 = setTimeout(function() {
							clearTimer(timer2);
							items.not(item).removeClass(hoverClass);
							item.addClass(hoverClass);
							delay = 0;
						}, delay);
					}); // end: mouseover

					item.mouseout(function() {
						clearTimer(timer1);
						//alert("there");
						timer1 = setTimeout(function() {
							items.removeClass(hoverClass);
						}, 0);

						timer2 = setTimeout(function() {
							delay = defaultDelay;
						}, defaultDelay);
					}); // end: mouseout
				}); // end: items.each
			});
		} // end: if
	}, // end: function hoverMenu
	
	hoverMenuSimple: function(itemsSelector, hoverClass, delayTimeIn, delayTimeOut) {
		var $ = jQuery;
		
		if ($.trim(itemsSelector) !== '' && $.trim(hoverClass) !== '') {
			$(function() {
				var delayIn = 0;
				var delayOut = 0;

				if (delayTimeIn > 0) {
					delayIn = delayTimeIn;
				} // end: if
				
				if (delayTimeOut > 0) {
					delayOut = delayTimeOut;
				} // end: if

				var items = $(itemsSelector);

				// Timer1 is responsible to delay the 
				// showing up of the submenus.
				var timer1 = null;
				
				// Safe version of clearTimeout.
				var clearTimer = function(timer) {
					try {
						clearTimeout(timer)
					} catch (_) {
					} // end: try
				} // end: function clearTimer

				items.each(function(idx, item) {
					// Add event handlers for each main item.
					item = $(item);

					item.mouseover(function() {
						clearTimer(timer1);
						
						// --- 
						
						timer1 = setTimeout(function() {
							// --- edited by dmc |gm
							if($.browser.msie && parseFloat($.browser.version.substr(0,1)) < 7){
								$('select').css("visibility", "hidden");
							} 
							items.not(item).removeClass(hoverClass);
							item.addClass(hoverClass);
						}, delayIn);
					}); // end: mouseover

					item.mouseout(function() {
						clearTimer(timer1);
						
						// --- 
						
						timer1 = setTimeout(function() {
							items.removeClass(hoverClass);
							// --- edited by dmc |gm
							if($.browser.msie && parseFloat($.browser.version.substr(0,1)) < 7){
								$('select').css("visibility", "");
							}
						}, delayOut);

					}); // end: mouseout
				}); // end: items.each
			});
		} // end: if
	}, // end: function hoverMenu
      


	/**
	 * Makes given containers tab enabled.
	 * HTML structure must be something like:
	 * 
	 * <div class="tabnav">
	 *   [<p>Optional title for all tabs</p>]
	 *   <ul>
	 *     <li class="active">
	 *       <a>Page 1</a>
	 *     </li>
	 *     <li>
	 *       <a>Page 2</a>
	 *      </li>
	 *   </ul>
	 *   <div>
	 *      <div>
	 *        Content of page 1
	 *      </div>
	 *      <div>
	 *        Content of page 2
	 *      </div>
	 *   </div>
	 * </div>
	 */
	tabBox: function(selection) {
    	if (selection) {
			jQuery(function() {
				var $ = jQuery;

				$(selection).each(function(_, tabBox) {
					var tabBar = $(tabBox).find('> ul');
					var tabs = $(tabBar).children();
					var contents = $(tabBox).find('> :not(:first)').find('> div');
					var unknownElementsCount = 0;
					
					var update = function() {
						tabs.each(function(i, elem) {
							var content = $(contents.get(i));

							// Check whether current content is empty, if yes
							// hide it including its related tab.
							if (content.html() && content.html()
									.replace(/<(img|object|embed)\s+[^>]*>/g, '*')
									.replace(/<[^>]*>|&nbsp;/g, '')
									.replace(/^\s+|\s+$/g, '') !== '') {
								$(tabs.get(i)).removeClass('hide').show();
							} else {
								$(tabs.get(i)).hide();
								content.hide();
							} // end: if
						});

						// Determinate active tab.
						var active = tabBar.find('.active:visible:first');

						if (active.size() == 0) {
							active = $(tabs.filter(':visible:first'));
						} // end: if

						// Determinate index of active tab.
						activeIdx = 0;

						tabs.each(function(i, elem) {
							if (elem == active.get(0)) {
								activeIdx = i;
							} // end: if
						});

						// Update tab styles.
						active.removeClass('inactive').addClass('active').css('cursor', 'default');
						tabs.not(active).removeClass('active').addClass('inactive').css('cursor', 'pointer');

						// Show active content, hide non-active content.
						var activeContent = $(contents.get(activeIdx));
						contents.not(activeContent).hide();
						activeContent.removeClass('hide').show();
					}

					update();
					
					tabs.each(function(_, tab) {
						$(tab).click(function() {
							tabs.not(tab).removeClass('active').addClass('inactive');
							$(tab).removeClass('inactive').addClass('active');
							update();
						});
					});
				});
			});
		} // end: if
	}, // end: function tabBox      
    
	/**
	 * enables slide down for service information elements
	 */
	

    toggleService: function() {
        
		toggle_cont_count = 0;
		box_mode = 0;
		
		//check for class 'openbox'
		$(".toggle_container").each(function() {
			
			if($(this).hasClass('openbox')){
				box_mode = 1;
			}
		})
		if (box_mode == 1){
			$(".toggle_container").each(function() {	
				if($(this).hasClass('openbox')) {
					$(this).prev().addClass( 'active' );
				}else{
					$(this).hide();	
				}
				toggle_cont_count++;
			});
		}else{
			//set first element active and hide other elements
				$(".toggle_container").each(function() {	
					if(toggle_cont_count > 0) {
						$(this).hide();
					}else{
						$(this).parent().children("h2.trigger:first").addClass( 'active' );
					}
					toggle_cont_count++;
				});
		}
		
    	$("h2.trigger").click (function(){
			if (!$(this).hasClass("active")) {
				$(this).addClass("active"); 
				$(this).next(".toggle_container").slideDown("fast");
    		} else {
				$(this).removeClass("active");
				$(this).next(".toggle_container").slideUp("fast");
			}
    	});

    },
	
	/**
	 * hides select elements when showing a layer on top
	 * @bugfix IE6 uses native select elements that have a higher z-index than browser elements
	 * @param selector optional alternative css selector for desired select-elements
	 * @return void
	 */
	hideSelectsForIE6 : function (selector) {
		var s = selector || 'select:visible';
		if (jQuery.browser.msie && jQuery.browser.version.substr(0,1)!=6) return true;
		
		jQuery(s).addClass('ie6hidden');
		return true;
	},
	
	/**
	 * shows select elements when showing a layer on top
	 * @bugfix IE6 uses native select elements that have a higher z-index than browser elements
	 * @param selector optional alternative css selector for desired select-elements
	 * @return void
	 */
	showSelectsForIE6 : function (selector) {
		var s = selector || 'select.ie6hidden';
		if (jQuery.browser.msie && jQuery.browser.version.substr(0,1)!=6) return true;
		
		jQuery(s).removeClass('ie6hidden');
		return true;
	}
}

// click-functions for layer
function showTopLayer(id, trigger) {
        $(id).slideDown('fast');
        $(trigger).addClass('open');
}

/**
 * to be sure the onblur-event doesn't  display the layer
 */
function hideTopLayer(id, trigger) {
        $(id).slideUp('fast');
        $(trigger).removeClass('open');
		jsUI.showSelectsForIE6();
}

