/* funkcjonalność usuwania niepotrzebnych pustych znaków */
function trim(str, chars) {	var strr = new String(str); return ltrim(rtrim(strr, chars), chars); }
function ltrim(str, chars) { chars = chars || "\\s"; return str.replace(new RegExp("^[" + chars + "]+", "g"), ""); }
function rtrim(str, chars) { chars = chars || "\\s"; return str.replace(new RegExp("[" + chars + "]+$", "g"), ""); }

/* funkcjonalność podmieniania i zczytywania hashu adresu url */
function getHash() { var hash = ''; if(String(window.location).split('#').length == 2) hash = String(window.location).split('#')[1]; return hash; }
function setHash(hashStr) { if(String(window.location).split('#').length == 2) { window.location = String(window.location).split('#')[0]+'#'+hashStr; }	else { window.location = String(window.location)+'#'+hashStr; }	}

//scroll
var ScrollBar = new Class({

		Implements: [Events, Options],

		options: {
			maxThumbSize: 15,
			wheel: 8,
			arrows: true,
			hScroll: true // horizontal scrollbars
		},

		initialize: function(textv, options){
			this.setOptions(options);
			this.content = new Element('div', {'class':'scroller_content'}).injectBefore(textv);
			textv.injectInside(this.content);
			this.main = new Element('div', {'class':'scroller_main'}).injectBefore(this.content);
			this.content.injectInside(this.main);
			var w = parseInt(textv.getStyle('width'));
			this.main.setStyles({
					width: w-30,
					height: textv.getStyle('height'),
					"position":"relative",
					'float':'left',
					'display': 'inline',
					'margin-left':textv.getStyle('margin-left') });
			this.content.setStyles({ 
					width: w-30,
					height: textv.getStyle('height'),
					'overflow': 'hidden',
					'float':'left',
					'display': 'inline',
					"position":"relative"
			 });
			textv.setStyles({height:'','margin-left':0, 'width': w-30});
					
			if (this.options.arrows == true){
				this.arrowOffset = 90;
			} else {
				this.arrowOffset = 0;
			}
			
			if (this.options.hScroll == true){
				this.hScrollOffset = 15;
			} else {
				this.hScrollOffset = 0;
			}				

			this.vScrollbar = new Element('div', {
    				'class': 'vScrollbar'
				}).injectAfter(this.content);
			this.vScrollbar.setStyles({'float': 'left',	'margin-left':10});				

			if (this.options.arrows == true){	
				this.arrowBegin = new Element('div', {
    					'class': 'arrowBegin'
					}).injectInside(this.vScrollbar);	
				this.arrowTop = new Element('div', {
    					'class': 'arrowTop'
					}).injectInside(this.vScrollbar);
				this.arrowUp = new Element('div', {
    					'class': 'arrowUp'
					}).injectInside(this.vScrollbar);
			}	

			this.vTrack = new Element('div', {
    				'class': 'vTrack'
				}).injectInside(this.vScrollbar);
			this.vTrack.setStyles({'height':380});
				
			this.vThumb = new Element('div', {
    				'class': 'vThumb'
				}).injectInside(this.vTrack);

			if (this.options.arrows == true){				
				this.arrowDown = new Element('div', {
    					'class': 'arrowDown'
					}).injectInside(this.vScrollbar);
								
				this.arrowBottom = new Element('div', {
    					'class': 'arrowBottom'
					}).injectInside(this.vScrollbar);
				this.arrowEnd = new Element('div', {
    					'class': 'arrowEnd'
					}).injectInside(this.vScrollbar);	
			}		
			
			this.hScrollbar = new Element('div', {
    				'class': 'hScrollbar'
				}).injectAfter(this.vScrollbar);
			this.hScrollbar.setStyles({'clear': 'both'});
			
			if (this.options.arrows == true){							
				this.arrowLeft = new Element('div', {
    					'class': 'arrowLeft'
					}).injectInside(this.hScrollbar);
			}

			this.hTrack = new Element('div', {
    				'class': 'hTrack'
				}).injectInside(this.hScrollbar);
			this.hTrack.setStyles({'width':300});
			
			this.hThumb = new Element('div', {
    				'class': 'hThumb'
				}).injectInside(this.hTrack);							
	
			if (this.options.arrows == true){
				this.arrowRight = new Element('div', {
    					'class': 'arrowRight'
					}).injectInside(this.hScrollbar);
			}											

			this.corner = new Element('div', {
    				'class': 'corner'
				}).injectAfter(this.hScrollbar);
			
			this.bound = {
				'vStart': this.vStart.bind(this),
				'hStart': this.hStart.bind(this),				
				'end': this.end.bind(this),
				'vDrag': this.vDrag.bind(this),
				'hDrag': this.hDrag.bind(this),				
				'wheel': this.wheel.bind(this),
				'vPage': this.vPage.bind(this),
				'hPage': this.hPage.bind(this)				
			};

			this.vPosition = {};
			this.hPosition = {};			
			this.vMouse = {};
			this.hMouse = {};			
			this.update();
			this.attach();
			this.zero();
		},

		zero: function() {
			this.content.scrollTop = 0;
			this.vUpdateThumbFromContentScroll();
		},
		
		update: function(){
			textv = this.content.getElement('div') || this.content.getElement('ul');
			
			this.main.setStyle('height', this.content.offsetHeight + this.hScrollOffset);
			this.vTrack.setStyle('height', this.content.offsetHeight - this.arrowOffset);
						
			this.main.setStyle('width', this.content.offsetWidth + ((textv.offsetWidth != this.content.offsetWidth - 30)?30:0));
			this.hTrack.setStyle('width', this.content.offsetWidth - this.arrowOffset);
			
			// Remove and replace vertical scrollbar			
			if (this.content.scrollHeight <= this.main.offsetHeight) {
				this.vScrollbar.setStyle('display', 'none');
				if (this.options.hScroll == true){				
					this.hTrack.setStyle('width', this.hTrack.offsetWidth + 30);
				}	
				this.content.setStyle('width', this.content.offsetWidth + 30);
			} else {
				this.vScrollbar.setStyle('display', 'block');
			}
			
			/* poprawka dla scrollerów dokładanych i update'owanych przez ajax'a */
			if(textv.offsetWidth != this.content.offsetWidth)
				this.content.setStyle('width', textv.offsetWidth);
			/* koniec poprawki */
			
			
			if (this.options.hScroll == true){			
			
				// Remove and replace horizontal scrollbar
				if (this.content.scrollWidth <= this.main.offsetWidth) {
					this.hScrollbar.setStyle('display', 'none');
					this.vTrack.setStyle('height', this.vTrack.offsetHeight + this.hScrollOffset);				
					this.content.setStyle('height', this.content.offsetHeight + this.hScrollOffset);	
				} else {
					this.hScrollbar.setStyle('display', 'block');			
				}
			
				// Remove and replace bottom right corner spacer			
				if (this.content.scrollHeight <= this.main.offsetHeight || this.content.scrollWidth <= this.main.offsetWidth) {
					this.corner.setStyle('display', 'none');				
				} else {
					this.corner.setStyle('display', 'block');			
				}		
			
				// Horizontal

				this.hContentSize = this.content.offsetWidth;
				this.hContentScrollSize = this.content.scrollWidth;
				this.hTrackSize = this.hTrack.offsetWidth;

				this.hContentRatio = this.hContentSize / this.hContentScrollSize;
				this.hThumbSize = (this.hTrackSize * this.hContentRatio).limit(this.options.maxThumbSize, this.hTrackSize);
				this.hScrollRatio = this.hContentScrollSize / this.hTrackSize;
				this.hThumb.setStyle('width', this.hThumbSize);

				this.hUpdateThumbFromContentScroll();
				this.hUpdateContentFromThumbPosition();			

			} else {
					this.hScrollbar.setStyle('display', 'none');
					this.corner.setStyle('display', 'none');										
			}
			

			// Vertical
			
			this.vContentSize = this.content.offsetHeight;
			this.vContentScrollSize = this.content.scrollHeight;
			this.vTrackSize = this.vTrack.offsetHeight;

			this.vContentRatio = this.vContentSize / this.vContentScrollSize;
			this.vThumbSize = (this.vTrackSize * this.vContentRatio).limit(this.options.maxThumbSize, this.vTrackSize);
			this.vScrollRatio = this.vContentScrollSize / this.vTrackSize;
			this.vThumb.setStyle('height', this.vThumbSize);

			this.vUpdateThumbFromContentScroll();
			this.vUpdateContentFromThumbPosition();
			
		},

		vUpdateContentFromThumbPosition: function(){
			this.content.scrollTop = this.vPosition.now * this.vScrollRatio;
		},
		
		hUpdateContentFromThumbPosition: function(){
			this.content.scrollLeft = this.hPosition.now * this.hScrollRatio;
		},		

		vUpdateThumbFromContentScroll: function(){
			this.vPosition.now = (this.content.scrollTop / this.vScrollRatio).limit(0, (this.vTrackSize - this.vThumbSize));
			this.vThumb.setStyle('top', this.vPosition.now);
		},
		
		hUpdateThumbFromContentScroll: function(){
			this.hPosition.now = (this.content.scrollLeft / this.hScrollRatio).limit(0, (this.hTrackSize - this.hThumbSize));
			this.hThumb.setStyle('left', this.hPosition.now);
		},		

		attach: function(){
			this.vThumb.addEvent('mousedown', this.bound.vStart);
			
			if (this.options.wheel) this.content.addEvent('mousewheel', this.bound.wheel);
			//this.vTrack.addEvent('mouseup', this.bound.vPage);
			this.arrowBottom.addEvent('mouseup', this.bound.vPage);
			this.arrowTop.addEvent('mouseup', this.bound.vPage);
			
			this.hThumb.addEvent('mousedown', this.bound.hStart);
			this.hTrack.addEvent('mouseup', this.bound.hPage);			
			
			if (this.options.arrows == true){
				this.arrowUp.addEvent('mousedown', function(event){
						this.interval = (function(event){
						this.content.scrollTop -= this.options.wheel;
						this.vUpdateThumbFromContentScroll();
					}.bind(this).periodical(40))
				}.bind(this));
			
				this.arrowUp.addEvent('mouseup', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowUp.addEvent('mouseout', function(event){
					$clear(this.interval);
				}.bind(this));
						
				this.arrowDown.addEvent('mousedown', function(event){
						this.interval = (function(event){
						this.content.scrollTop += this.options.wheel;
						this.vUpdateThumbFromContentScroll();
					}.bind(this).periodical(40))
				}.bind(this));
			
				this.arrowDown.addEvent('mouseup', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowDown.addEvent('mouseout', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowLeft.addEvent('mousedown', function(event){
						this.interval = (function(event){
						this.content.scrollLeft -= this.options.wheel;
						this.hUpdateThumbFromContentScroll();
					}.bind(this).periodical(40))
				}.bind(this));
			
				this.arrowLeft.addEvent('mouseup', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowLeft.addEvent('mouseout', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowRight.addEvent('mousedown', function(event){
						this.interval = (function(event){
						this.content.scrollLeft += this.options.wheel;
						this.hUpdateThumbFromContentScroll();
					}.bind(this).periodical(40))
				}.bind(this));
			
				this.arrowRight.addEvent('mouseup', function(event){
					$clear(this.interval);
				}.bind(this));
			
				this.arrowRight.addEvent('mouseout', function(event){
					$clear(this.interval);
				}.bind(this));
			}			
						
		},
		
		wheel: function(event){
			this.content.scrollTop -= event.wheel * this.options.wheel;
			this.vUpdateThumbFromContentScroll();
			event.stop();
		},

		vPage: function(event){
			if (event.page.y > this.vThumb.getPosition().y) this.content.scrollTop += this.content.offsetHeight;
			else this.content.scrollTop -= this.content.offsetHeight;
			this.vUpdateThumbFromContentScroll();
			event.stop();
		},
		
		hPage: function(event){
			if (event.page.x > this.hThumb.getPosition().x) this.content.scrollLeft += this.content.offsetWidth;
			else this.content.scrollLeft -= this.content.offsetWidth;
			this.hUpdateThumbFromContentScroll();
			event.stop();
		},		

		vStart: function(event){
			this.vMouse.start = event.page.y;
			this.vPosition.start = this.vThumb.getStyle('top').toInt();
			document.addEvent('mousemove', this.bound.vDrag);
			document.addEvent('mouseup', this.bound.end);
			this.vThumb.addEvent('mouseup', this.bound.end);
			event.stop();
		},
		
		hStart: function(event){
			this.hMouse.start = event.page.x;		
			this.hPosition.start = this.hThumb.getStyle('left').toInt();
			document.addEvent('mousemove', this.bound.hDrag);
			document.addEvent('mouseup', this.bound.end);
			this.hThumb.addEvent('mouseup', this.bound.end);
			event.stop();
		},		

		end: function(event){
			document.removeEvent('mousemove', this.bound.vDrag);
			document.removeEvent('mousemove', this.bound.hDrag);			
			document.removeEvent('mouseup', this.bound.end);
			this.vThumb.removeEvent('mouseup', this.bound.end);
			this.hThumb.removeEvent('mouseup', this.bound.end);			
			event.stop();
		},

		vDrag: function(event){
			this.vMouse.now = event.page.y;
			this.vPosition.now = (this.vPosition.start + (this.vMouse.now - this.vMouse.start)).limit(0, (this.vTrackSize - this.vThumbSize));
			this.vUpdateContentFromThumbPosition();
			this.vUpdateThumbFromContentScroll();
			event.stop();
		},
		
		hDrag: function(event){
			this.hMouse.now = event.page.x;
			this.hPosition.now = (this.hPosition.start + (this.hMouse.now - this.hMouse.start)).limit(0, (this.hTrackSize - this.hThumbSize));
			this.hUpdateContentFromThumbPosition();
			this.hUpdateThumbFromContentScroll();
			event.stop();
		}		

	});

//przegladarka zdjec	
var imgs = new Array();	

function closeDiv(c) {
	var wrapperdiv = c.getParent().getParent();
	c.getParent().getParent().getParent().setStyle('display','none');
	c.getParent().getParent().getParent().getParent().setStyle('display','none');
}

function nextImage(c) {	
	var bigImgWrapper = c.getParent().getParent().getParent();
	bigImgWrapper.setStyle('display','none');
	currentIndex = imgs.indexOf(bigImgWrapper.id);
	if (currentIndex<(imgs.length-1)) {
		newIndex = currentIndex+1;
	} else {
		newIndex = 0;
	}
	var bigImgId = imgs[newIndex];
	$(bigImgId).setStyle('display','block');
}

function previousImage(c) {
	var bigImgWrapper = c.getParent().getParent().getParent();
	bigImgWrapper.setStyle('display','none');
	currentIndex = imgs.indexOf(bigImgWrapper.id);
	if (currentIndex>0) {
		newIndex = currentIndex-1;
	} else {
		newIndex = imgs.length-1;
	}
	var bigImgId = imgs[newIndex];
	$(bigImgId).setStyle('display','block');
}

function download(c) {
	var option = (c.id.match("wrap_4"))?true:false;
	var bigImgWrapper = c.getParent().getParent().getParent();
	var imgToDownload = (option) ? bigImgWrapper.getElement('img').src : bigImgWrapper.getElement('img').src.replace('preview', '1024x768');
  	win = window.open(imgToDownload, 'newImage', "resizable=no,scrollbars=yes,status=no");
	// self.location.href=imgToDownload;
}

/* obsługa scrollerów */
function addScrollers(context) {
	
	var i;
	if(document.scr) {
		i = document.scr.length;
	}
	else {
		document.scr = new Array();
		i = 0;
	}
	
	var prefix = '';
	if(context != 'document') {
		prefix = context;
	}
	$$(prefix+'.scroll').each(function(textv){
		
		var height = 0;
	
		textv.getChildren().each(function (el) {
			if(el.getTag()=='ul') {
				if(el.offsetHeight == 0) {
					el.getChildren().each(function(li) {
						if(li.hasClass('gallery') || $$('#infoNoneTopNews').length > 0) {
							if(li.getSize().size) height += parseInt(li.getSize().size.y);
							else height += li.getSize().y;
						}
					});
					if($$('#infoNoneTopNews').length == 0) 
						height = parseInt(height/3);
				}
				else {
					height += el.offsetHeight;
				}
			}
			else {
				if(el.getSize().size) height += parseInt(el.getSize().size.y);
				else height += el.getSize().y;
			}
		});
		
		var b = parseInt(textv.getStyle('height').slice(0,-2))+12;
		
		// window.status += textv.id+': '+ height+' '+b+ ' | ';
		
		if(height > b) {
			textv.setStyle('display', 'block');
			textv.setStyle('overflow', 'visible');
			document.scr[i] = new ScrollBar(textv, {'hScroll': false});
			i += 1;
		}
	});
}

function updateScrollers () {
	for(i in document.scr) {
		try {
			if(typeof document.scr[i] == 'object') {
				document.scr[i].update();
			}
		}
		catch(exception) {}
	}
}

function zeroScroller(which) {
	for(i in document.scr) {
		try {
			if(typeof document.scr[i] == 'object' && document.scr[i].content.getElement('div').getAttribute('id') == which) {
				document.scr[i].zero();
			}
		}
		catch(exception) {}
	}
}
/* koniec obsługi scrollerów */

/* usunięcie pustych, nie walidujących się elementów */
function trimEmptyElements() {
	/* puste elementy tekstowe, link */
	$$('h2, h3, p').each(function(el) {
		if(trim(el.getText())=='')
			el.remove()
	});
	
	/* puste teasery z linkiem, usługi-porady linki z prawej */
	$$('ul li a, #soundCheck a, #infoMediumTopWideColors dl dd a, #infoNoneTop dl dd a').each(function(el) {
		if(trim(el.getText())=='') {
			/* wyjątek strony głównej - duże boxy */
			if(el.getElements('img').length == 0)
				el.getParent().remove();
		}
	});
	
	/* doświadczenie - motocykle sportowe, downloads */
	$$('ul li em, ul li span, ul li a b').each(function(el) {
		if(trim(el.getText())=='' && !el.hasClass('plus'))
			el.getParent().getParent().remove();
	});
}

/* obsługa przełączania dealerów z mapki */
function showDealer(region) {
	var pool = $$('#boxRight div');
	var div = $(region);

	var toDisplay = new Array();
	if(div!=null && div != undefined) {
		toDisplay = [div.id];
	}
	else {
		switch(region) {
			case 'zachodniopomorskie': toDisplay = ['pomorskie', 'wielkopolskie']; break;
			case 'warminskomazurskie': toDisplay = ['pomorskie','mazowieckie'];	break;
			case 'podlaskie': toDisplay = ['mazowieckie']; break;
			case 'kujawskopomorskie': toDisplay = ['pomorskie', 'wielkopolskie', 'lodzkie', 'mazowieckie'];	break;
			case 'lubuskie': toDisplay = ['wielkopolskie', 'dolnoslaskie']; break;
			case 'opolskie': toDisplay = ['wielkopolskie', 'dolnoslaskie', 'lodzkie', 'slaskie']; break;
			case 'lubelskie': toDisplay = ['mazowieckie']; break;
			case 'swietokrzyskie': toDisplay = ['mazowieckie', 'lodzkie', 'slaskie', 'malopolskie']; break;
			case 'podkarpackie': toDisplay = ['malopolskie']; break;
			case 'all': toDisplay = ['pomorskie', 'wielkopolskie', 'mazowieckie', 'lodzkie', 'dolnoslaskie', 'slaskie', 'malopolskie'];
			default: break;
		}
	}
	
	function inArray(arrayElement, arrayObject) {
		for(a in arrayObject) {
			if(arrayObject[a] ==  arrayElement) return true;
		}
		return false;
	}
	
	pool.each(function(elem) {
		if(inArray(elem.getProperty('id'), toDisplay)) {
			elem.setStyle('display', 'block');
		}
		else {
			if(!elem.hasClass('clear'))
				elem.setStyle('display', 'none');
		}
	});
	
	/* obscrolluj dealerów */
	if(document.scr && document.scr['dealerScroll'] && document.scr['dealerScroll'].update)	document.scr['dealerScroll'].update();
	else document.scr['dealerScroll'] = new ScrollBar($E('#teasers #boxRight.scroll'), {'hScroll': false});
}

window.addEvent('domready', function(){
	/* obsługa głównego menu */
	mainMenu={
		menus: ['subM','subW','subP'],
		create: function(){
			for(var i=0; i<mainMenu.menus.length; i++) {
				x = mainMenu.menus[i];
				var temp = $(x+'H');
				
				temp.dif = $(x);
				temp.dif.link = temp;
				temp.onmouseover = function() {
					this.dif.style.display='block';
					this.className = this.id+'h'
				}
				temp.onmouseout = function(e){
					e=e||event;
					if(!mainMenu.isOver((e.relatedTarget||e.toElement),this.dif.id,this.id)){
						this.dif.style.display='none';
						this.className = '';
					}
					return!1
				}
				temp.dif.onmouseout = function(e){
					e=e||event;
					if(!mainMenu.isOver((e.relatedTarget||e.toElement),this.id+'H',this.id)){
						this.style.display='none'
						this.link.className = '';
					}
				}
			}
		},
		isOver: function(a,id1,id2){
			if(!a) return;
			do {
				if(a.id==id1||a.id==id2)
					return!0;
			} while(a = a.parentNode);
			return!1;
		}
	}
	// mainMenu.create();
	
	/* dodanie window.open dla elementów menu i dla toplayera z linkami */
	$$('#menuBottom a.openNew, #links a.openNew, #infoHome .imgTeasers .openNew, #infoNoneTopNews .openNew, #infoHome a.openNew').each(function(el) {
		el.addEvent('click', function(e) {
			var e = new Event(e); e.stop();
			var newWin = window.open(el.getProperty('href'));
		});
	});
	
	/* obsługa topLayera to linków, imprintu, newslettera */
	$$('#footer a[href*=#links], #footer a[href*=#imprint], #footer a[href*=#newsletter]').each(function(el) {
		var identifier = String(el.getAttribute('href')).split('#')[1];
		el.addEvent('click', function(e) {
			var e = new Event(e); e.stop();
			$$('div#links, div#imprint, div#newsletter').each(function(elm) {
				elm.setStyle('display', 'none');
			});
			$$('div#'+identifier).each(function(elm) {
				elm.setStyle('display', 'block');
			});
		});

		$$('div#'+identifier+' a.close').each(function(el) {
			el.addEvent('click', function(e) {
				var e = new Event(e); e.stop();
				$$('div#'+identifier).each(function(elm) {
					elm.setStyle('display', 'none');
				});
			});
		});
	});
	/* koniec topLayera */
	
	/* obsługa linków zawierających hash (links, imprint, newsletter */
	if(String(window.location).split('#').length == 2) {
		var id = String(window.location).split('#')[1];
		if(id == 'imprint' || id=='links' || id=='newsletter') {
			$$('div#'+id).each(function (el) {
				el.setStyle('display', 'block');
			});
		}
	}
	/* koniec hashowania */
	

	/* IE6 menu hack #1 */
	if(window.ie6) {
		var bg = new Element('div');
		bg.setAttribute('id', 'belkaBgIe');
		bg.injectInside($('belka'));
	}
	
	/* IE6 menu hack #2 - wyłączenie podmenu */
	$$('#submenu div').each(function(el) { el.setStyle('display', 'none') });
	/* koniec obsługi głównego menu */
	
//	/* IE6 header hack, zunifikowany na wszystko - wpisanie SWFObjecta */
//	if($$('#flashHeader').length > 0 && $defined(bottom_so)) {
//		bottom_so.write("flashHeader");
//	}
	
	/* IE6 float hack */
	if(window.ie6) {
		function repairFloat() {
			var winWidth = window.getWidth();
			
			if(winWidth < 1045) {
				$$('html').each(function (el) { el.setStyle('overflow-x', 'scroll')});
				window.scrollTo(1000, 0);
				$$('#content').each(function (el) { el.setStyle('width', 1045)});
				$$('#footer').each(function (el) { el.setStyle('width', 1045)});
			}
			else {
				$$('#content').each(function (el) { el.setStyle('width', '100%')});
				$$('#footer').each(function (el) { el.setStyle('width', '100%')});
				$$('html').each(function (el) { el.setStyle('overflow-x', 'hidden')});
			}
		}
		window.onresize = repairFloat;
		repairFloat();
		repairFloat();
	}
	
  	// FAQ
	var faqlinks = $('faqlist');
	var currentlydisplayedfaq = $('faqitem1');
	var currentlyenlightenedhref;
	
	$$('.faqitem').each(function(item) { 
		var header = $E('h2', item); 
		var linkli = new Element('dd',{'class':''}).injectInside(faqlinks);
		var linktext = new Element('a',{'class':'arrow'}).injectInside(linkli);
		linktext.innerHTML = header.innerHTML;
		if (item != currentlydisplayedfaq) {
			item.setStyle("display","none");
		} else {
			currentlyenlightenedhref = linktext;
			linktext.setProperty('class','arrow selected');
		} 
		linktext.setStyle('cursor','pointer');
		linktext.addEvent('mousedown',function(e) {
			currentlydisplayedfaq.setStyle('display','none');
			currentlyenlightenedhref.setProperty('class','arrow');
			item.setStyle('display','block');
			currentlydisplayedfaq=item;
			linktext.setProperty('class','arrow selected');
			currentlyenlightenedhref = linktext;
		}); 
	});
	// ---
	
	// Downloads
	var downloadList = $('downloadlist');
	var currentlyDisplayedDownload = $('downloadItem1');
	var currentlyEnlightenedHrefDownload;
	
	$$('.downloadItem').each(function(item) { 
		var header1 = $E('h2', item);
		// var header2 = $E('h3', item);
		
		var linkli = new Element('dd',{'class':''}).injectInside(downloadList);
		var linktext = new Element('a',{'class':'arrow'}).injectInside(linkli);
		linktext.innerHTML = header1.innerHTML;
		// linktext.innerHTML = header1.innerHTML + header2.innerHTML;
		
		if (item!=currentlyDisplayedDownload) {
			item.setStyle("display","none");
		} else {
			currentlyEnlightenedHrefDownload = linktext;
			linktext.setProperty('class','arrow selected');
		}
		linktext.setStyle('cursor','pointer');
		linktext.addEvent('mousedown', function(e) {
			currentlyDisplayedDownload.setStyle('display','none');
			currentlyEnlightenedHrefDownload.setProperty('class','arrow');
			item.setStyle('display','block');
			currentlyDisplayedDownload=item;
			linktext.setProperty('class','arrow selected');
			currentlyEnlightenedHrefDownload = linktext;
		}); 
	});
	// ---
	
	/* obsługa newsów */
	if(!document.archive) document.archive = new Array();
	
	function showScrollableDetails(contextDivId) {
		$$('#'+contextDivId+' a[href*=#details]').each(function(el) {
			el.addEvent('click', function(e) {
				$('layerDetail').empty();
				
				var e = new Event(e); e.stop();
				var detail = $E('#'+contextDivId+' div.details').innerHTML;
				
				var newDiv = new Element('div');
				newDiv.addClass('scroll');
				newDiv.setHTML(detail);
				newDiv.setStyle('height', $('layerDetail').getStyle('height'));
				
				var close = new Element('a');
				close.addClass('close');
				close.setAttribute('href', '#');
				
				$('layerDetail').adopt([close, newDiv]);
				$('layerDetail').setStyle('display', 'block');

				addScrollers('#layerDetail ');

				$$('#layerDetail a.close').each(function(elm) {
					elm.addEvent('click', function(ee) {
						var ee = new Event(ee); ee.stop();
						$('layerDetail').setStyle('display', 'none');
					});
				});
			});
		});
	}
	
	function setTitle() {
		if(!$defined(document.defaultTitle)) document.defaultTitle = document.title;
		var titleAppend = $E('#box h2').getText();
		var index = titleAppend.indexOf(' ', 48);
		
		if(titleAppend.length < 48 || index == -1) {
			document.title = 'BMW Motorrad Polska : '+titleAppend;
		}
		else {
			document.title = 'BMW Motorrad Polska : '+titleAppend.substring(0, index)+'...';
		}
	}
	
	$$('ul#newsList li a').each(function(item) {
		var newsId = String(item.getProperty('href')).split('#')[1];

		item.addEvent('click', function(e) {
			var e = new Event(e); e.stop();

			if(document.archive[newsId] || window.currentNews == newsId) {
				if(window.currentNews != newsId) {
					$('box').setHTML(document.archive[newsId]);
					if($('box').getParent().getParent().hasClass('scroller_main')) updateScrollers();
					else addScrollers('#box');
					zeroScroller('box');
					setHash(newsId);
					addGallery('box');
					showScrollableDetails('box');
					setTitle();
				}
				window.currentNews = newsId;
			}
			else {
				var req = new Ajax('/Aktualnosci/Newsy/'+newsId+'.html', {
					method:'post',
					onSuccess: function(data) {
						$('box').setHTML(data);
						var inner = $('box').innerHTML;
						document.archive[newsId] = inner;
						if($('box').getParent().getParent().hasClass('scroller_main')) updateScrollers();
						else addScrollers('#box');
						zeroScroller('box');
						window.currentNews = newsId;
						setHash(newsId);
						addGallery('box');
						showScrollableDetails('box');
						setTitle();
					}
				}).request();
			}
		});
	});
	
	if($$('#infoNoneTopNews').length > 0) {
		addScrollers('document');
		
		// pobierz pierwszego newsa	
		var newsId = getHash();
		if(newsId == '') newsId = String($E('ul#newsList li a').getProperty('href')).split('#')[1];
		
		var req = new Ajax('/Aktualnosci/Newsy/'+newsId+'.html', {
			method:'post',
			onSuccess: function(data) {
				$('box').setHTML(data);
				var inner = $('box').innerHTML;
				document.archive[newsId] = inner;
				window.currentNews = newsId;
				if($('box').getParent().getParent().hasClass('scroller_main')) updateScrollers();
				else addScrollers('#box');
				addGallery('box');
				showScrollableDetails('box');
				setTitle();
			}
		}).request();
	}
	/* koniec obsługi newsów */
	
	
 	/* wyłącz lewe menu, jeśli to nie jest dział enduro */
 	if($$('body#enduro').length == 0 && $$('#sidemenucontent').length > 0) {
		var mySlide = new Fx.Slide('sidemenucontent');
	 	$$('.dropper').each(function(item) {
	 		item.addEvent('click', function(e){
				e = new Event(e);
				mySlide.toggle();
				e.stop();
			});
	 	});
 		
	 	/* rozciągnięcie aktywnego fragmentu lewego menu w pionie */
 		var sideMenuContent = $$('#sidemenucontent > li');
 		var sizeall = 434 - (sideMenuContent.length-1)*26;
 		sideMenuContent.each(function(el) {
 			if((el.getSize().y||el.getSize().size.y) > 26) {
 				el.setStyle('height', sizeall);
 			}
 		})
 		$$('#sidemenucontent > li').getLast().addClass ('last-child');
 		window.menuLeft = mySlide;
 		
 		if($defined($E('#content #infoNoneTop #usedBikes')))
 			window.setTimeout('menuLeft.toggle();', 1500);
		var bodyid = document.body.id.substr(1);
		
		if(bodyid=='zwin')
 			window.setTimeout('menuLeft.toggle();', 1500);
		
 	}

	/* obsługa wyświetlania danych dla systemów nawigacji */
	if($('naviData') != null && $('naviData')!=undefined) {
		// ustawia nazwę modelu		
		var naviModel = trim($E('#belka h2.dropper').getText());
		
		var req = new Ajax('/tools/naviData.php', {
			method:'post',
			data: {
				navigator: naviModel
			},
			onSuccess: function(data) {
				$E('#naviData').setHTML(data);
				addScrollers('document');
			}
		});
		req.request();
	}
	/* koniec obsługi dla nawigacji */

	/* obsługa porównywania motocykli */
	if($('baseModel') != null && $('baseModel')!=undefined) {

		// ustawia nazwę modelu		
		var baseModel = trim($E('#belka h2.dropper').getText());
		$E('#baseModel b').setText(baseModel);
		
		var req = new Ajax('/tools/motorData.php', {
			method:'post',
			data: {
				action: 'compare',
				base: baseModel
			},
			onSuccess: function(data) {
				$E('#modelPickerData').setHTML(data);
				addScrollers('document');
			}
		}).request();
		
		// ustawia wyświetlanie dropdown menu
		var pickers = $$('.modelPickerText');
		pickers.each(function(item) {
			item.addEvent('click', function(e) {
				var toggleList = item.getParent().getElement('dl[class=dropdownCompare]');
				if(toggleList.style.display=="" || toggleList.style.display=="none")
					toggleList.style.display="block";
				else
					toggleList.style.display="none";
			});
		});
		
		// ustawia akcje dla poszczególnych modeli
		var reset = $$('.dropdownCompare').getElement('dt');
		reset.each(function(item) {
			item.style.cursor = 'pointer';
			
			item.addEvent('click', function(e) {
				dropid = item.getParent().id;
				image = $E('#'+dropid+'_img');
				image.setProperty('src', '');
				image.setStyle('display', 'none');
				
				item.getParent().style.display = 'none';
				item.getParent().getParent().getElement('.modelPickerText').setText(item.getText());
				
				model_1 = trim($E('#picker_1 .modelPickerText').getText());
				model_2 = trim($E('#picker_2 .modelPickerText').getText());
				
				var req = new Ajax('/tools/motorData.php', {
					method:'post',
					data: {
						action: 'compare',
						base: baseModel,
						motor_1: model_1,
						motor_2: model_2
					},
					onSuccess: function(data) {
						$E('#modelPickerData').setHTML(data);
						updateScrollers();
					}
				}).request();
			});
		});
		
		var models = $$('.dropdownCompare dd');
		models.each(function(item) {
			var modelItem = trim(item.getText());
			
			if(modelItem == baseModel) {
				model = item.id.substring(3);
				var tag = 'dd';
				var innerItem = item;
				while(tag != 'dt') { innerItem = innerItem.getPrevious(); tag = innerItem.getTag(); }
				
				category = String(innerItem.id).substring(3);
				path = "/images/compare/"+category+"/color_"+model+"_01_thumbnail.jpg";
				
				
				$E('#base_img').setProperty('src', path);
				$E('#base_img').setStyle('display', 'block');
				item.getParent().removeChild(item);
			}

			item.addEvent('click', function(e) {
				model = item.id.substring(3);
					
				var tag = 'dd';
				var innerItem = item;
				while(tag != 'dt') { innerItem = innerItem.getPrevious(); tag = innerItem.getTag(); }
				
				category = String(innerItem.id).substring(3);
				path = "/images/compare/"+category+"/color_"+model+"_01_thumbnail.jpg";
				
				dropid = item.getParent().id;
				image = $E('#'+dropid+'_img');
				image.setProperty('src', path);
				image.setStyle('display', 'block');
				
				item.getParent().style.display = "none";
				item.getParent().getParent().getElement('.modelPickerText').setText(item.getText());
				
				baseName = $E('#baseModel b').getText();
				model_1 = trim($E('#picker_1 .modelPickerText').getText());
				model_2 = trim($E('#picker_2 .modelPickerText').getText());
				
				var req = new Ajax('/tools/motorData.php', {
					method:'post',
					data: {
						action: 'compare',
						base: baseModel,
						motor_1: model_1,
						motor_2: model_2
					},
					onSuccess: function(data) {
						$E('#modelPickerData').setHTML(data);
						updateScrollers();
					}
				}).request();
			});
		});
	}
	/* koniec obsługi porównywania motocykli */
	
	
	/* obsługa danych technicznych */
	if($('dataContainer') != null && $('dataContainer') != undefined) {
		var baseModel = trim($$('#belka h2.dropper')[0].getText());
		
		var req = new Ajax('/tools/motorData.php', {
			method:'post',
			data: {
				action: 'technical',
				base: baseModel
			},
			onSuccess: function(data) {
				var zoomImageHTML = $('dataContainer').innerHTML;
				$E('#dataContainer').setHTML(data);
				
				var lefty = $('leftDataColumn').innerHTML;
				$E('#leftDataColumn').setHTML(zoomImageHTML+lefty);
				
				$E('#zoomIcon').addEvent('click', function(e) { $('zoomedImage').style.display = 'block'; });
				$E('#zoomIconOut').addEvent('click', function(e) { $('zoomedImage').style.display = 'none'; });
				
				var prop = String($E('#zoomImage > img').getProperty('src'));
				if(prop=='' || prop==undefined || prop==null || !prop.match('.gif')) {
					$E('#zoomImage').setStyle('display', 'none');
				}
				
				prop = String($E('#zoomedImage > img').getProperty('src'));
				if(prop=='' || prop==undefined || prop==null || !prop.match('.gif')) {
					$E('#zoomIcon').setStyle('display', 'none');
				}
				addScrollers('document');
			}
		}).request();
	}
	/* koniec obsługi danych technicznych */
	
	/* pokazanie wszystkich dealerów */
	$$('#infoDealers #box a[href=#wszyscy]').each(function (el) {
		el.addEvent('click', function(e) {
			showDealer('all');
		});
	});
	
	/* obsługa drukowania */
	$$('#printIcon').each(function (el) {
		el.addEvent('click', function(e) {
			print();
		});
	});
	
	/* usunięcie pustych, nie walidujących się elementów*/
	trimEmptyElements();
	
	/* podświetlenie odpowiedniego linka w menu prawym */
	$$('#infoNoneTop dl dd a').each(function(el) {
		var regTest = new RegExp(el.getProperty('href')+'$');
		var result	= regTest.test(String(window.location));
		if(result) {
			el.addClass('selected');
		}
		else {
			el.removeClass('selected');
		}
	});
	
	
	/* popup - obsługa dla wszystkich a tej klasy */
	$$('.popup').each(function (a){
		a.addEvent('click', function(e) {
			var e = new Event(e); e.stop();
			
			var hrefString = a.getProperty('href');
			var hrefParts = String(hrefString).split('?');
			var queryString = hrefParts[hrefParts.length-1];
			var queryParts = String(queryString).split('&');
			var winAttr = '';
			for(var i=0; i<queryParts.length; i++) {
				winAttr = winAttr + queryParts[i] + ',';
			}
			
			var windowAttr = String(winAttr).substring(0, winAttr.length-1);
			window.open(hrefParts[0], 'motorrad_popup', windowAttr, false);
		});
	});
	
	/* newsletter - wysłanie zapytania */
	$$('#newsletter #newsletterSend').each(function(a) {
		var emailRegExp = new RegExp(/^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i);
		var emailInput = $E('#newsletter input#email');
		
		var indicator = $E('#newsletter em');
		indicator.setStyle('display', 'none');
		
		emailInput.addEvent('keyup', function(e) {
			var emClass = (emailRegExp.test(emailInput.getProperty('value')))?'mail_valid':'mail_invalid';
			
			if(String(emailInput.getProperty('value')).length > 0) {
				indicator.removeClass('mail_valid').removeClass('mail_invalid').addClass(emClass);
				indicator.setStyle('display', 'block');
			}
			else {
				indicator.setStyle('display', 'none');
			}
		});


				
		a.addEvent('click', function(e) {
			var e = new Event(e); e.stop();
			var email = emailInput.getProperty('value');
			var optionText = $E('#newsletterText').getProperty('checked');
			var optionBMW = $E('#newsletterBMW').getProperty('checked');
			
			if(emailRegExp.test(email)) {
				var req = new Ajax('/tools/newsletter.php', {
					method:'get',
					data: {
						email: email,
						type: optionText?'2':'3',
						andbmw: optionBMW?'1':0
					},
					onSuccess: function(message) {
						var box = $E('#newsletter dl');
						if($defined(box)) {
							box.setStyle('display', 'none');
							var msgDiv = new Element('p');
							msgDiv.addClass('ojaxMsg');
							
							msgDiv.setHTML(message);
							msgDiv.injectAfter(box);
							$E('#newsletter #newsletterSend').setStyle('display', 'none');
						}
					}
				}).request();
			}
		});
	});

	/* dodaj scrollery wszędzie, gdzie potrzebne */	
	if($$('#infoModelCompare').length==0 && $$('#dataContainer').length==0 && $$('#naviData').length==0 && $$('#infoNoneTopNews').length==0)
		window.setTimeout("addScrollers('document');", 10);
});
