var langLayer;
var bEnableDynamicSearch = true;

window.addEvent('domready', function()
{	
  if ($("dealersearch")) {
	  $("dealersearch").getElements("input").each(function(el) {
		  setupInputListener(el, "blur");
	  });
	  
	  $("dealersearch").getElements("select").each(function(el) {
		  setupInputListener(el, "change");
	  });
  }
  
  function setupInputListener(el, myEvent)
  {
	 el.addEvent(myEvent, function(e) {
		 var sSuffix = getIdentifierSuffix(this);
		 var bError = false;
		 if(sSuffix == "from" || sSuffix == "to") {
			 var aIdentifier = getIdentifierArray(this);
			 	 aIdentifier.pop();
			 var sIdentifier = aIdentifier.join('_');
			 var from = document.getElementById(sIdentifier + '_from');
			 var to = document.getElementById(sIdentifier + '_to');
		    
			 if (from != undefined && to != undefined) {
				 from.removeClass('serror');
				 to.removeClass('serror');
				 if (checkNumeric(from) == false || checkNumeric(to) == false) {
					 from.addClass('serror');
					 to.addClass('serror');	
					 bError = true;
				 } else{
					 if (isValid(from) && isValid(to)) {
						 var fFrom = parseFloat(from.value);
						 var fTo = parseFloat(to.value);
						 if ((fFrom > fTo) && fTo != -1) {
							 from.addClass('serror');
							 to.addClass('serror'); 
							 bError = true;
						 }
					 }
				 }
			 }
		 }
		 if (bError == false && bEnableDynamicSearch == true) {
			 bEnableDynamicSearch = false;
			 window.setTimeout("enableDynamicSearch()", 500);
			 tx_bftrucksajaxSearch(xajax.getFormValues('dealersearch'));
		 }
	 });
  }
  
  function getIdentifierArray(el)
  {
	  if (el.id == undefined) {
		return new Array();
	  }
	  return el.id.split("_");
  }
  
  function getIdentifierSuffix(el)
  {
	  var aIdentifier = getIdentifierArray(el);
	  return aIdentifier[aIdentifier.length-1];	  
  }  
  
  function isValid(el) 
  {
	 if (el.value != el.title && el.value != '') {
		 return true;
	 }
	 return false;
  }
  
  function checkNumeric(el)
  {
	  if (isValid(el) && el.hasClass("numeric")) {
		  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
		  if (objRegExp.test(el.value) == false) {
			  return false;
		  }
		  return true;
	  }
	  return true;
  }
  
	/* Find all elements in the DOM with a class of .slide
  	they hold the content to show or hide. 
  	$$('.sliders') returns an Array of found elements
	*/
	var sliders = $$(".slider");
	/* Find all elements with a class of slide_trigger
	  they will capture the click event.
	*/  
	  
	/* For each instance of .slide_trigger triggers (note the anonymous function)*/ 
	$$(".slide-trigger").each(function(trigger, x) {
		var sl = new Fx.Slide(sliders[x], { 
                //duration: 1000,
                //transition: Fx.Transitions.Back.easeOut,
                //duration: 200,
                //transition: Fx.Transitions.linear,
                onComplete: function(){
					if (this.bg) {
						resetClassName(this.bg, '-small|-hover');		
						if (this.open) {
							this.bg.className += '-small-hover';
						}
					} 
					           	
					if (this.bottom) {
						this.bottom.setStyle('display', 'none');
						if (!this.open) {
							this.bottom.setStyle('display', 'block');
						}				
					}
					
					if (this.icon) {
						resetClassName(this.icon, 'plus-|minus-');
						var sPrefix = (sl.open) ? 'plus' : 'minus';
						this.icon.className = sPrefix + '-' + this.icon.className;
					}
					
					if (this.id == 'extrasearch') {
						var aTxt = $(this.id).rev.split('|');
						$(this.id).innerHTML = (this.open) ? aTxt[1] : aTxt[0];		
					}
					
					if (this.id == 'teaser-notice') {
						if (this.open) {
							Cookie.set('teaser-notice', 'closed',{path:"/"});
						} else {
							Cookie.set('teaser-notice', 'opened',{path:"/"});
						}
					}	
					
                },
                onStart: function(){
					if (this.bottom) {
						this.bottom.setStyle('display', 'block');			
					}
					
					if (this.bg) {	
						if (!this.open) {
							resetClassName(this.bg, '-small|-hover');
						}
					} 					
                }              
		});	/* Instantiate a new slider effect on the matching .slide element */
				
		
		var wrap = trigger.getParent();
		if (wrap.id == trigger.id + '-wrap') {
			sl.bg = wrap;
			trigger.bg = wrap;			
		}
		if (trigger.id) {
			sl.icon = trigger.icon = $(trigger.id + '-icon');
					
		}	
		var bottom = sl.bottom = $(trigger.id + '-bottom');
		
		sl.id = trigger.id;
		
		trigger.addEvents
		({	
			'click': function(e) {		
				e = new Event(e);			  /* the event */
				sl.toggle();				  /* Toggle the slider condition */
				
				// Use an empty height instead of auto because otherwise the slider will not open/close correctly
				var sliderWrap = checkParent(trigger);			
					sliderWrap.setStyle('height', '');				
	
				e.stop(); 				  /* Stop the event from bubbling */
			},
				
			'mouseenter': function() {
				this.style.cursor='pointer';
				if (this.icon) {
					resetClassName(this.icon, '-hover');
					this.icon.className += '-hover';
				}
				if (this.bg && !sl.open) {
					resetClassName(this.bg, '-hover');
					this.bg.className += '-hover';
				}
			},	
		
			'mouseleave': function() {
				if (this.icon) {
					resetClassName(this.icon, '-hover');
				}
				if (this.bg) {
					resetClassName(this.bg, '-hover');
				}			
			},
		
			'openElement': function(e) {
				sl.slideIn();
			},
			
			'resizeElement': function(e) {
				sl.open = false;
				sl.slideIn();
			}
		});
					
		if (trigger.getProperty('rel') == 'dontcollapse') {
			sl.open = false;
			sl.slideIn();
		} else {
			sl.hide();			  /* Hide the slider */		
			sliders[x].setStyle('display', 'block');				  
			if (bottom) {
				bottom.setStyle('display', 'none');
			}			
		}
		
		if (trigger.id == 'teaser-notice' && Cookie.get('teaser-notice') == 'opened') {
			sl.open = false;
			sl.slideIn();			
		}
		
	});	// end of triggers.each
	
	
	
	function checkParent(elem)
	{
		var par = elem.getParent();
		if (par) {
			if (par.hasClass('slider') || par.hasClass('wholediv')) { // par.hasClass('wholediv') als abbruchkriterium
				return par.getParent();
			} else {
				return checkParent(par);
			}
		} else {
			return elem;
		}
	}
	
	function resetClassName(elem, reg)
	{
		var sClassName = elem.className;
		elem.className = sClassName.replace(new RegExp(reg,"g"),"");		
	}
	
	$(document.body).addEvent('keyup', function(event){
		if (event.target) {
			if (event.target.tagName.toLowerCase() == 'input' && event.target.type.toLowerCase() == 'text') {
				if (event && event.keyCode == 13 && document.searchform) {
					document.searchform.submit();
				}		
			}
		}
	});
	
	/* setup tooltips input */
	/*
	$$(".textinput").each(function(myinput) {
		myinput.mytitle = myinput.getAttribute('title');
		myinput.addEvents
		({	
			'mouseover': function() {
				new Tips('test', {maxOpacity: 0.9, className: 'tooltip-input'});
			}	
		});		
	});
	*/
	/*
	var as = [];
	$$(".textinput").each(function(a){
		if (a.getAttribute('title')) as.push(a);
	});
	new Tips(as, {maxOpacity: 0.9, className: 'tooltip-input'});
	*/
	
	/* setup tooltips */
	var as = [];
	$$(".tooltip-trigger").each(function(a){
		if (a.getAttribute('title')) as.push(a);
	});
	new Tips(as, {maxOpacity: 0.9});
	    
    $$(".textinput").each(function(myinput) 
	{
		myinput.mytitle = myinput.getAttribute('title');
		myinput.addEvents
		({	
			'focus': function() {
                if(this.value == this.mytitle) this.value = '';
			},		
			'blur': function() {
				if(this.value == this.mytitle || this.value == '') this.value = this.mytitle;
			}
		})	
	});	
	
	
	$$(".result-row").each(function(myrow) 
	{
		myrow.addEvents
		({	
			'mouseover': function() {
				this.addClass('result-row-hover');
			},	
		
			'mouseout': function() {
				this.removeClass('result-row-hover');		
			}
		})	
	});	
	
	$$(".white-button").each(function(mybutton) 
	{
		mybutton.addEvents
		({	
			'mouseover': function() {
				this.addClass('white-button-hover');
			},	
		
			'mouseout': function() {
				this.removeClass('white-button-hover');		
			}
		})	
	});		
	
	$$(".comparelist").each(function(mybutton) 
	{
		mybutton.addEvents
		({	
			'mouseover': function() {
				this.addClass('highlight');
			},	
		
			'mouseout': function() {
				this.removeClass('highlight');		
			}
		})	
	});	
	
	var printTemplate = $$('body').hasClass('print');
	if (printTemplate[0] == true) {
		setTimeout("showPrintDialog();", 500);
	}
	
});


function showPrintDialog()
{
	if (window.print) {
		window.print();
	}
}


function openElement(elem)
{
	elem.fireEvent('openElement');
}

function resizeElement(elem)
{
	elem.fireEvent('resizeElement');
}


function disableCompareButtons()
{
	$$(".button3-compare-s").each(function(button, x) {
		button.addClass('button3-compare-s-d');
	});
}

function enableCompareButtons()
{
	$$(".button3-compare-s").each(function(button, x) {
		button.removeClass('button3-compare-s-d');
	});
}

function closeLayer(sLayer)
{
	document.getElementById(sLayer).style.display='none';
}

function switchLeftborder(modus)
{      
	switch (modus) { 
		case 1:   
			document.getElementById('mainnavi_leftborder').src= "fileadmin/img/bg_mainnavi_leftborder_h.gif";       
			break;      
		case 2:
			document.getElementById('mainnavi_leftborder').src= "fileadmin/img/bg_mainnavi_leftborder.gif";        
			break;
	}
}

// check the searchform for valid inputs
function checkSearchForm(input, std_val, mode)
{
  switch (mode) {
  	case 'clear':
		if(input.value == std_val) input.value = '';
	  	break;
	case 'fill':
	  	if(input.value == std_val || input.value == '') input.value = std_val;
	  	break;
  }  
}


function enableDynamicSearch() {
	  bEnableDynamicSearch = true;
}


// ie6 select-list bugfix for mootools tips class
var Tips = new Class({
 
	getOptions: function(){
		return {
			onShow: function(tip){
				tip.setStyle('visibility', 'visible');
			},
			onHide: function(tip){
				tip.setStyle('visibility', 'hidden');
			},
			maxTitleChars: 30,
			showDelay: 100,
			hideDelay: 100,
			className: 'tool',
			offsets: {'x': 16, 'y': 16},
			fixed: false
		};
	},
 
	initialize: function(elements, options){
		// this checks for IE 5 and 6, then adds an iframe to the document to act as a shim 
		if (/MSIE (5.5|6.)/.test(navigator.userAgent)) { 
			if(!$('DivShim')){ 
				var divShimProperties = {
					'id': "DivShim", 
					'src': "",
					'scrolling': "no",
					'frameborder': 0
				}; 
				var divShimStyles = {
					'position': "absolute",
					'top': "0px",
					'left': "0px",
					'display': "none", 
					'font-size': "6px", 
					'padding': "0px"				
				}; 
				var divShim = new Element('iframe').setProperties(divShimProperties).setStyles(divShimStyles);
				divShim.injectInside(document.body); 
			} 
		} 

		this.setOptions(this.getOptions(), options);
		this.toolTip = new Element('div').addClass(this.options.className+'-tip').setStyles({
			'position': 'absolute',
			'top': '0',
			'left': '0',
			'visibility': 'hidden'
		}).injectInside(document.body);
		this.wrapper = new Element('div').injectInside(this.toolTip);
		$each(elements, function(el){
			this.build($(el));
		}, this);
		if (this.options.initialize) this.options.initialize.call(this);
	},
 
	build: function(el){
		el.myTitle = el.href ? el.href.replace('http://', '') : (el.rel || false);
		if (el.title){
			var dual = el.title.split('::');
			if (dual.length > 1) {
				el.myTitle = dual[0].trim();
				el.myText = dual[1].trim();
			} else {
				el.myText = el.title;
			}
			el.removeAttribute('title');
		} else {
			el.myText = false;
		}
		if (el.myTitle && el.myTitle.length > this.options.maxTitleChars) el.myTitle = el.myTitle.substr(0, this.options.maxTitleChars - 1) + "&hellip;";
		el.addEvent('mouseover', function(event){
			this.start(el);
			this.locate(event);
		}.bindWithEvent(this));
		if (!this.options.fixed) el.addEvent('mousemove', this.locate.bindWithEvent(this));
		el.addEvent('mouseout', this.end.bindWithEvent(this));
	},
 
	start: function(el){
		this.wrapper.setHTML('');
		if (el.myTitle){
			new Element('span').injectInside(
				new Element('div').addClass(this.options.className+'-title').injectInside(this.wrapper)
			).setHTML(el.myTitle);
		}
		if (el.myText){
			new Element('span').injectInside(
				new Element('div').addClass(this.options.className+'-text').injectInside(this.wrapper)
			).setHTML(el.myText);
		}
		$clear(this.timer);
		this.timer = this.show.delay(this.options.showDelay, this);
	},
 
	end: function(event){
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.hideDelay, this);
		event.stop();
	},
 
	locate: function(event){
		var win = {'x': window.getWidth(), 'y': window.getHeight()};
		var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
		var tip = {'x': this.toolTip.offsetWidth, 'y': this.toolTip.offsetHeight};
		var prop = {'x': 'left', 'y': 'top'};
		for (var z in prop){
			var pos = event.page[z] + this.options.offsets[z];
			if ((pos + tip[z] - scroll[z]) > win[z]) pos = event.page[z] - this.options.offsets[z] - tip[z];
			this.toolTip.setStyle(prop[z], pos + 'px');
		};
 
		this.toolTip.setStyle('z-index', 1000);
 
		// added the zindex here 
		// make sure the iframe moves with our tooltip
		if (/MSIE (5.5|6.)/.test(navigator.userAgent)) { 
			$('DivShim').setStyle('z-index', 999);
			for (var z in prop) {
				var pos = event.page[z] + this.options.offsets[z];
				if ((pos + tip[z] - scroll[z]) > win[z]) {
					pos = event.page[z] - this.options.offsets[z] - tip[z];
				}
				$('DivShim').setStyle(prop[z], pos + 'px');
			}
		} 
		event.stop();
	},
 
	show: function(){
		if (/MSIE (5.5|6.)/.test(navigator.userAgent)) { 
			var IfrRef = $('DivShim'); 
			var myValues = this.toolTip.getCoordinates();
 
			IfrRef.style.width = myValues['width'] + "px";
			IfrRef.style.height = myValues['height'] + "px";
			IfrRef.style.display = "block";
		} 
		this.fireEvent('onShow', [this.toolTip]);
	},
 
	hide: function(){
		if (/MSIE (5.5|6.)/.test(navigator.userAgent)) { 
			var IfrRef = $('DivShim'); 
			IfrRef.style.display = "none"; 
		} 
		this.fireEvent('onHide', [this.toolTip]);
	}
 
});
 
Tips.implement(new Events);
Tips.implement(new Options);
