/********************************************************************/
/* START: PFController                                              */

var EventHelper = Class.create();

EventHelper.getInstance = function(elm) {
	if (!EventHelper.instance) {
		EventHelper.instance = new EventHelper(elm);
	}
	return EventHelper.instance;
}

EventHelper.prototype = {

	initialize: function(elm)
	{
		this.elm = $(elm);
		this.offset = this.elm.cumulativeOffset();
		this.active = true;
		this.resumeEvent();
	},
	calc: function(e)
	{
		if(e)
		{
			var coordx = Event.pointerX(e);
			var coordy = Event.pointerY(e);

			var helperElement = $('pftmousepositionframe').cumulativeOffset();

			var taboffset = 20;

			if(Info.browser.isIE)
			{
				taboffset += 5;
			}

			if((this.offset.left > coordx - 10)
			   || (this.offset.top > coordy - taboffset)
			   || (helperElement.top < coordy)
			   || (this.offset.left + 440 < coordx + 10)
			  )
			{
				if(this.active)
				{
					selFeatureVisualLink = null;
					PFFlashController.getInstance().hideDhtml();
				}
			}
		}
	},
	_over: function(e)
	{
		var coordx = Event.pointerX(e);
		var coordy = Event.pointerY(e);
	},
	pauseEvent: function()
	{
		this.active = false;
		this.elm.stopObserving("mouseout",function(e) {this.calc(e)}.bindAsEventListener(this));
	},
	resumeEvent: function()
	{
		this.active = true;
		this.elm.observe("mouseout", function(e) {this.calc(e)}.bindAsEventListener(this));
	}
}

/********************************************************************/

var PFRandomNr = Math.random();
var PFFlashController = Class.create();

PFFlashController.getInstance = function(elm) {
	if (!PFFlashController.instance) {
		PFFlashController.instance = new PFFlashController();
	}
	return PFFlashController.instance;
}

PFFlashController.prototype = {
	initialize: function() {

		this.mainframe = $('headerpftvisual-zone');
		this.headline = $('pftvisual-headline');
		this.description = $('pftvisual-description');

		this.hideDhtml();
	},
	showDhtml: function(aPic,aHead,aCopy)
	{
		var pic = PF_RESOURCES_PATH + "prof/import/pool/" + aPic;

		$('headervisual-zone').style.visibility = 'hidden';

		$('pftvisual-visual').update();
		$('pftvisual-visual').setOpacity(0);

		var preLoad = new Image();
		preLoad.style.width = 640 + "px";
		preLoad.style.height = 393 + "px";

		preLoad.onload = function()
		{
			$('pftvisual-visual').setStyle("width:640px; opacity:0; filter:alpha(opacity=0);");
			$('pftvisual-visual').update(preLoad);
			Spry.Effect.DoFade($('pftvisual-visual'), {duration:2000, to:100});
		}
		preLoad.src = pic;

		$('pftvisual-headline').update(aHead);
		$('pftvisual-description').update(aCopy);

		this.mainframe.style.visibility = 'visible';

	},
	hideDhtml: function(aPic)
	{
		this.mainframe.style.visibility = 'hidden';
		$('headervisual-zone').style.visibility = 'visible';
		if( $('ng_feature') ) $('ng_feature').setStyle("opacity:100; filter:alpha(opacity=100);");
	}
}

function callPfFlashMethod() {
	var args = new Array();
	for (var i = 0; i < arguments.length; i++)
		args.push(arguments[i]);
	
	//flashController.flashSetVariable('productFinderFlash','callFlashMethod',args.join('$$$'));
	pfflash.rewrite(PFT_LANGID, PFT_CONFIG, args.join('$$$')); //new implementation
}

var FlashController = Class.create();

FlashController.prototype = {
	initialize: function(id) {

	},
	/**
	 * we cannot use ExternalInterface because of flash player 7, so use the old method SetVariable
	 * NOTE: Opera has Bug on second call. first call just works fine. strange behavior. needs to be fixed!
	 */
	flashSetVariable: function(id,method, value) {
		_flashObj = $(id);
	    if(_flashObj) _flashObj.SetVariable(method,value);
	}
}



var PFT_REL_REGEX = /(\w{4}-\w{2}-)(\w+)-(\w+)-(\d+)/;

var PFController = Class.create();

PFController.prototype = {
	initialize: function(clusternumber,clusterlanguage) {

		var blankpftopener = new Element('a', {id: 'blankpftopener', href:'javascript:void(0);'}).update();
		$('pftmousepositionframe').update(blankpftopener);
		this.pfLayer = new PFContentLayer($('toolbar-layer-productfinder'),$('blankpftopener'));

		this.siteid = clusternumber;
		this.langid = clusterlanguage;

    this.nrClusters = null;
    this.loadedClusters = 0;
		this.loadCluster();

	},

	addLayerLink: function(pftlinks)
	{
		var pfttoollinks = $$('#' + pftlinks + ' a[rel]');
		pfttoollinks.each(
			function(elt) {
				elt = $(elt);
				if (PFT_REL_REGEX.test(elt.rel)) { // layer link

					PFT_REL_REGEX.exec(elt.rel);
					var clustername = RegExp.$3;
					var nodeid = RegExp.$4;

					elt.observe("click", function(e) {this.pfLayer.action = "init";this.pfLayer.setPf(e,clustername,nodeid);this.pfLayer.toggle();Event.stop(e); }.bindAsEventListener(this));
				}
			}.bind(this)
		);
	},

	openExternalWindow: function(externalLink)
	{
		openWindow(externalLink);
		return false;
	},

	loadDeeplink: function(values)
	{
		this.pfLayer.action = "deep";
		this.pfLayer.pfContentLayerDeepArray = values;
		
		this.pfLayer.toggle();
	},

	searchDeeplink: function(values)
	{
		this.pfLayer.action = "search";
		this.pfLayer.pfContentLayerDeepArray = values;
		this.pfLayer.toggle();
	},

	createCluster: function(oXHR)
	{
		var xmlCluster = oXHR.responseXML.documentElement;

		var clusterId = xmlCluster.attributes.getNamedItem('id').nodeValue;
		var clusterCount = 0;
		
		this.loadedClusters += 1;
		/**
		 * layout values: 0 = column layout, 1 = horizontal layout
		 */

		var layout = 0;
		if(clusterId == "brandnames")
		{
			layout = 1;
			var glossaryList = new Element('ul', {'class': 'clearfix'});
		}

				var myClusterName = xmlCluster.attributes.getNamedItem('name').nodeValue;

				var tablink = 'tablistlink' + clusterId;

				$(tablink).update(myClusterName);
               
				var uleftlistid = 'tab' + clusterId + 'link1';
				var urightlistid = 'tab' + clusterId + 'link2';

				var uleftList = new Element('ul', {id:uleftlistid, 'class': 'link'});
				var urightList = new Element('ul', {id:urightlistid, 'class': 'link'});

				var nodes = $A(xmlCluster.getElementsByTagName("node"));
				nodes.each(function(item)
				{
					if(item.parentNode.tagName == 'cluster')
					{
						var nodeId = item.attributes.getNamedItem('id').nodeValue;
						var nodeName = item.attributes.getNamedItem('name').nodeValue;
						var visible = item.attributes.getNamedItem('visible').nodeValue;
						var newWindow = (item.attributes.getNamedItem('window') == null) ? 0 : item.attributes.getNamedItem('window').nodeValue;

						var isEndpoint = true;
						var hasNoChilds = true;

						if($A(item.childNodes).find(function(n){return n.tagName == "node" ? true : false;}))
						{
							if(clusterId == "brandnames")
							{
								hasNoChilds = false;
							}
							else
							{
								isEndpoint = false;
							}
						}

						var teaser = $A(item.getElementsByTagName("teaser"));
						teaser.each(function(teaserItem){
							if(teaserItem.parentNode.parentNode.tagName == 'cluster')
							{
								var teaserId = teaserItem.attributes.getNamedItem('id').nodeValue;
								var teaserName = teaserItem.attributes.getNamedItem('name').nodeValue;
								var relLink = 'jump-to-productfinder-' + clusterId + '-' + nodeId;

								if(layout == 1)
								{
									if(visible = 1)
									{
										if(hasNoChilds)
										{
											var linkListElement = new Element('li', {}).update(teaserName);
										}
										else
										{
											var linkElement = new Element('a', { href:'javascript:void(0);', rel: relLink}).update(teaserName);
											var linkListElement = new Element('li', {}).update(linkElement);
										}

										glossaryList.appendChild(linkListElement);
									}
								}
								else
								{
									if(isEndpoint)
									{
										var openerLink = (item.attributes.getNamedItem('link') == null) ? '' : item.attributes.getNamedItem('link').nodeValue;
										 
										/**
										 * new tracking implementation
										 */
										var clickHandler = 'javascript:void(0);';
										if(newWindow == 1)
										{
											clickHandler = (openerLink == '') ? '#' : "javascript:openWindow('" + openerLink + "');";
											clickHandler += "ste.PF.exit({path:'"+clusterId+"', name:'"+item.attributes.getNamedItem('name').nodeValue+"', url:'" + openerLink + "', lang:'"+PFT_LANGID+"'});";
										}
										else if(newWindow == 0)
										{
											clickHandler = "javascript:ste.PF.exit({path:'"+clusterId+"', name:'"+item.attributes.getNamedItem('name').nodeValue+"', url:'" + openerLink + "', lang:'"+PFT_LANGID+"'});void(window.setTimeout(function() { window.location.href = \"" + openerLink + "\";}, 500));";
										}
										var linkElement = new Element('a', { href:clickHandler, 'class': 'link'}).update(item.attributes.getNamedItem('name').nodeValue);
									}
									else
									{
										var linkElement = new Element('a', { href:'javascript:void(0);', 'class': 'link', rel: relLink}).update(teaserName);
									}

									var featureImage = (teaserItem.attributes.getNamedItem('bigImage') == null) ? '' : teaserItem.attributes.getNamedItem('bigImage').nodeValue;
									var featureText = (teaserItem.attributes.getNamedItem('text') == null) ? '' : teaserItem.attributes.getNamedItem('text').nodeValue;

									new FeatureVisual(linkElement, clusterId, teaserId, featureImage, teaserName, featureText);

									var linkListElement = new Element('li', {}).update(linkElement);

									if(visible < 2)
									{
										uleftList.appendChild(linkListElement);
									}
									else if(visible == 2)
									{
										urightList.appendChild(linkListElement);
									}
								}
							}
						});
					}
				});

				var tabcontentlink = 'tab' + clusterId;
				if(layout == 1)
				{
					var glossaryDiv = new Element('div', {'class': 'glossary-index'}).update(glossaryList);
					$(tabcontentlink).appendChild(glossaryDiv);
					$A($$('div.glossary-index li')).last().addClassName("last");
				}
				else
				{
					var linkListDiv1 = new Element('div', {'class': 'link-list', style:'float:left;width:45%'}).update(uleftList);
					var linkListDiv2 = new Element('div', {'class': 'link-list', style:'float:right;width:50%'}).update(urightList);
          
          $(tabcontentlink).update();
					$(tabcontentlink).appendChild(linkListDiv1);
					$(tabcontentlink).appendChild(linkListDiv2);
				}

				this.addLayerLink(tabcontentlink);
				
				if(this.loadedClusters == this.nrClusters) {
				    pfReadyAfterLoad();
				}
	},

	loadCluster: function()
	{
	  this.nrClusters = clusterNameList.length;
      for(var i = 0; i < clusterNameList.length; i++)
	  {
			if(clusterNameList[i] == 'industry')
			{
				$('tab'+clusterNameList[i]).update();
			}
			new Ajax.Request(PF_RESOURCES_PATH + "prof/import/" + this.siteid + "/" + this.langid + "/" + clusterNameList[i] + ".xml" + "?" + PFRandomNr,
			{
				method: "get",
				onSuccess: this.createCluster.bind(this),
				onFailure: function (oXHR) {
					//"An error occurred: ";
				}
			});
	   }
	}
}

/* END: PFcontroller                                                */
/********************************************************************/
/* START: content layer                                             */

var PFContentLayer = Class.create();

PFContentLayer.prototype = Object.extend(new Layer, {

	initialize: function(node, trigger) {
		this.initSuper(node, trigger);

		this.action = 'init';
		this.pfContentLayerIntervalId;
		this.pfContentLayerCluster;
		this.pfContentLayerNodeid;
		this.pfContentLayerDeepArray = new Array(4);

		var closeButton = this.node.down("div.close");
		if (!closeButton) { // could be IE<6
			closeButton = $A(this.node.getElementsByTagName("div")).find(
				function(div) {
					return ($(div).hasClassName("close"));
				}
			);
		}

		if(!closeButton) alert("Implementation Error: no close button found");

		closeButton.observe("click",
			function() {
				this.close();
			}.bindAsEventListener(this)
		);
	},

	setPf: function(event, cluster, nodeid) {

		var linkElement = Event.findElement(event,'a');
		/**
		 * new tracking implementation
		 */
		ste.PF.nodeclick({path:cluster, name:linkElement.innerHTML, lang:PFT_LANGID});

		this.pfContentLayerCluster = cluster;
		this.pfContentLayerNodeid = nodeid;

		EventHelper.getInstance().pauseEvent();
	},

	afterClose: function(newLayer) {
		if (!Layer.toggle) {
			HeaderAnimation.augment();
		}
	},

	closePft: function() {
		selFeatureVisualLink = null;
		PFFlashController.getInstance().hideDhtml();
		callPfFlashMethod("reset");
		EventHelper.getInstance().resumeEvent();
	},

	afterOpen: function() {
		HeaderAnimation.diminish();

		this.callPF();
	},

	callPF: function() {
		this.pfContentLayerIntervalId = setInterval("pfcont.pfLayer.observeAnimation()",2000);
	},

	observeAnimation: function() {
		if(HeaderAnimation.augmented == false) {

			switch(this.action)
			{
				case 'init':
				callPfFlashMethod('init',this.pfContentLayerCluster + '.xml',parseInt(this.pfContentLayerNodeid,10));
				break;
				case 'deep':
				callPfFlashMethod('deep',this.pfContentLayerDeepArray[0] + '.xml',parseInt(this.pfContentLayerDeepArray[1],10),parseInt(this.pfContentLayerDeepArray[2],10), isNaN(this.pfContentLayerDeepArray[3]) ? 0 : parseInt(this.pfContentLayerDeepArray[3],10));
				break;
				case 'search':
				callPfFlashMethod('search',this.pfContentLayerDeepArray[0], this.pfContentLayerDeepArray[1] + '.xml');
				break;
				default:
				callPfFlashMethod('reset');
			}

			clearInterval(this.pfContentLayerIntervalId);
		}
	},

	beforeClose: function() {
		HeaderAnimation.registerLayer(this);
		this.closePft();
		return true;
	},

	beforeOpen: function() {
		HeaderAnimation.registerLayer(this);
		return true;
	},

	correctIframe: function() {
		this.iframeLining.correction.width = 4;
	},

	hide: function() {
		this.node.removeClassName("active-layer");
		this.trigger.up().removeClassName("active");
	},

	show: function() {
		this.node.addClassName("active-layer");
		this.trigger.up().addClassName("active");
	},

	setOffset:function(offset) {
		this.node.style.top = offset + "px";
		if (this.iframeLining) {
			this.iframeLining.setOffset(Position.cumulativeOffset(this.node)[1]);
		}
	}

});

/* END: content layer                                               */
/********************************************************************/
/* START: swap header feature                                       */

var selFeatureVisualLink = null;

var FeatureVisual = Class.create();
FeatureVisual.prototype = {
	initialize: function(listItem, clusterid, teaserid, imageid, headline, description)
	{
		this.clusterid = clusterid;
		this.teaserid = teaserid;
		this.loaded = true;

		this.imageid = imageid;
		this.headline = headline;
		this.description = description;

		listItem.observe("mouseover", function(e) {
			this.show(e);
		}.bindAsEventListener(this));
	},
	hide: function() {
		if( $('ng_feature') ) { /*added by Christian Wellh�fer 02.07.2009 for Next Generation Features */
			$('ng_feature').setStyle("opacity:100; filter:alpha(opacity=100);");
		}
		if (this.loaded) {
			selFeatureVisualLink = null;
			PFFlashController.getInstance().hideDhtml();
		} else {
			this.hideProgress();
		}
	},

	hideProgress: function() {
	},

	show: function(event) {
		var elm = Event.findElement(event,'a')
		if (this.loaded && elm != selFeatureVisualLink) {
			if(typeof featureFlash != 'undefined') {
				if(typeof featureFlash.stopVideo == 'function') {
					featureFlash.stopVideo();
				}
				if(typeof featureFlash.looseFocus == 'function') {
					featureFlash.looseFocus();
				}
				if ($('ng_feature')) { /*added by Christian Wellh�fer 02.07.2009 for Next Generation Features */
					$('ng_feature').setStyle("opacity:0; filter:alpha(opacity=0);");
				}
			}
			this.setSelected(elm);
			PFFlashController.getInstance().showDhtml(this.imageid,this.headline,this.description);

		} else {
			this.showProgress();
		}
	},

	showProgress: function() {
		// hook to show a progress symbol (image still loading)
	},

	setSelected: function(elm) {
		selFeatureVisualLink = elm;
	}
}

/* END: swap header feature                                         */
/********************************************************************/

var PFFlash = Class.create();

PFFlash.prototype = {
	initialize: function(lang,config)
	{
		/*var namespace = "";
        var fo = new SWFObject(PF_RESOURCES_PATH + "pub/flash/productfinder_v2_3/productfinder_flash7.swf", "productFinderFlash", "916", "450", "6,0,0,0", "#e7e8eb");
		fo.addParam("wmode", "opaque");
		fo.addParam("salign", "t");
		fo.addParam("swliveconnect","true");
		fo.addParam("FlashVars", "s_account=" + "" + "&lang="+lang+"&configurl="+config+namespace+"&delay=500&randomNr=" + PFRandomNr);
		fo.write("productFinder");*/
	},
	rewrite: function(lang,config, flashmethod)
	{
		$('productFinder').update('');
		var namespace = "";
		flashmethod = flashmethod || '';
		var fo = new SWFObject(PF_RESOURCES_PATH + "pub/flash/productfinder_v2_3/productfinder_flash7.swf", "productFinderFlash", "916", "450", "6,0,0,0", "#e7e8eb");
		fo.addParam("wmode", "opaque");
		fo.addParam("salign", "t");
		fo.addParam("swliveconnect","true");
		fo.addParam("FlashVars", "s_account=" + "" + "&lang="+lang+"&configurl="+config+namespace+"&delay=500&randomNr=" + PFRandomNr + "&callFlashMethod=" + flashmethod);
		fo.write("productFinder"); 
	}
}

/********************************************************************/
/*get urlparameter to set preselected productfinder tab*/
function getPreselectedPFTab() {
	var preselectedTab = 0;
	var hasHashParameter = false;
	var startTab = getUrlParameter("tab");
	if(startTab != "" && startTab != null && startTab.indexOf('#') != -1) {
		var urlParamParts = startTab.split("#");
		startTab = urlParamParts[0];
		var hashUrlParam = urlParamParts[1];
		var hashMatch = hashUrlParam.match(/^([a-z]*).xml-([0-9]{6,7})?-([0-9]{6,7}|0)?-([0-9]{6,7}|0)?$/);
		if(hashMatch && hashMatch.length ) {
			hasHashParameter = true;  
		}
	}
	//console.log("StartTab: " + startTab);
	if(startTab != null && startTab != "") {
		var nodes = startTab.split("-");
		if(nodes != null && nodes[0] != undefined && nodes[0] != "") {
			for(var i = 0; i < clusterNameList.length; i++) {
				if(clusterNameList[i] == nodes[0]) {
					preselectedTab = i;
				}
			}
      
			if(hasHashParameter) { return preselectedTab; }
      
			if(nodes[1] != undefined) {
				var deeplinkArray = []; //oh oh oh
				deeplinkArray[0] = nodes[0];
				var linkDescription = '';

				for(var i = 0; i < nodes.length; i++) {
					if(isNaN(nodes[i])) {
						linkDescription = nodes[i];
						if(i==3) {
							deeplinkArray[i] = nodes[i-1];
						}
						else if(i > 0 && i != 4) {
							deeplinkArray[i] = 0;
						}
					}
					else {
						if(i==3) {
							deeplinkArray[i] = (nodes[i] == undefined || nodes[i] == '') ? nodes[i-1] : nodes[i];
						}
						else if(i != 4) {
							deeplinkArray[i] = (nodes[i] == undefined || nodes[i] == '') ? 0 : nodes[i];
						}
					}
				}
				/**
				 * new tracking implementation
				 */
				ste.PF.deeplink({path: nodes[0], name: linkDescription, lang: PFT_LANGID});
				pfcont.loadDeeplink(deeplinkArray);
				
			} else {
				ste.PF.deeplink({path: nodes[0], lang: PFT_LANGID});
			}
		}
	}
	return preselectedTab;
}

/************************************************************************/
/******************PFT_SEARCH********************************************/
var PFSearchCompleter = Class.create();

PFSearchCompleter.prototype = {
	initialize: function()
	{
		this.setupSearch();

		this.input = $('search_term');
		this.pfSearchSubmit = $('pfSearchSubmit');

		this.top = 470;
		this.isFadeOpen = false;
		this.isPFOpen = false;
		this.SEARCH_REL_REGEX = /(deeptoproductfinder)(.+)$/;

		Event.observe(this.input,'keyup', this.onKeyUp.bindAsEventListener(this));
		Event.observe(this.pfSearchSubmit,'mousedown', this.onPfSearchSubmit.bindAsEventListener(this));
		Event.observe(this.pfSearchSubmit, 'mouseover', function(evt) { Event.element(evt).setAttribute('src','../framework/pub/img/go_on.gif'); } );
		Event.observe(this.pfSearchSubmit, 'mouseout', function(evt) { Event.element(evt).setAttribute('src','../framework/pub/img/go.gif'); } );
	},
	fadeopen: function()
	{
		this.isFadeOpen = !this.isFadeOpen;
	},
	setupSearch: function()
	{
		this.searchTerm = new Element('input', {
			id: 'search_term',
			name: 'searchfield',
			size: 50,
			type: 'text',
			autocomplete: 'off'
		});
		
		var resource_go = PF_RESOURCES_PATH + "pub/img/go.gif";
		if(PFT_SITEID == 100170 || PFT_SITEID == 100300) {
			resource_go =PF_RESOURCES_PATH + "pub/img/go.gif"
		}
		
		this.pfSearchSubmit = new Element('input', {
		  id: 'pfSearchSubmit',
		  'class': 'button',
		  type: 'image',
		  src: resource_go
		});
		var translation = (PFT_LANGID == 'de') ? "Weitere Produkte anzeigen" : "View more products";
		this.viewmorelink = new Element('a', {href: 'javascript:void(0);'}).update(translation);

		this.content = new Element('div', {id: 'content'});
		this.content.appendChild(this.searchTerm);
		this.content.appendChild(this.pfSearchSubmit);
		var linebreak = new Element('div', {'class': 'hruler'}).update('&#160;');

		this.content.appendChild(linebreak);
		$('tabbrandnames').appendChild(this.content);

		Event.observe(this.viewmorelink,'click', this.onPfSearchSubmit.bindAsEventListener(this));
		Event.observe(this.searchTerm, 'focus', this.searchOnFocus.bindAsEventListener(this));
	},
	addResult: function()
	{
		var searchresult = new Element('div',{'id': "searchresult", 'class': "pft_search_window hideInitially"});
		if($('animationContainer'))
		{
			$('animationContainer').remove();
		}
		var animationContainer = new Element('div', {id: 'animationContainer', 'class': "animationContainer"});
		animationContainer.update(searchresult);
		
		$('tablistframe').appendChild(animationContainer);
		
		
		Event.observe(document, "click", function(e) {
				if (this.isFadeOpen) {
					var element   = $(Event.element(e));
					var layerNode = $('animationContainer');
					if (element != layerNode && !element.descendantOf(layerNode)) {
						this.removeResult(e);
					}
				}
			}.bindAsEventListener(this)
		);
		

		this.flashFeature = $('FlashApplication');
		if(this.flashFeature) {
			Event.observe(this.flashFeature, 'focus', function(e){this.flashFeature.stopObserving("focus"),this.onFlashFocus(e)}.bindAsEventListener(this));
		}

	},
	onFlashFocus: function(event)
	{
		this.removeResult(event);
	},
	removeResult: function(event)
	{
		this.isFadeOpen = false;
		if($('animationContainer'))
		 {
			 $('animationContainer').remove();
		 }
	},
	onPfSearchSubmit: function(event)
	{
		var sT = $('search_term').getValue();
		if(sT.length > 0)
		{
			this.removeResult(event);
			this.isFadeOpen = false;
			this.isPFOpen = true;
			var searchArray = [sT,'brandnames'];
			pfcont.searchDeeplink(searchArray);
		}
	},
	onKeyUp: function(event)
	{
		var liveinput = $('search_term');

		if(liveinput.getValue() && !liveinput.getValue().match(" ") && liveinput.getValue().length > 2)
		{
			if(event.keyCode == 13)
			{
				$('search_term').blur();
				this.removeResult(event);
				this.onPfSearchSubmit();
			}
			else if(event.keyCode == 27)
			{
				this.removeResult(event);
			}
			else
			{
				this.input = $('search_term');
				this.autosuggest(this.input.getValue());
			}
		}
		else if(this.isFadeOpen)
		{
			this.removeResult(event);
		}
		else
		{
			this.isFadeOpen = false;
		}
	},

	searchOnFocus: function(event)
	{
		var liveinput = $('search_term');
		if(liveinput.getValue() && !liveinput.getValue().match(" ") && liveinput.getValue().length > 2 && !this.isFadeOpen)
		{
			this.input = liveinput;
			this.isPFOpen = false;
			this.autosuggest(this.input.getValue());
		}
	},

	autosuggest: function(value)
	{
		var url = PF_RESOURCES_PATH+'pub/script/proxy.php?region='+PFT_SITEID+'&language='+PFT_LANGID+'&suchtext=' + encodeURIComponent(value) + "&maxhits=10";

		new Ajax.Request(url,
		{
			method: "get",
			onSuccess: this.createResult.bind(this),
			onFailure: function (oXHR) {
				//error message
			}
		});
	},
	createResult: function(oXHR)
	{
		if(!this.isPFOpen)
		{
			this.addResult();
	
			var sT = this.input.getValue();
	
			$('searchresult').update("");
			
			var closeSpan = new Element('span', {'class': "access"}).update("Close Contact Layer");
			var closeLink = new Element('a', {id: 'pftclose', href: "javascript:void(0)"}).update(closeSpan);
			
			if(PFT_LANGID == 'de') {
				closeLink.addClassName('de');
			}
			var closeContainer = new Element('div', {'class': "pftclose"}).update(closeLink);
			if(PFT_LANGID == 'de') {
				closeContainer.setStyle({width: "78px"});
			}
			
			$('searchresult').appendChild(closeContainer);
	
			var xmlCluster = oXHR.responseXML.documentElement;
			var clusternodes = $A(xmlCluster.getElementsByTagName("cluster"));

			var showMoreProducts = false;
			if($A(xmlCluster.getElementsByTagName("node")).size() >= 10) {
				showMoreProducts = true;
			}

			var filter = ["industries","products"];
			if(clusternodes.size() > 3 && $A(xmlCluster.getElementsByTagName("division")).size() > 5 && $A(xmlCluster.getElementsByTagName("node")).size() >= 10)
		    {
				filter.push("brandnames");
		    }

			clusternodes.each(function(item)
			{
				var clusterNodeName = item.attributes.getNamedItem('name').nodeValue;
				var clusterNodeId = item.attributes.getNamedItem('id').nodeValue;
	
				if($A(filter).indexOf(clusterNodeId) == -1)
				{
					var level1Div = new Element('div', {'class': 'level-1'}).update(clusterNodeName);
					$('searchresult').appendChild(level1Div);
	
					var divisons = $A(item.getElementsByTagName("division"));
					divisons.each(function(divisonitem)
					{
						var divisonName = divisonitem.attributes.getNamedItem('name').nodeValue;
						var divisonId = divisonitem.attributes.getNamedItem('id').nodeValue;
	
						var level2relLink = 'deeptoproductfinder|' + clusterNodeId + '|' + divisonId;
						var level2deeplink = new Element('a', {href: 'javascript:void(0);', rel: level2relLink}).update(divisonName);
						var level2Div = new Element('div', {'class': 'level-2'}).update(level2deeplink);
	
						$('searchresult').appendChild(level2Div);
	
						var nodes = $A(divisonitem.getElementsByTagName("node"));
						nodes.each(function(nodeitem)
						{
							var nodeName = nodeitem.attributes.getNamedItem('name').nodeValue;
							var reg = new RegExp(sT, "i");
							var sTPos = nodeName.search(reg);
							var boldName = nodeName.substring(0,sTPos) + "<b>" + nodeName.substring(sTPos,sTPos+sT.length) + "</b>" + nodeName.substring(sTPos+sT.length,nodeName.length);							
							var nodenamepath = "";
							var nodeIdNamePath = nodeitem.attributes.getNamedItem('nodeidnamepath').nodeValue;
	
							if(nodeIdNamePath.length > 0)
							{
								var path = nodeIdNamePath.split("|");
								if(path[0].length == 0)
								{
									path.shift();	
								}
								nodenamepath = path.join(" / ");
								var LIMIT = 80;
								if(nodenamepath.length + boldName.length > LIMIT)
								{
									var len = LIMIT - boldName.length;
									nodenamepath = "( " + nodenamepath.substring(0,len) + "... )";
								}
								else
								{
									nodenamepath = "( " + nodenamepath + " )";
								}
							}
							
							var spanPath = new Element('span').update(boldName + " " + nodenamepath);
	
							var nodeid = nodeitem.attributes.getNamedItem('id').nodeValue;
							var nodeIdPath = nodeitem.attributes.getNamedItem('nodeidpath');
							var nodelink = nodeitem.attributes.getNamedItem('link');
	
							if(nodelink && nodelink.nodeValue.length > 0)
							{
								//exitlink
								var openerLink = nodelink.nodeValue.strip();
								//var clickHandler = (openerLink == '') ? '#' : "javascript:openWindow('" + openerLink + "');trackPFExtLink('"+nodeName+"','" + openerLink + "','"+clusterNodeId+"');";
								/**
								 * new tracking implementation
								 */
								var clickHandler = (openerLink == '') ? '#' : "javascript:openWindow('" + openerLink + "');";
								clickHandler += "ste.PF.exit({path:'"+clusterNodeId+"', name:'"+nodeName+"', url:'" + openerLink + "', lang:'"+ PFT_LANGID +"'});";

								var linkElement = new Element('a', { href:clickHandler, 'class': 'link'}).update(spanPath);
							}
							else
							{
								//deeplink
								var relLink = 'deeptoproductfinder|' + clusterNodeId + '|' + divisonId;
								if(nodeIdPath && nodeIdPath.nodeValue.length > 0)
								{
									relLink += nodeIdPath.nodeValue + '|' + nodeid;
								}
								else
								{
									relLink += '|' + nodeid;
								}
								var linkElement = new Element('a', {href: 'javascript:void(0);', rel: relLink}).update(spanPath);
							}
							var level3Div = new Element('div', {'class': 'level-3'}).update(linkElement);
							$('searchresult').appendChild(level3Div);
						});
					});
				}
			});
	
			if(clusternodes.size() > 0)
			{
				var viewmoreDiv = new Element('div', {'class': 'more-level'}).update("&nbsp;");
				if(showMoreProducts)
				{
					viewmoreDiv.update(this.viewmorelink);
				}
				$('searchresult').appendChild(viewmoreDiv);
				
				var height = $('searchresult').getHeight();
				var spacer = (this.top - height) + 'px'; //var spacer = (this.top - height - 10) + 'px';
				$('searchresult').setStyle({top: spacer});
				$('searchresult').removeClassName('hideInitially');
				this.isFadeOpen = true;
				this.observeSearchlinks();
			}
		}
	},
	observeSearchlinks: function()
	{
		var pfttoollinks = $$('#searchresult a[rel]');
		pfttoollinks.each(
			function(elt) {
				elt = $(elt);
				if (this.SEARCH_REL_REGEX.test(elt.rel)) {
					elt.observe("click", function(e) {this.loadDeeplink(e);Event.stop(e);}.bindAsEventListener(this));
				}
			}.bind(this)
		);
		
		var closeButton = $('pftclose');
		if(closeButton)
		{
			closeButton.observe("click", function(e){this.removeResult(e);}.bindAsEventListener(this));// 
		}
	},
	loadDeeplink: function(event)
	{
		var deeplink = Event.findElement(event, 'a');
		var rel = deeplink.rel;
		var nodes = rel.split("|");
		nodes.shift();

		var deeplinkArray = new Array(4);
		deeplinkArray[0] = nodes[0];
		deeplinkArray[1] = (nodes[1] == undefined || nodes[1] == '') ? 0 : nodes[1];
		deeplinkArray[2] = (nodes[2] == undefined || nodes[2] == '') ? 0 : nodes[2];
		var lastNode = nodes.pop();
		deeplinkArray[3] = (lastNode == undefined || lastNode == '') ? 0 : lastNode;

		pfcont.loadDeeplink(deeplinkArray);
		this.isPFOpen = true;
		this.removeResult(event);
	}
}
/************************************************************************/
/******************PF_HASHHISTORY***************************************/
var PFhashHistory = Class.create();
PFhashHistory.prototype = {
	_initialized: 		false,
	_iframeID: 			'hashHistory-iframe',
	_method: 			(navigator.appName.indexOf('Microsoft Internet') != -1) ? 'IFRAME' : 'HASH',
	stateID:			null,				//current state id
	defaultStateID: 	'defaultState',		//causes no _dispatchEvent
	_oldStateID: 		null,				//
	_intervalID: 		null,				//interval ID
	_checkInterval:		100,				//rate the location.hash is checked (in ms)
	_debug:				false,				//set this to true for debug
	_preventPageRefresh:false,				//IE var (not used anymore)
	_hashActions:		new Array(),
	initialize: function( params ) {
		var hashCallbacks = params || false;
        this.stateID = this._getStateID();
        
		switch(this._method) {
			case 'IFRAME':	
					// Create and attach the iframe.
			        var iframe = new Element('iframe',{ name:this._iframeID, 'id':this._iframeID });
					$(iframe).setStyle({ width:'0px', height:'0px', position:'absolute', display:'none' });
					document.body.appendChild(iframe);
		        break;
			case 'HASH':
					/**
			         * Firefox & Safari approach, we can handle URL changes without IFrame, _but_ firefox does not re-run javascript when pressing 
			         * the back-button on an external URL and coming back to page, like we need it, so we add a dummy iframe.
			         * This iframe _needs_ to have a src attribute or it wont force FF to re-evaluate page
			         */
					 // Create and attach the iframe.
					var srcPath = PF_RESOURCES_PATH + 'pub/noscript/empty.htm';
			        var iframe = new Element('iframe',{ name:this._iframeID, 'id':this._iframeID, src: srcPath });
					$(iframe).setStyle({ width:'0px', height:'0px', position:'absolute', display:'none' });
					document.body.appendChild(iframe);
					//start Interval
					this._intervalID = setInterval("hashHistory._checkForHashChange()", this._checkInterval);
				break;
		}
		this._initialized = true;
		if( typeof(hashCallbacks) == 'object' && hashCallbacks.length > 0) {
			this._hashActions = hashCallbacks;
		}
		if(this.stateID) this._dispatchEvent(this.stateID, 'initialize');
	},
	setHash: function(stateID) {
		if(this._debug) alert( "PFHashHistory.setHash(" + stateID+")" );
		switch(this._method) {
			case 'IFRAME': 	frames[this._iframeID].document.open();
				            frames[this._iframeID].document.write('<script>parent.document.location.hash = "' + (stateID == this.defaultStateID ? '' : stateID) + '"; /* Wait for IE to impose its title before setting ours. */ setTimeout( function(){ parent.hashHistory._updateIFrame("' + stateID + '"); }, 0);</script>');
				            frames[this._iframeID].document.close();
				            break;     
			case 'HASH':	document.location.hash = (stateID == this.defaultStateID ? '#' : stateID);
							break;
		}
	},
	setHashAndRedir: function(stateID, newURL, targetWindow) {
		if(this._debug) alert( "PFHashHistory.setHashAndRedir() :Setting Hash to " + stateID + "\nRedirecting to " + newURL + "\nWindow: "+ targetWindow);
		this._oldStateID = stateID;
		this.setHash(stateID);
		if(targetWindow == "_blank") {
			window.open(newURL);
		} else {
			window.location.href = newURL;
		}
	},
	/*
	 * public function addCallback
	 *  @param hash : hash to add a callback for
	 *  @param callback: function which gets called if that hash is navigated to
	 */
	addCallback: function(hash, callback) {
		var hashAction = { 'hash':hash, 'callback':callback };
		this._hashActions.push(hashAction);
	},
	/*
	 * returns current location-hash
	 */
	_getStateID: function() {
		return document.location.href.split('#')[1] || false;
	},
	_dispatchEvent: function(stateID,from) {
		this._oldStateID = stateID;
		var cb = this._hasHashAction(stateID);
		if(cb != false && typeof(cb) == "function") {
			if(this._debug) alert("PFHashHistory._dispatchEvent("+stateID+") from " + from);
			cb(stateID);
		}
	},
	/*
	 * checks URL hash for changes, and dispatches event if so
	 */
	_checkForHashChange: function() {
		var stateID = this._getStateID();
        if (stateID != false && stateID != this._oldStateID) {
            this._oldStateID = stateID;
            this._dispatchEvent(stateID,"_checkforHashChange()")
        }
	},
	/*
	 * called from IFrame in IE, dispatches event 
	 */
	_updateIFrame: function(stateID) {
		if(stateID != this.defaultStateID && stateID != this._oldStateID) {
			this._oldStateID = stateID;
			this._dispatchEvent(stateID,'_updateIFrame()');
		}
	},
	/*
	 * _hasHashAction
	 * checks if a given hash has a callback associated
	 * @param 		the hash 
	 * @returns 	callback function or false
	 */
	_hasHashAction: function(hashToFind) {
		if(this._debug) alert("PFHashHistory._hasHashAction: Checking if there's an action assigned to hash " + hashToFind);
		if(this._hashActions.length) {
			for(var i=0; i < this._hashActions.length; i++) { //non-catch all has preference over catch-alls
				if(this._hashActions[i].hash == hashToFind) { return this._hashActions[i].callback; }
			}
			for(var j=0; j <= this._hashActions.length; j++) { //catch-all
				if(this._hashActions[j].hash == "@all") { return this._hashActions[j].callback; }
			}
		}
		return false;
	}
}

function PF_Hash(param) {
	var matches = param.match(/^([a-z]*).xml-([0-9]{6,7})?-([0-9]{6,7}|0)?-([0-9]{6,7}|0)?$/);
	if( matches && matches.length ) {
		pfcont.loadDeeplink( new Array(matches[1], matches[2], (matches[3]?matches[3]:0), (matches[4]?matches[4]:0)) );
	}
}

/************************************************************************/

//its wird but hashHistory needs onDOMReady and won't work with dom:loaded
Object.extend(Event, {
  _domReady : function() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;
    if (this._timer)  clearInterval(this._timer);
    this._readyCallbacks.each(function(f) { f() });
    this._readyCallbacks = null;
},
  onDOMReady : function(f) {
    if (!this._readyCallbacks) {
      var domReady = this._domReady.bind(this);
      if (document.addEventListener)
        document.addEventListener("DOMContentLoaded", domReady, false);
        /*@cc_on @*/
        /*@if (@_win32)

            document.write("<script id=__ie_onload defer src=//:><\/script>");

            document.getElementById("__ie_onload").onreadystatechange = function() {

                if (this.readyState == "complete") domReady();

            };
        /*@end @*/
        if (/WebKit/i.test(navigator.userAgent)) {
          this._timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) domReady();
          }, 10);
        }
        Event.observe(window, "load", domReady);
        Event._readyCallbacks =  [];
    }
    Event._readyCallbacks.push(f);
  }
});

var tabbedPanels;
var pfcont;
var pfflash;
var flashController;
var hashHistory; //added 20.11. by C.Wellhoefer
//document.observe("dom:loaded",function() {
//Event.onDOMReady(function() {
document.observe("dom:loaded", function() {
	var isFlash = deconcept.SWFObjectUtil.getPlayerVersion()['major'];
	if(isFlash > 0)
	{
		flashController = new FlashController();
		pfflash = new PFFlash(PFT_LANGID,PFT_CONFIG);
	
		if($('tabbrandnames'))
		{
			new PFSearchCompleter();
		}
	
		pfcont = new PFController(PFT_SITEID,PFT_LANGID);
		EventHelper.getInstance('tablistframe');
		//setTimeout('pfReadyAfterLoad()',500); <- moved to PFController
		tabbedPanels = new Spry.Widget.TabbedPanels('tablistframe', { defaultTab: 0 });
	}

	//hashHistory = new PFhashHistory( [ {'hash':'@all', 'callback':PF_Hash} ] );

});

function pfReadyAfterLoad() {
    var selectedTab = getPreselectedPFTab();
    tabbedPanels.showPanel(selectedTab);
	hashHistory = new PFhashHistory( [ {'hash':'@all', 'callback':PF_Hash} ] );
}

/******************* WonderLoop **********************/
function wLoop(cluster) {
    if($('wLoopContainer')) {
    } else {
        new Insertion.Before('footer-position-placeholder', '<div id="wLoopContainer"></div>');
    }
    var wl_ord      = new Date().getTime(); 
    var wl_protocol = location.protocol.indexOf('https')>-1?'https':'http'; 
    
    $('wLoopContainer').update(); //Clear Container
    
    if(cluster == 'industry')
    {
         var wl_image1 = new Element('img', {'height':'0', 'width':'0', 'style':'display:none', 'src':wl_protocol+'://tu.connect.wunderloop.net/TU/1070/3328/12152/?ord=' + wl_ord });
         var wl_image2 = new Element('img', {'height':'0', 'width':'0', 'style':'display:none', 'src':wl_protocol+'://req.connect.wunderloop.net/RQ/1070/3328/4811/if?ord=12345&amp;EAS=cu=4811;ty=pc'});
         $('wLoopContainer').appendChild(wl_image1);
         $('wLoopContainer').appendChild(wl_image2);
    }
    else if (cluster == 'energy')
    {
         var wl_image1 = new Element('img', {'height':'0', 'width':'0', 'style':'display:none', 'src':wl_protocol+'://tu.connect.wunderloop.net/TU/1070/3328/12153/?ord=' + wl_ord });
         var wl_image2 = new Element('img', {'height':'0', 'width':'0', 'style':'display:none', 'src':wl_protocol+'://req.connect.wunderloop.net/RQ/1070/3328/4810/if?ord=12345&amp;EAS=cu=4810;ty=pc'});
         $('wLoopContainer').appendChild(wl_image1);
         $('wLoopContainer').appendChild(wl_image2);
    } 
    else if (cluster == 'healthcare')
    {
         var wl_image1 = new Element('img', {'height':'0', 'width':'0', 'style':'display:none', 'src':wl_protocol+'://tu.connect.wunderloop.net/TU/1070/3328/12154/?ord=' + wl_ord });
         var wl_image2 = new Element('img', {'height':'0', 'width':'0', 'style':'display:none', 'src':wl_protocol+'://req.connect.wunderloop.net/RQ/1070/3328/4809/if?ord=12345&amp;EAS=cu=4809;ty=pc'});        
         $('wLoopContainer').appendChild(wl_image1);
         $('wLoopContainer').appendChild(wl_image2);
    }   

}
/***************** End WonderLoop********************/