// ----------- do not edit below this line ---------- //

if (!window.console){
	var console = { log:function(comm){ if (Config.devMode == true && $('consoleDiv')) $('consoleDiv').innerHTML = $('consoleDiv').innerHTML+"<br />\n"+comm;/*alert(comm);*/} }
}

String.implement({ 
	toHash: function(){ 
		var hash = new Hash(); 
		this.split('&').each(function(el){
			var t = el.split('=');
			t[0] = t[0].replace("http://maps.google.com/staticmap?center", 'latlng');
			hash.include(t[0].replace(/amp;/, ''), t[1]);  
		});
		return hash; 
	}
});

Number.extend({
	 
	/*
	Property: numberFormat
		Format a number with grouped thousands.
 
	Arguments:
		decimals, optional - integer, number of decimal percision; default, 2
		dec_point, optional - string, decimal point notation; default, '.'
		thousands_sep, optional - string, grouped thousands notation; default, ','
 
	Returns:
		a formatted version of number.
 
	Example:
		>(36432.556).numberFormat()  // returns 36,432.56
		>(36432.556).numberFormat(2, '.', ',')  // returns 36,432.56
	*/
 
	numberFormat : function(decimals, dec_point, thousands_sep) {
		var decimals = Math.abs(decimals) + 1 ? decimals : 2;
		var dec_point = dec_point || '.';
		var thousands_sep = thousands_sep || ',';
 
		var matches = /(-)?(\d+)(\.\d+)?/.exec(this + ''); // returns matches[1] as sign, matches[2] as numbers and matches[2] as decimals
		var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
		return (matches[1] ? matches[1] : '') + (remainder ? matches[2].substr(0, remainder) + thousands_sep : '') + matches[2].substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) + 
				(decimals ? dec_point + (+matches[3] || 0).toFixed(decimals).substr(2) : '');
	}
})

//jezyk dokumentu - poki html nie ma lang
lang = $(document.html).get('lang');

window.addEvent("domready", function() {

	//tworzenie #consoleDiv pod ie
	if (Browser.Engine.trident && Config.devMode == true) new Element('div',{'id':'consoleDiv'}).setStyles({'position':'absolute','z-index':'13','top':'0','left':'0','background':'#fff','color':'#000'}).inject($('container'), 'before').appendText('consoleDiv');

	// ie bg fix 
	try {
		document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}
	
	
	//categories - ostatnie li
	$('categories').getLast().addClass('last-child');
	
	//categories - zaslaw, stokota
	$$('#categories a').each(function(a){
		if (a.get('text').indexOf('Zasław') != -1) a.addClass('zaslaw');
		else if (a.get('text').indexOf('Stokota') != -1) a.addClass('stokota');
		else if (a.get('text').indexOf('CMT') != -1) a.addClass('cmt');
		else if (a.get('text').indexOf('TRAILIS') != -1) a.addClass('trailis');
		else if (a.get('text').indexOf('T.S.R.') != -1 || a.get('text').indexOf('TSR') != -1) a.addClass('tsr');
	})
	
	//manufacturers - dodaje bottom
	new Element('div').addClass('bottom').inject($('manufacturers'));
	
	//Dtr ekstra - dodaje klase .dtr do h1 nie zagniezdzonych w #intro, aby Dtr mogl pracowac na wlasciwej kolekcji elementow
	$$('h1').each(function(el){
		if (el.getParent() != $('intro') && !$('productitem')) el.addClass('dtr');
	})
	
	//Dtr - Dynamic Text Replacement
	$each(Config.Dtr.elements, function(props, id) { 
		$$(props.elements).each(function(el){
			el.addClass('dtr');
			var img_path = '/style/dtr/image.php?text='+el.get('text');
			$each(props, function(prop, k){
				if (k != 'elements') img_path += '&'+k+'='+prop.replace(/#/, ''); //czyscimy hasza bo nie przechodzi
			})
			var img = new Element('img', {
				'src': img_path
			}).inject(el);
			var h = img.getSize().y;
			if (h < 1) h = 20;
			var span = new Element('span').set({
				'class': 'dtr',
				'styles': {
					'background-image': 'url("'+img_path+'")',
					'height': h
				},
				'html': '<span>'+el.get('text')+'</span>'
			});
			//img.destroy();
			el.empty().grab(span);
			//span.inject(el);
		})
	})

	//Decorations - osadzanie ozdobnikow
	$each(Config.Decorations.elements, function(props) { 
		$$(props.containers).each(function(el){
			if (props.where == 'bottom' || props.where == null) 
				el.innerHTML += props.symbol;
			else
				el.innerHTML = props.symbol + el.innerHTML;
		})
	})
	
	//sort - obsluga formularza sortujacego
	if ($('sort')) {
		var form = $('sort').getParent('form');
		var select = $('sort').getElement('select');
		var submit = $('sort').getElement('input[type=submit]');
		
		submit.setStyle('display', 'none');
		select.addEvent('change', function(ev){
			//console.log(ev);
			form.submit();
		})		
		
	}
	
	//pagenawigator - ostatnia pozycja
	if ($('pagenavigator')) $('pagenavigator').getLast().addClass('last-child');
	
	//formularz sprzedazy
	if ($('sell-form')) {
		$('vehicle_type').addEvent('change', function() {
			$$('#vehicle_make optgroup').each(function(el){
				if (el.get('label') != $('vehicle_type').get('value')) el.setStyle('display', 'none');
				else {
					el.setStyle('display', 'block');
					visibleOptgroup = el; 
				}				
			}) 
			$$('#vehicle_make option').erase('selected');
			visibleOptgroup.getFirst().set('selected', 'selected');
		})
	}
	
	//FormCheck
	Config.FormCheck.forms.each(function(form) {
		if ($(form)) new FormCheck(form, {
			alerts: {
            	required: eval('Config.FormCheck.alerts.'+lang+'.required'),
            	phone: eval('Config.FormCheck.alerts.'+lang+'.phone'),
            	email: eval('Config.FormCheck.alerts.'+lang+'.email')
        	}
		})			
	})

	
	//FILTROWANIE
	if ($('filters')) {
		$('filters').getParent('form').set('autocomplete', 'off'); //dokladanie autocomplete="off" aby formularz filtrowania nie wypelnial sie poprzednio wprowadzonymi danymi pod FX
		
		//zwin/rozwin
		var h = $('filters').getSize().y;
		var filtersEffect = new Fx.Morph($('filters'));
		var table = $('filters').getElement('table');
		//var tableEffect = new Fx.Morph($('filters').getElement('table'));
		if (lang == 'en') { var shrink = 'Collapse'; var expand = 'Expand'; }
		else if (lang == 'ru') { var shrink = 'Свернуть'; var expand = 'Развернуть'; }
		else { var shrink = 'Zwiń'; var expand = 'Rozwiń'; }
		var zwin = new Element('span').inject($$('h2.filters')[0], 'bottom');
		$$('h2.filters')[0].addEvent('click', function() {
			//alert($('filters').getSize().y);
			if ($('filters').getSize().y < 30) {
				filtersEffect.start({ 'height': h, 'opacity': 1 });
				zwin.set('html', '['+shrink+']');
				Cookie.write('filters', 'expanded', {/*domain: window.location.hostname, */path: '/'});
				if (Browser.Engine.trident) table.setStyle('visibility', 'visible'); //na ie
			}
			else {
				filtersEffect.start({ 'height': 0, 'opacity': 1 });
				zwin.set('html', '['+expand+']'); 
				Cookie.write('filters', 'shrinked', {path: '/'});
				if (Browser.Engine.trident) table.setStyle('visibility', 'hidden'); //na ie
			}
		});
		$('filters').setStyle('overflow', 'hidden'); //konieczne, pamietac
		if (Cookie.read('filters') == 'shrinked') {
			zwin.set('html', '['+expand+']');
			filtersEffect.set({'height': 0, 'opacity': 1 });
			if (Browser.Engine.trident) table.setStyle('visibility', 'hidden'); //na ie
		}
		else zwin.set('html', '['+shrink+']');
	}
	
	
	
	//suwaki
	$$('.slider').each(function(slider){
	//var fieldset = document.body.getElement('fieldset.slider');
		//ukrywamy labele i inputy
		//fieldset.getElements('label').addClass('hide');
		//fieldset.getElements('input').addClass('hide');
		//tworzymy elementy suwaka
		var gutter = new Element('div', { //jezdnia :D
			'class': 'suwak-tlo'
		}).inject(slider);
		var knob_min = new Element('div', { //dolny
			'class': 'suwak-galka'
		}).inject(gutter);
		var knob_max = new Element('div', { //gorny
			'class': 'suwak-galka'
		}).inject(gutter);
		var int_min = slider.getElement('.min').get('text').toInt(); //minimum
		var int_max = slider.getElement('.max').get('text').toInt(); //maksimum		
		
		var input_od = slider.getElement('input'); 
			var int_od = input_od.get('value').toInt(); //biezaca wartosc pola "Od"		
		var input_do = slider.getElements('input')[1]; 
			var int_do = input_do.get('value').toInt(); //biezaca wartosc pola "do"
		
		//console.log(start_val+' / '+end_val);
		
		//tworzymy suwak
		new Slider(gutter, knob_min, {
			start: int_min,
			end: int_max,
			offset: 1,
			knobheight: 17,
			onChange: function(pos){
				input_od.set('value', pos.minpos.toInt());
				input_do.set('value', pos.maxpos.toInt());
				/*if (pos.minpos.toInt() != int_od || pos.maxpos.toInt() != int_do ) slider.getElement('p').addClass('selected');
				else slider.getElement('p').removeClass('selected');*/
			}
		}, knob_max).setMin(int_od).setMax(int_do);
		
	})
	
	//accordion
	
	//zaznaczanie biezacej kategorii gdy jestesmy w produkcie
	if ($$('#categories a.actv').length == 0) $('categories').getElements('a').each(function(el){
		var href = el.getProperty('href').replace(window.location.protocol+'//'+window.location.host+'','');
		var url = window.location.href.replace(window.location.protocol+'//'+window.location.host+'','');
		url = url.substr(0, url.lastIndexOf('/'));
		url = url.substr(0, url.lastIndexOf('/')+1);
		if (href == url) el.addClass('actv');
	});
	
	//przygotowywanie kolekcji
	$$('#categories ul ul').each(function(el){
		el.addClass('accordion')
		el.getPrevious().addClass('toggle');		
	});
	//wykrywanie podmenu do rozwiniecia
	accordion_to_show = 99;
	$$('.accordion').each(function(ul, i){
		ul.getElements('.actv').each(function(){
			accordion_to_show = i;			
		})
	})

	//zdejmowanie eventu onclick z a1, a2 w menu kategorii		
	$('categories').getChildren().each(function(li) {
		li.getFirst('a').erase('href');
	})
	$$('#categories a.toggle').each(function(a){
		a.erase('href');
	})
	
	//accordion - tworzenie instancji
	var myAccordion = new Accordion($$('.toggle'), $$('.accordion'), { 
		show: accordion_to_show,
		opacity: true,
		alwaysHide: true
	});	
	
	// seo
	$('seo4').addEvent('click', function(event) {
    	location.href = "http://seo4.net/";
    	new Event(event).stop();
	})

}) //koniec ondomready

window.addEvent("load", function() {

	//osadzanie map googla
	var Gmap = $$('img[src^=http://maps.google.com/staticmap]')[0];
	if (Gmap && Gmap.getParent().get('id') == 'Gmap') {
		var src = Gmap.get('src');
		Gmap = Gmap.getParent();
		
		window.onunload = GUnload; // przy wyjsciu ze strony zwalniamy pamiec 
		if (GBrowserIsCompatible()) {  
			//obrabiamy zrodlo mapy statycznej
			var h = src.toHash();
			console.log(h);
			var size = h.size.split('x');
			var latlng = h.latlng.split(',');
						
			var map = new GMap2(Gmap, { 
				size: new GSize(size[0], size[1]) 
			});  
			map.addControl(new GLargeMapControl());  
			map.addControl(new GMapTypeControl());  
			var point = new GLatLng(latlng[0], latlng[1]);
			map.setCenter(point, h.zoom.toInt(), G_NORMAL_MAP);  
			map.addOverlay(new GMarker(point/*, icon*/));
			map.enableScrollWheelZoom();			
		}
	}
	
}); //koniec onload