/*
	DECODE UTF8 string
*/
var encode = function(string) {
	string = string.replace(/\r\n/g,"\n");
	var utftext = "";
	for (var n = 0; n < string.length; n++) {
		var c = string.charCodeAt(n);
		if (c < 128) {
			utftext += String.fromCharCode(c);
		}
		else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		}
		else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}
	}
	return utftext;
}
var decode = function(utftext) {
	var string = "";
	var i = c = c1 = c2 = 0;
	while (i < utftext.length) {
		c = utftext.charCodeAt(i);
		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		}
		else if ((c > 191) && (c < 224)) {
			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else {
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}
	}
	return string;
}

/*var surveyFormValidation = function() {
	
	$('.close-layer').click(function() {
		$('#ajax-survey').remove();
		$('#overlay').remove();
		return false;
	});
	
	$('form#promo-survey-layer').submit(function(){
		
		$this = $(this);
		$this.find('.warning').removeClass('warning');
		
		if ($.trim($('#phone-layer').val()) == ''){
			$('#promo-survey-layer label[for="phone-layer"]').parent('div').addClass('warning');
		}
		if(!($('#promo-survey-layer .radio input').is(':checked'))) {
			$('#promo-survey-layer #radio-buttons-layer').addClass('warning');
		}
		if ($('.warning').size()) {
			alert('Wypełnij poprawnie wszystkie obowiązkowe pola ankiety.');
			$('.warning:first label').next().focus();
			return false;
		}
		$('#promo-survey-layer').addClass('processing').find('#unique_id').val((Math.random()) * 10);
		$.post(HP_host + '/admin/forms/form_submit.php', $this.find('input').serialize(), function(){
			$('#promo-survey-layer').removeClass('processing').html('<h4>Ankieta została wysłana, dziękujemy.</h4><h5><a href="#" class="close-layer">&lt; Wróć do strony FeuVert</a></h5>');
			$('.close-layer').click(function() {
				$('#ajax-survey').remove();
				$('#overlay').remove();
				return false;
			});
		});
		return false;
	});
	
}*/

/*
	KLIENCI rotator
*/
var rotate = function(objId, count, topshift) {
	$(objId + ' li').hide().css({marginTop: '0'});
	for (var i = 0; i < count; i++) {
		$(objId + ' li:eq(' + (i + parseInt($(objId).attr('last'))) + ')').animate({marginTop: topshift + 'px'}, {queue: false}).fadeIn();
	}
	last = (parseInt($(objId).attr('last')) + count >= $(objId + ' li').size()) ? 0 : parseInt($(objId).attr('last')) + count;
	$(objId).attr('last', last);
}

/*
	DOCUMENT READY
*/
$(function(){
	
	/*
		GOOGLE ANALYTICS events
	*/
	$('#index #advices h4 a').click(function(){pageTracker._trackPageview("/clickdata/homepage/porady/1");});
	$('#index #advices .more a').click(function(){pageTracker._trackPageview("/clickdata/homepage/porady/2");});
	$('#print-bar button').click(function() {pageTracker._trackEvent('Kupony', 'Wydruk', 'Ktos wydrukowal kupon');});
	$('.print-promo a, #main-content #article .entry .content h4 a, #main-content #article .entry .thumb a').click(function() {pageTracker._trackEvent('Kupony', 'Zobaczyl', 'Ktos zobaczyl kupon');});
	
	/*
		PRINT popop & action
	*/
	$('.print-promo a, #main-content #article .entry .content h4 a, #main-content #article .entry .thumb a, #article .promo-tires .promo-content .tire-cupon').click(function(){
		window.open(this.href, null, 'width=620,height=430,scrollbars=yes');
		return false;
	});
	
	/*
		FLIP PAGE FLASH embed
	*/
	$('#company-news .thumb a').click(function(){
		window.open(HP_host + '/showpage.php?pageID=120','flippage','width=1000, height=620');
		return false;
	});
	
	/*
		VOTE results animation
	*/
	var showResults = function() {
		$('.results li div').each(function(){
			$this = $(this);
			$this.css({'max-width': $this.css('width'), 'width': '0'}).animate({width: $this.css('max-width')}, {duration:2000});
		})
	}

	/*
		PRINT popop & action
	*/
	$('#toolbar .print').click(function(){
		window.open(this.href, null, 'width=530,height=400,scrollbars=yes');
		return false;
	});
	$('#print-bar button').click(function(){
		print();
		return false;
	});

	/*
		NEWSLETTER MAIL info
	*/
	var $field = $('#mail');
	var startVal = $field.val();
	$field.focus(function(){
		(this.value == startVal) && $field.val('');
	})
	.blur(function(){
		(!this.value) && $field.val(startVal);
	});
	$('#newsletter form, #article form#newsletter-content-form').submit(function(){
		$field.val($.trim($field.val()));
		if (!(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($field.val()))) {
			alert('Podany adres e-mail jest nieprawidłowy.');
			$field.addClass('warning').focus();
			return false;
		}
	});
	
	/*
		VOTE ajax submit
	*/
	$('#vote form').submit(function(){
		if ($('input:checked', this).size() > 0) {
			$('#vote').addClass('ajax-layer');
			$.ajax({
				type: 'POST',
				url: HP_host + '/showpage.php?pageID=11',
				data: $('#vote form input:checked').serialize(),
				success: function(msg){
					if (msg != '') {
						$('#vote').after(msg).remove();
						$('#vote p:first').before('<p><strong>Dziękujemy! Twój głos został zapisany.</strong></p>');
						showResults();
					}
					else
						alert("Przepraszamy, wystąpiły problemy ze sondą. Twój głos nie został zapisany.");
				}
			});
		} else {
			alert('Proszę wybrać jedną z odpowiedzi.');
		}
		return false;
	});
	
	/*
		CLIENTS OPINION form ajax submit
	*/
	$('form#opinieklientow').css('visibility', 'visible').submit(function(){
		$this = $(this);
		$this.find('#unique_id').val(Math.random() * 10).end().find('#f_srv').val($('#f_srv_list option:selected', $this).val());
		$this.find('.warning').removeClass('warning');
		mailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		if (!mailFilter.test($.trim($('#f_mail').val()))){
			$('label[for="f_mail"]').parent('div').addClass('warning');
		}
		if ($('#f_srv').val().length < 3){
			$('label[for="f_srv_list"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_msg').val()) == ''){
			$('label[for="f_msg"]').parent('div').addClass('warning');
		}
		if ($('.warning').size()) {
			alert('Wypełnij poprawnie wszystkie obowiązkowe pola formularza.');
			$('.warning:first label').next().focus();
			return false;
		}
		$this.addClass('processing').find('#unique_id').val((Math.random()) * 10);
		$.post(HP_host + '/admin/forms/form_submit.php', $this.find('input, textarea').serialize(), function(){
			$this.removeClass('processing').html('<p><strong>Twoja opinia na nasz temat została wysłana. Dziękujemy.</strong></p>');
		});
		return false;
	});
	
	/*
		CONTACT form ajax submit
	*/
	$('form#kontaktowy').css('visibility', 'visible').submit(function(){			
		$this = $(this);
		$this.find('.warning').removeClass('warning');
		mailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		if ($.trim($('#f_name').val()) == ''){
			$('label[for="f_name"]').parent('div').addClass('warning');
		}
		if (!mailFilter.test($.trim($('#f_mail').val()))){
			$('label[for="f_mail"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_msg').val()) == ''){
			$('label[for="f_msg"]').parent('div').addClass('warning');
		}
		if ($('.warning').size()) {
			alert('Wypełnij poprawnie wszystkie obowiązkowe pola formularza.');
			$('.warning:first label').next().focus();
			return false;
		}
		$this.addClass('processing').find('#unique_id').val((Math.random()) * 10);
		$.post(HP_host + '/admin/forms/form_submit.php', $this.find('input, textarea').serialize(), function(){
			$this.removeClass('processing').html('<p><strong>Formularz kontaktowy został wysłany, dziękujemy.</strong></p>');
		});
		return false;
	});
	
	/*
		FLEET form ajax submit
	*/
	$('form#fleet-form').css('visibility', 'visible').submit(function(){
		$this = $(this);
		$this.find('.warning').removeClass('warning');
		mailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		
		if ($.trim($('#f_company_name').val()) == ''){
			$('label[for="f_company_name"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_company_addr').val()) == ''){
			$('label[for="f_company_addr"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_company_car_q').val()) == ''){
			$('label[for="f_company_car_q"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_company_car').val()) == ''){
			$('label[for="f_company_car"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_company_personal_name').val()) == ''){
			$('label[for="f_company_personal_name"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_company_phone').val()) == ''){
			$('label[for="f_company_phone"]').parent('div').addClass('warning');
		}
		if (!mailFilter.test($.trim($('#f_company_email').val()))){
			$('label[for="f_company_email"]').parent('div').addClass('warning');
		}
		if ((!$('.checkbox input:checked').size())){
			$('.checkbox').parent().addClass('warning');
		}
		if ($('.warning').size()) {
			alert('Wypełnij poprawnie wszystkie obowiązkowe pola formularza.');
			$('.warning:first label').next().focus();
			return false;
		}
		$this.addClass('processing').find('#unique_id').val((Math.random()) * 10);
		$.post(HP_host + '/admin/forms/form_submit.php', $this.find('input, textarea, checkbox').serialize(), function(){
			$this.removeClass('processing').html('<p><strong>Formularz został wysłany, dziękujemy.</strong></p>');
		});
		return false;
	});
	
	/*
		JOB APPLY form submit
	*/
	$('form#zgloszeniowy').css('visibility', 'visible').submit(function(){			
		$this = $(this);
		$this.find('.warning').removeClass('warning');
		if ($.trim($('#f_name').val()) == ''){
			$('label[for="f_name"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_stand').val()) == '-1'){
			$('label[for="f_stand"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_file1').val()) == ''){
			$('label[for="f_file1"]').parent('div').addClass('warning');
		}
		if ($('.warning').size()) {
			alert('Wypełnij poprawnie wszystkie obowiązkowe pola formularza.');
			$('.warning:first label').next().focus();
			return false;
		}
		function completeCallback(response) {
			alert(response);
		}
		$this.addClass('processing').find('#unique_id').val((Math.random()) * 10);
		AIM.submit($this.get(0), {
			'onComplete': function(){
				$this.removeClass('processing').html('<p><strong>Formularz zgłoszeniowy został wysłany, dziękujemy.</strong></p>');
			}
		});
		$this.unbind('submit').submit();
		return false;
	});

	/*
		AJAX IFRAME METHOD (AIM) http://www.webtoolkit.info/
	*/
	AIM = {
		frame : function(c) {
			var n = 'f' + Math.floor(Math.random() * 99999);
			var d = document.createElement('DIV');
			d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
			document.body.appendChild(d);
			var i = document.getElementById(n);
			if (c && typeof(c.onComplete) == 'function') {
				i.onComplete = c.onComplete;
			}
			return n;
		},
		form : function(f, name) {
			f.setAttribute('target', name);
		},
		submit : function(f, c) {
			AIM.form(f, AIM.frame(c));
			if (c && typeof(c.onStart) == 'function') {
				return c.onStart();
			} else {
				return true;
			}
		},
		loaded : function(id) {
			var i = document.getElementById(id);
			if (i.contentDocument) {
				var d = i.contentDocument;
			} else if (i.contentWindow) {
				var d = i.contentWindow.document;
			} else {
				var d = window.frames[id].document;
			}
			if (d.location.href == "about:blank") {
				return;
			}
			if (typeof(i.onComplete) == 'function') {
				i.onComplete(d.body.innerHTML);
			}
		}
	}
	
	/*
		PROMO FLASH - dla flot
	*/
	if($('#promo .visit').size()) {
		$('#promo .visit').prepend('<div id="promo-visit-flash"></div>');
		swfobject.embedSWF(HP_host + '/pub/uploadflash/klient_flotowy_box.swf', 'promo-visit-flash', '217', '104', '8.0.0.0', '', {HP_host: HP_host}, {});
	}
	
	if($('#aside .visit').size()) {
		$('#aside .visit').prepend('<div id="aside-visit-flash"></div>');
		swfobject.embedSWF(HP_host + '/pub/uploadflash/klient_flotowy_box.swf', 'aside-visit-flash', '237', '113', '8.0.0.0', '', {HP_host: HP_host}, {});
	}
	
	/*
		About Us flash
	*/
	if($('#about-us-video').size()) {
		$('#about-us-video').prepend('<div id="about-us-video-flash"></div>');
		swfobject.embedSWF(HP_host + '/pub/uploadflash/about-us.swf', 'about-us-video-flash', '614', '345', '8.0.0.0', '', {uiDir: HP_host + '/pub/uploadflash/'}, {allowFullScreen: 'true'});
	}
	
	/*
		NAV TOP flash embed
	*/
	if($('#nav-ani').size()) {
		$('#nav-ani').prepend('<div id="nav-ani-flash"></div>');
		swfobject.embedSWF(HP_host + '/pub/uploadflash/banner_top.swf', 'nav-ani-flash', '676', '98', '9.0.0', '', {HP_host: HP_host}, {wmode: 'transparent'});
	}
	
	/*
		MAIN FLASH embed
	*/
	if($('#main-ani').size()) {
		$('#main-ani').prepend('<div id="main-ani-flash"></div>');
		swfobject.embedSWF(HP_host + '/pub/uploadflash/main.swf', 'main-ani-flash', '702', '345', '9.0.0', '', {HP_host: HP_host}, {});
	}
	
	/*
		PROMO BIG FLASH EMBED
	*/
	if($('#feuvert_main_banner').size()) {
	//$('#main-ani').prepend('<div id="main-ani-flash"></div>');
		swfobject.embedSWF(HP_host + '/pub/uploadflash/Feuvert-FV-czerwiec.swf', 'feuvert_main_banner', '702', '500', '9.0.0', '', {HP_host: HP_host}, {wmode: 'transparent'});
	}
	
	/*
		LOCATIONS MAP FLASH EMBED
	*/
	if($('#locations-map').size()) {
		$('#locations-map').prepend('<div id="locations-map-ani"></div>');
		swfobject.embedSWF(HP_host + '/pub/uploadflash/mapa.swf', 'locations-map-ani', '706', '421', '9.0.0', '', {HP_host: HP_host}, {wmode: 'transparent'});
	}
	
	/*
		POPUP LAYER
	*/
	//if (document.URL.indexOf('popup=1') > -1) {
	if ($.cookie('popup_fv') != $('#popup-content .entry').attr('id') && $('#popup-content').html().length > 10 && $('.sOverlibDiv').size() < 1) {
		var date = new Date();
		date.setTime(date.getTime()+(30*60*1000))
		document.cookie = "popup_fv=" + $('#popup-content .entry').attr('id') + "; expires=" + date.toGMTString() + "; path=/";
		$('#popup-content')
			.show()
			.before('<div id="overlay"></div>')
			.prepend('<a href="#close" class="close">x</a>')
			.find('.close')
			.click(function(){
				$('#popup-content').hide();
				$('#overlay').hide();
				$('object, embed, select').show();
				return false;
			}).end()
			.find('h4:first').remove();
		$('object, embed, select').hide();
		$('#overlay')
			.css({height: $(document).height() + 'px', opacity: '0.6', zIndex: '980'})
			.click(function(){
				$('#popup-content').hide();
				$('#overlay').hide();
				$('object, embed, select').show();
			});
	}
	
	/**
	 * Popup layer survey form
	
	surveyFormValidation();
	if (($.cookie('popup_survey') != 1) && ($('.sOverlibDiv').size() < 1) && (!$('#promotion-survey').size())) {
	
		$.cookie('popup_survey', 1, {path: '/', expires: 365});
		$('#footer').after('<div id="overlay"></div><div id="ajax-survey"></div>');
		$('#ajax-survey').addClass('processing').load(HP_host + '/showpage.php?pageID=246', function() {
			$(this).removeClass('processing');
			surveyFormValidation();
		});
		
		$('#overlay')
			.css({height: $(document).height() + 'px', opacity: '0.6', zIndex: '950'})
			.click(function(){
				$('#ajax-survey').remove();
				$('#overlay').remove();
			});
	}*/
	
	/* 
		PROMOTIONS SLIDER
	*/
	
	$('#promotions')
		.css({visibility: 'visible'})
		.find('.content')
			.loopedSlider({container: '.slide-box', containerClick: false, autoStart: 6000, restart: 6000, slidespeed: 850, fadespeed: 850});
	
	$('#oi').change(function(){
		location = HP_host + '/kontakt/nasze-oddzialy.html?oi=' + $('option:selected', this).val();
	});
	
	var directionsFromInitValue = $('#directions-from').val();
	$('#directions-from')
		.focus(function(){
			if ($(this).val() == directionsFromInitValue) {
				$(this).val('');
			}
		})
		.blur(function(){
			if ($(this).val() == '') {
				$(this).val(directionsFromInitValue);
			}
		});
	
	/**
	 * Google Maps Directions embedding
	 */
	if ($('#map').size() && GBrowserIsCompatible()) {
		
	
		$(window).unload(function(){
			GUnload();
		});
		
		var map = new GMap2(document.getElementById('map'));
		map.setUIToDefault();
		map.addControl(new GMapTypeControl());
		
		marker = '';
		var activeMarker;
		
		function getTargetPoint(){
			if($('#map-entries li.active').size()) {
				return GLatLng.fromUrlValue($('#map-entries li.active .latlng').val().slice(1, -1));
			}
		}
		
		var latlng = getTargetPoint();
		
		if ($('.latlng').size() > 1) {
			bounds = new GLatLngBounds();
			$('.latlng').each(function(index){
				var latlng = GLatLng.fromUrlValue($(this).val().slice(1, -1));
				var fv_ico = new GIcon(G_DEFAULT_ICON);
				if ($(this).parent().is('.fv')) {
					fv_ico.image = HP_host + '/pub/uploadimages/google_marker_ico_fv.png';
					fv_ico.iconSize = new GSize(53, 39);
					fv_ico.iconAnchor = new GPoint(25, 39);
				} else {
					fv_ico.image = HP_host + '/pub/uploadimages/google_marker_ico_cs.png';
					fv_ico.iconSize = new GSize(33, 39);
					fv_ico.iconAnchor = new GPoint(15, 39);
				}
				marker = new GMarker(latlng, {icon: fv_ico});
				map.addOverlay(marker);
				if ($('#map-entries li:eq(' + index + ')').text() != '') {
					GEvent.addListener(marker, 'click', function(){
						this.openInfoWindowHtml('<div class="marker-content">' + $('#map-entries li:eq(' + index + ')').html() + '</div>');
					});
					//alert(latlng + ' : ' + getTargetPoint())
					if (latlng == getTargetPoint()) {
						GEvent.addListener(map, 'load', function(){
							GEvent.trigger(marker, 'click');
						});
					}
					
				}
				bounds.extend(marker.getPoint());
				map.setCenter(latlng, 18);
			});
		}
		
		if($('#map-entries li.active').size()) {
			map.setCenter(latlng, 14);
		}
		else {
			map.setZoom(map.getBoundsZoomLevel(bounds) - 1);
			map.setCenter(bounds.getCenter());
		}
		
		//GEvent.trigger(marker, 'click');
		
		var path = [];
		var bounds = new GLatLngBounds();
		var geo = new GClientGeocoder(new GGeocodeCache());
		var reasons=[];
		reasons[G_GEO_SUCCESS]            = "Success";
		reasons[G_GEO_MISSING_ADDRESS]    = "Nierozpoznany adres.";
		reasons[G_GEO_UNKNOWN_ADDRESS]    = "Nierozpoznany adres - spróbuj wpisać tylko nazwę miejscowości.";
		reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Niedostępny adres - nie można pokazać tej trasy.";
		reasons[G_GEO_BAD_KEY]            = "Błędny klucz API.";
		reasons[G_GEO_TOO_MANY_QUERIES]   = "Bład - za dużo zapytań. Spróbuj ponownie za jakiś czas.";
		reasons[G_GEO_SERVER_ERROR]       = "Błąd serwera. Spróbuj ponownie za jakiś czas.";
		reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
		reasons[G_GEO_MISSING_QUERY]      = "Brak lokalizacji w polu wyszukiwania.";
		reasons[G_GEO_UNKNOWN_DIRECTIONS] = "Nie można ustalić połączenia między punktami.";
		
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.iconSize=new GSize(24,38);
		
		var icon1 = G_START_ICON;
		var icon3 = G_END_ICON;
		var addresses = [];
		var startpoint = null;
		
		function doStart(point){
			path[1] = getTargetPoint();
			if (startpoint != null){
				map.removeOverlay(startpoint);
				map.setCenter(path[1], 12);
				bounds = new GLatLngBounds();
			}
			startpoint = new GMarker(point,{dragable:true, icon:icon1}); 

			GEvent.addListener(startpoint, 'dragend', function(){
				path[0] = startpoint.getPoint();
				addresses[0] = '';
			});
			map.addOverlay(startpoint);

			path[0] = point;
			bounds.extend(path[0]);
			bounds.extend(path[1]);
			map.setZoom(map.getBoundsZoomLevel(bounds));
			map.setCenter(bounds.getCenter());
			directions();
		}

		var gdir = new GDirections(null, document.getElementById('path'));

		GEvent.addListener(gdir,'error', function(){
			var code = gdir.getStatus().code;
			var reason = 'Kod ' + code;
			if (reasons[code]){
				reason = "Kod " + code + ': ' + reasons[code]
			}
			alert('Failed to obtain directions, ' + reason);
		});

		var poly;
		GEvent.addListener(gdir, 'load', function(){
			if (poly)
				map.removeOverlay(poly);
			poly = gdir.getPolyline();
			map.addOverlay(poly);
		});
		
		GEvent.addListener(gdir, 'addoverlay', function(){
			$('#article tr td:has("a")').each(function(){
				$(this).html($(this).text());
			});
			$('#article tr td').css('cursor', 'default');
		});

		function directions(){
			if (addresses[0]){
				var a = addresses[0] + "@" + path[0].toUrlValue(6)
			}
			else {
				var a = path[0].toUrlValue(6)
			}
			var b = path[1].toUrlValue(6)
			var a = 'from: ' + a + ' to: ' + b;
			gdir.load(a, {getPolyline:true});
			map.removeOverlay(marker);
			marker = new GMarker(latlng, {icon:icon3});
			map.addOverlay(marker);
		}
		
		function showAddress(){
			var search = $('#directions-from').val();
			addresses[0] = search;
			geo.getLatLng(search, function (point){ 
				if (point){
					doStart(point);
				}
				else {
					var result = geo.getCache().get(search);
					if (result){
						var reason = 'Kod ' + result.Status.code;
						if (reasons[result.Status.code]){
							reason = reasons[result.Status.code]
						}
					}
					else {
						var reason = '';
					}
					alert('Nie można odnaleźć "' + search + '". ' + reason);
				}
			});
		}
		
		$('#directions')
			.show()
			.submit(function(){
				showAddress();
				return false;
			});
		
		$('#directions-to')
			.change(function(){
				$('#map-entries li:contains("' + $('option:selected', this).text() + '")').addClass('active').siblings().removeClass('active');
				if (startpoint != null){
					showAddress();
				} else {
					map.setCenter(getTargetPoint(), 14);
				}
			});
		
	}
	
	/*
		GOOGLE MAPS PROMOTION
	*/
	$('.promotion-map-tabs li').click(function() {
		$('.promotion-map-tabs li').removeClass('active');
		$(this).attr('class', 'active');
		infoText = '<h4>' + $('h4', this).text() + '</h4>' + $('.infoText', this).html();
		var latlng = GLatLng.fromUrlValue($('.latlng', this).val().slice(1, -1));
		marker = new GMarker(latlng, {icon: feuvertIcon});
		GEvent.addListener(marker, "click", function(){
			map.openInfoWindowHtml(latlng, '<div class="marker-content">' + infoText + '</div>');
		});
		map.openInfoWindowHtml(latlng, infoText);
		map.setCenter(latlng, 15);
		map.addOverlay(marker);
		//zmien kolor
		return false;
	})

	if ($('#mapPromotion').size() && GBrowserIsCompatible()) {
		$('#mapPromotion').css('visibility', 'visible');
		var map = new GMap2(document.getElementById("mapPromotion"));
		map.addControl(new GSmallMapControl());	
		var feuvertIcon = new GIcon(G_DEFAULT_ICON);
		feuvertIcon.image = HP_host + "/pub/uploadimages/marker.png";
		$('.promotion-map-tabs li:first').trigger('click');
	}
	
	/*
		OVARHAUL SUBMIT VALIDATOR
	*/
	$('#overhaul form, #overhaul-form').submit(function() {
		if ($('#overhaul select#km option:selected, #overhaul-form select#km option:selected').val() == '-1' && $('#overhaul select#years option:selected, #overhaul-form select#years option:selected').val() == '-1') {
			alert('Prosze wybrać przynajmniej jedną opcję.');
			return false;
		}
	});
	
	/*
		GALLERY lightbox
	*/
	$('#article .gallery li a').lightBox();
	$('#article a[href~="cennik.jpg"]').each(function(){
		$(this).lightBox();
	});
	
	/*
		PRODUKTY ROTATOR
	*/
	$('#products').attr('last', 0);
	$('#products-recommended').css('visibility', 'visible');
	n_img =  ($('#index').size()) ? 8 : 2;
	var all_img = $('#products li').size();
	if (n_img != all_img) {
		rotate('#products', n_img, 0);
		window.setInterval("rotate('#products', n_img, 0)", 9000);
	}
	else {
		$('#products li').show();
	}
	
	$('#promotions-static').attr('last', '0');
	$('#products-promotion').css('visibility', 'visible');
	rotate('#promotions-static', 2, 10);
	window.setInterval("rotate('#promotions-static', 2, 10)", 4000);
	
});