var map;

$().ready(function(){
	GMapApiLoaded = false;
	elToScroll = null;

	/////////////////////////////////////////////////////////////////////////////////////
	// zastąpienie styli :hover akcją js
	/////////////////////////////////////////////////////////////////////////////////////
	$('.bbox-tematy li').hover(function(){
		//over
		$(this).addClass('hover');
	},function(){
		//out
		$(this).removeClass('hover');
	});

	$('.bbox-forum li').hover(function(){
		//over
		$(this).addClass('hover');
	},function(){
		//out
		$(this).removeClass('hover');
	});
	
	/////////////////////////////////////////////////////////////////////////////////////
	// przykłady bannerów
	/////////////////////////////////////////////////////////////////////////////////////
	$('.banner-example-button').click(function(){
		$(this).siblings('.banner-example').toggle();
	});
	$('.banner-example').click(function(){
		$(this).hide();
	});
	
	/////////////////////////////////////////////////////////////////////////////////////
	// zakładki
	/////////////////////////////////////////////////////////////////////////////////////
	
	//przewija stronę do elementu elToScroll i animuje tło tego elementu
	scrollToElem = function(elem){
		if(elem) $.scrollTo(elem, 1000, {offset: -220}); 
		else if(elToScroll){
			$.scrollTo("#"+elToScroll, 1000, {offset: -220});
		}
        
        if(elToScroll){
            var blinkDuration = 300;
            var elemToAnimate = $('#'+elToScroll);
            elemToAnimate.animate({backgroundColor: '#eeee00'}, blinkDuration);
            elemToAnimate.animate({backgroundColor: '#ffffff'}, blinkDuration);
            elemToAnimate.animate({backgroundColor: '#eeee00'}, blinkDuration);
            elemToAnimate.animate({backgroundColor: '#ffffff'}, blinkDuration);
            elemToAnimate.animate({backgroundColor: '#eeee00'}, blinkDuration);
            elemToAnimate.animate({backgroundColor: '#ffffff'}, blinkDuration);
            elemToAnimate.animate({backgroundColor: '#eeee00'}, blinkDuration);
            elemToAnimate.animate({backgroundColor: '#ffffff'}, blinkDuration);
            elemToAnimate.animate({backgroundColor: '#eeee00'}, blinkDuration);
            elemToAnimate.animate({backgroundColor: '#ffffff'}, blinkDuration);
            elemToAnimate.animate({backgroundColor: '#eeee00'}, blinkDuration);
            elemToAnimate.animate({backgroundColor: '#ffffff'}, blinkDuration);
        }
		
	};
	
	$('.tab-panel').each(function(){
		var tabBodies = $(this).find('div.tab');
		var tabH2 = $(this).find('h2.tab-h2');
		
		//usuniecie atrybutów id i zastapienie ich atrybutem class, aby przeglądarka nie przewijała strony
		tabBodies.each(function(){
			$(this).addClass('_'+$(this).attr('id'));
			$(this).removeAttr('id');
		});

		//tworzenie zakładek
		var html = [];
		html.push('<div class="tab-menu"> <div id="formularz-menu"> <div class="items">');
		tabH2.each(function(ind, elem){
			html.push('<div class="item'+($(this).hasClass('disabled')? ' disabled' : '')+'"> <p>');
			html.push('<a ');
			html.push($(this).hasClass('disabled')? '' :'href="');
			html.push($(this).hasClass('disabled')? '' : $(this).children('a').attr('href'));
			html.push($(this).hasClass('disabled')? '' : '"');
			html.push('>'+$(this).text());
			html.push('</a> </p> </div>');
		});
		html.push('</div> </div> </div>');
		$(this).prepend( html.join('') );
		
		tabsTriggers = $(this).find('div.item');
		var tabs = $(this).find('div.item');
		
		//usunięcie starych nagłówków
		tabH2.remove();
		
		//ukrycie wszystkich zakładek
		tabBodies.hide();
		
		//jeśli jakaś zakładka zawiera div.important-msg uaktywniamy ją
		var impTabBodies = tabBodies.filter(':has(.important-msg)');
		if(impTabBodies.length){
			impTabBodies.eq(0).show();
		}
		//jeśli nie ma div.important-msg, a url wskazuje na którąś zakładkę
		else if(window.location.hash){
			var hash = window.location.hash;
			hash = hash.split('|');
			var tab = $(this).find('.'+hash[0].replace('#','_'));
			if( tab.length && tab.hasClass('tab') ){
				tab.eq(0).show();
			}else tabBodies.eq(0).show();
			elToScroll = hash[1];
			if(hash[1])	setTimeout(scrollToElem, 100);
		}
		//jeśli nic nie wskazuje na jakąkolwiek zakładkę, uaktywnaimy pierwszą niepustą
		else{
            if( tabBodies.not('.empty').length ) tabBodies.not('.empty').eq(0).show();
            else tabBodies.eq(0).show();
		}
		
		syncTabs();
		
		//synchronizuje widoczność zakładek z ich zawartością 
		function syncTabs(){
			tabs.removeClass('active');
			tabs.addClass('noactive');
			tabBodies.each(function(index){
				if( $(this).is(':visible') )  tabs.eq(index).addClass('active').removeClass('noactive');
			});
		}
		
		//reakcja na click zakładki
		tabs.not('.disabled').add('a.tab-link').click(function(){
			var hash;
			var tab;
			if($(this).hasClass('tab-link')){
				hash = $(this).attr('href');
                hash = '#'+hash.split('#')[1];
				tab = $('a[href='+$(this).attr("href")+']').not('.tab-link').parents('div.item');
			}
			else {
				hash = $(this).find('a').attr('href');
                hash = '#'+hash.split('#')[1];
				tab = $(this);
			}
            
			if(!hash) return;
			tabBodies.hide();
			tabBodies.filter( '.'+hash.replace('#','_') ).show();
			tabs.removeClass('active').addClass('noactive');
			tab.removeClass('noactive').addClass('active');
			window.location.hash = hash;
		});
		
	});
	//////////////////////////////////////////////////////////////////////////////////////
	// linki do opisów składowych pakietów
	//////////////////////////////////////////////////////////////////////////////////////
	$('td.c-1').click(function(evt){
		evt.preventDefault();
		$(this).parent('tr').nextAll('tr').eq(0).find('.pakiet-desc').slideToggle('fast');
		//console.log($(this).parent('tr').nextAll('tr').eq(0).find('.pakiet-desc'));
	});
	
	///////////////////////////////////////////////////////////////////////////////////////
	// mapka google w formularzu rejestracyjnym
	///////////////////////////////////////////////////////////////////////////////////////
	
	//pokazanie mapy google w formularzu i dziale kontakt z niewielkim opóźnieniem po uaktywnieniu zakładki
	mapDivs = $('.mapDiv');
	mapDivsIndex = 0;
	shownMapDivs = [];
	if( mapDivs.length>=0 ) {
		for(var i=0; i<mapDivs.length; i++){
			//'i' zostaje później nadpisane ?
			var divIndex = i;
            
			//pobranie zakładki w której wyświetlamy mapę 
			var tabClasses = mapDivs.eq(i).parents('div.tab').attr('class').split(' ');
			var tabId;
			var tabTrigger;
			for(var j=0; j<tabClasses.length; j++){
				if(tabClasses[j]!='tab' && tabClasses[j].substr(0, 1)=='_'){
					tabId = '#'+tabClasses[j].substring(1);
					tabTrigger = $('a[href*='+tabId+']').parents('div.item').eq(0);
					//jeśli zakładka jest już aktywna wyświetlamy mapkę
					if(tabTrigger.hasClass('active')){
						mapDivsIndex = divIndex;
						if(!GMapApiLoaded) activateGMapApi();
						else delayedShowMap();
					}
					tabTrigger.mouseup(function(){
						mapDivsIndex = divIndex;
						if(!GMapApiLoaded) activateGMapApi();
						else delayedShowMap();
						
					});
				}
			}
		}
	}
	
	delayedShowMap = function(){
		if(mapDivs.hasClass('contact-map')) setTimeout('showContactMap(mapDivs.get(mapDivsIndex));', 100); 
		else if(mapDivs.hasClass('client-map')) setTimeout('showClientMap(mapDivs.get(mapDivsIndex));', 100);
		else setTimeout('showInputMap(mapDivs.get(mapDivsIndex));', 100);
	};
	
	
	/////////////////////////////////////////////////////////////////////////////////////////
	// pokazanie mapki na formularzu rejestracyjnym
	/////////////////////////////////////////////////////////////////////////////////////////
	showInputMap = function(mapEl){
		//var mapEl = document.getElementById('mapDiv');
		
		//nie wyświetlamy mapki już wyświetlonej
		if(shownMapDivs.indexOf(mapEl)!=-1)	return;
		else shownMapDivs.push(mapEl);
		
		var map;
		var marker;

		if (GBrowserIsCompatible()) {
	        map = new GMap2(mapEl);
	        map.setCenter(new GLatLng(52.281601868071434,18.7646484375), 6);
	        map.addControl(new GSmallZoomControl());
	        map.enableScrollWheelZoom();
	        GEvent.addListener(map, "singlerightclick", function(point, tileElem, overlay) {
	        	var latlng = map.fromContainerPixelToLatLng(point);
	        	if(marker) map.removeOverlay(marker);
	        	marker = new GMarker(latlng);
	        	map.addOverlay(marker);
	        	$('#registration_coords').val(latlng.lat()+','+latlng.lng());
	        });
		}
	};
	
	/////////////////////////////////////////////////////////////////////////////////////////
	// mapka google w dziale kontakt lub na wizytówce
	/////////////////////////////////////////////////////////////////////////////////////////
	showContactMap = function(mapEl){
		//var mapEl = document.getElementById('mapDiv');
		//nie wyświetlamy mapki już wyświetlonej
		if($.inArray(mapEl, shownMapDivs)!=-1)	return;
		else shownMapDivs.push(mapEl);
			
		var latlng;
		var latlng2;
		var marker;
		var imMarker;
		var geocoder = new GClientGeocoder();
		var destAddr;
		//alert('mapa:'+mapEl.getAttribute('rel'));
		var coords = mapEl.getAttribute('rel');
        
        //jeśli mamy współrzędne wyświetlimy mapkę z markerem na współrzędnych
        coords = coords.split(',');
        var coord1 = parseFloat(coords[0]);
        var coord2 = parseFloat(coords[1]);
        latlng = new GLatLng(coord1, coord2);
        //jeśli mamy zamiast współrzędnych "infomedic" wrzucamy lokację infomedic'a
		if(coords[0]=='infomedic') {
            latlng = new GLatLng(54.190848532546866,16.227750778198242);
        }
        
		geocoder.getLocations( latlng, saveDestAddr );
		if (GBrowserIsCompatible()) {
	        map = new GMap2(mapEl);
	        directions = new GDirections(map);
	        map.setCenter(latlng, 12);
	        map.addControl(new GSmallZoomControl());
	        //map.enableScrollWheelZoom();
	    	imMarker = new GMarker(latlng);
	    	map.addOverlay(imMarker);
            
	        GEvent.addListener(map, "singlerightclick", function(point, tileElem, overlay) {
	        	latlng2 = map.fromContainerPixelToLatLng(point);
	        	if(marker) map.removeOverlay(marker);
	        	marker = new GMarker(latlng2);
	        	map.addOverlay(marker);
	        	geocoder.getLocations( latlng2, showContactRoute );
	        	//$('#registration_coords').val(latlng.lat()+','+latlng.lng());
	        });
		}

		function showContactRoute(from){
			if(from && from.Placemark) directions.load('from: '+from.Placemark[0].address+' to: '+ destAddr);
			else if(from) {
				directions.load('from: '+from+' to: '+destAddr);
			}
			cityInput.siblings('.err').empty();
			setTimeout(reportAddr, 1000);
			removeContactMarkers();
		};
		function saveDestAddr(to){
			if(to && to.Placemark) destAddr = to.Placemark[0].address;
			else if(to) destAddr = to;
			
		}
		

		function removeContactMarkers(){
			if(marker) map.removeOverlay(marker);
			if(imMarker) map.removeOverlay(imMarker);
		};

		//kontakt - wyszukiwanie trasy
		var cityInput = $('input[name*=map-city]');
		var streetInput = $('input[name*=map-street]');
		$('input[value=Pokaż dojazd]').click(searchContactRoute);

		//$('#contact-map').submit(searchContactRoute);
		cityInput.keydown(quitSubmit);
		streetInput.keydown(quitSubmit);

		function quitSubmit(e) {
            if (e && e.keyCode == 13) {
            	searchContactRoute();
            	return false;
           }
           return true;
        }
		
		function searchContactRoute(){
			var city = cityInput.val();
			var street = streetInput.val();
			if(city && street) {
				showContactRoute(city+' , '+street);
				cityInput.removeClass('error');
				streetInput.removeClass('error');
			}
			else if(!city) cityInput.addClass('error');
			else if(!street) streetInput.addClass('error');
		};
		
		function reportAddr(){
			if(directions.getStatus().code==602) cityInput.siblings('.err').append('<div class="error">Nie odnaleziono podanego adresu</div>');
			
		};

	};
	
	function activateGMapApi(){
		GMapApiLoaded = true;
		var script = document.createElement("script");
		//infomedic.loc
		//script.setAttribute("src", "http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAR7Y8-8ysq_tGpuBIbWWkuBS-944qkcM3YSGIe0JBKm3srUqF1BRTkflu32LBplx2ht1EnA5jWswaxA&async=2&callback=delayedShowMap");
		//infomedic.mentax.pl
		//script.setAttribute("src", "http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAR7Y8-8ysq_tGpuBIbWWkuBS-hAsvvDwQyfmF61x59u2qldKK7RQmvoMKKWOM0BgbFBucFsSjuLZ62Q&async=2&callback=delayedShowMap");
		//infomedic.pl
        script.setAttribute("src", "http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAR7Y8-8ysq_tGpuBIbWWkuBSKP_bLYSa2vuKjHWco_afX6tT_9BQMgbF_82QktYX59qbK2CEiIjo8RA&async=2&callback=delayedShowMap");
        script.setAttribute("type", "text/javascript");


		document.documentElement.firstChild.appendChild(script);  
	}  
	
	
	//////////////////////////////////////////////////////////////////////////////
	// carousel init - przewijana galeria
	//////////////////////////////////////////////////////////////////////////////
	
	var carousel = $(".jCarouselLite").add('.jCarouselLite-cert');
	
	if(carousel.length){
		//inicjujemy galerie gdy zakładka na której się znajduje zostanie aktywowana
		tabId = carousel.parents('div.tab').attr('class').split(' ');
		if(tabId[1] && tabId[1][0]=='_') tabId = '#'+tabId[1].substring(1);
		var tabTrigger = tabsTriggers.filter(':has(a[href='+tabId+'])');
		
		if(tabTrigger.hasClass('active')) setTimeout(initCarousels, 200);
		tabTrigger.click(function(){
			initCarousels();
		});	
	}
	
	function initCarousels(){
		carousel.each(function(){
			//if($(this).find('li').length>5){
				var prev = $(this).prevAll('.prev-button').eq(0);
				var next = $(this).nextAll('.next-button').eq(0);
				$(this).jCarouselLite({
					visible: 4,
					speed:	 30,
					btnPrev: prev,
					btnNext: next
				});
			//}
		});
		
		carousel.siblings('.prev-button').hover(function(){
			$(this).css('background-position', '-30px 0');
		}, function(){
			$(this).css('background-position', '0 0');
		});
		carousel.siblings('.next-button').hover(function(){
			$(this).css('background-position', '-30px 0');
		}, function(){
			$(this).css('background-position', '0 0');
		});
		
	}
	
      
	///////////////////////////////////////////////////////////////////////////////
	// jCarouselLite - przewijana galeria zdjęć 
	///////////////////////////////////////////////////////////////////////////////
	
	//zmiana url na właściwy
	/*$('.jCarouselLite li').add('.jCarouselLite-cert li').children('a').each(function(){
		var oldSrc = $(this).attr('href');
		$(this).attr('href', infomedic.path+''+oldSrc);
		$(this).children('img').attr('src', infomedic.path+''+oldSrc);
	});*/
	
	//galerie
	imGalleries = [];
	$('.jCarouselLite').add('.jCarouselLite-cert').each(function(i){
		var galIndex = i;
		var descrBox = $(this).siblings('.carouselDesc');
		
		//obrazki w obrębie galerii
		$(this).find('img').each(function(j){
			var imgIndex;
			
			$(this).mouseover(function(){
				descrBox.text($(this).siblings('.thumbDesc').text());
			});
			
			$("a[rel^='lightbox']").slimbox({
				//loop: true,
				overlayOpacity: 0.6,
				overlayFadeDuration: 1,
				easing: "easeOutElastic",
				captionAnimationDuration: 1,
				counterText: "Obraz {x} z {y}",
				closeKeys: [27, 70],
				nextKeys: [39, 83]
			}, null, function(el) {
				return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
			});
			
		});
		
	});
	///////////////////////////////////////////////////////////////////////////////
	// Wizytówka - powiększanie logo klienta onHover
	///////////////////////////////////////////////////////////////////////////////
	function adjustClientLogo(){
		var largeLogoSize = {};
		var logo = $('.client-logo');
		var logoLarge = $('.client-logo-large');
		logo.each(function(){
			largeLogoSize.width = logoLarge.width();
			largeLogoSize.height = logoLarge.height();
			logoLarge.height($(this).height()).width($(this).width());
			logoLarge.css('left', $(this).position().left);
			logoLarge.css('top', $(this).position().top);
		});
		
		logo.mouseover(function(){
			logoLarge.stop();
			logoLarge.show();
			logoLarge.css('display', 'block');
			logoLarge.animate({
				width: largeLogoSize.width,
				height: largeLogoSize.height
			}, 500);
		});
		logoLarge.mouseout(function(){
			logoLarge.stop();
			logoLarge.animate({
				width: logo.width(),
				height: logo.height()
			}, 500, 'linear', function(){
				logoLarge.hide();
			});
		});
	};

    setTimeout(adjustClientLogo, 100);

    /*$('.tab-panel div.item:contains(Dane ogólne)').click(function(){
        setTimeout(adjustClientLogo, 100);
    });
    
    if(window.location.hash == '#dane-ogolne') setTimeout(adjustClientLogo, 100);*/

	
	///////////////////////////////////////////////////////////////////////////////
	// Wizytówka - rozwinięcie formularza oceny
	///////////////////////////////////////////////////////////////////////////////
	$('#ocen-firme').click(function(){
		$('#ocena-form').slideToggle('fast');
	});
	
	///////////////////////////////////////////////////////////////////////////////
	// Przewijanie do elementu
	///////////////////////////////////////////////////////////////////////////////
	$('.scroll-link').click(function(evt){
		evt.preventDefault();
		scrollToElem( $(this).attr('href') ); 
	});
	
	if($().slimbox){
		$("a[rel^='lightbox']").slimbox({
			loop: true,
			overlayOpacity: 0.6,
			overlayFadeDuration: 1,
			easing: "easeOutElastic",
			captionAnimationDuration: 1,
			counterText: "Obraz {x} z {y}",
			closeKeys: [27, 70],
			nextKeys: [39, 83]
		}, null, function(el) {
			return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
		});
	}
	
	
	//tablica z godzinami przyjęć - tło wierszy
	$('table.hours tr').hover(function(){
		$(this).addClass('hovered');
	}, function(){
		$(this).removeClass('hovered');
	});
	
	//
	var protTd = $('#daneTelAddr');
	var protA = $('a:contains("Włącz obsługę javaScript")');
	var protData = protTd.children('div');
	protA.attr( 'href', 'mailto:'+protData.eq(0).text()+'@'+protData.eq(1).text() );
	protA.text( protData.eq(0).text()+'@'+protData.eq(1).text() );

    //////////////////////////////////////////
    // pokazywanie/ukrywanie publikacji
    //////////////////////////////////////////
    var ajaxExpandables = $('.ajax-expandable');
    var waitMsg = 'Proszę czekać...';
    var expandMsg = 'Czytaj całość...';
    var collapseMsg = 'Schowaj...';
    aeHandler = function(){
        var body = $(this).parents('.ajax-expandable').eq(0).find('.ae-body');
        var links = $(this).parents('.ajax-expandable').find('.ae-link');

        lastAeLink = links.eq(1);

        if($(this).attr('href')){
            links.removeAttr('onclick');
            links.unbind('click');
            links.removeAttr('href');
            links.click(aeHandler);
        }
        if(body.children('*').length){
            body.slideToggle(500, function(){
                if(links.eq(1).text()==waitMsg || links.eq(1).text()==collapseMsg) links.eq(1).text(expandMsg);
                else links.eq(1).text(collapseMsg);
            });
        }else{
            links.eq(1).text(waitMsg);
        }

    };

    aeLoadedHandler = function(data){
        lastAeLink.text(collapseMsg);
        var body = lastAeLink.parents('.ajax-expandable').eq(0).find('.ae-body');
        body.hide();
        body.append(data);
        body.slideDown(500);
    };

    ajaxExpandables.find('.ae-link').click(aeHandler);


    ///////////////////////////////////////////////////////////////////////////////
    // carousel na głównej stronie
    ///////////////////////////////////////////////////////////////////////////////
    var carouselUl = $('.main-carousel');
    var carElemNo = 0;
    var carClip = $('.main-carousel-clip');
    var carWidth = carClip.width();
    var carLoop = true;
    var carInterval = 5000;
    carouselUl.append( carouselUl.children('li').eq(0).clone() );
    carouselUl.width(carWidth*(carouselUl.children('li').length+1) );
    carouselUl.children('li').width(carWidth);

    setTimeout(scrollMain, carInterval);

    carClip.click(function(){
        if(carLoop) carLoop = false;
        scrollMain();
    });

    function scrollMain(){
        carElemNo++;
        if(carElemNo>=carouselUl.children('li').length){
            carElemNo = 1;
            carouselUl.css('left', 0);
        }
        carouselUl.animate({
            left: -carElemNo*carWidth
        }, 500);
        if(carLoop) setTimeout(scrollMain, carInterval);
    }

	$(function(){
		//kasowanie atrybutu value pola hidden dla id miasta, gdy input zostanie zmodyfikowany
		var cityField = $('#autocomplete_quick_search_city');
		if(cityField.length){
			//var match = 0;
			var hidden = cityField.prev('input');
			cityField.keypress(function(e){
				var resultsLi = $('.ac_results li');
				var results = [];
				resultsLi.each(function(ind, elem){
					results.push(resultsLi.eq(ind).text());
				});
	
				if(results.indexOf(cityField.val()) == -1){
					//console.log(cityField.val(), results);
					hidden.removeAttr('value');
					//console.log('wyczyszczono...');
	
				}
			});
	
		}
	
		var dateField = $('#credit_firm_created_at');
		var adress = $('#credit_adress');
		if(dateField.length && adress.length){
			dateField.keydown(function(evt){
				if(evt.keyCode==9) adress.focus();
			});
	
		}
	});

});






