$(document).ready(function() {
	footerSize.resize();
	
	$('#copy-url .content .url').text(''+document.location);
	
	$(window).resize(function() {
		footerSize.resize()
	});
	
	$(".fotogalery:not(.articlegalery) .scrollable").scrollable({
		size: 1,
		prev: ".fotogalery-prev",
		next: ".fotogalery-next",
		globalNav: true,
		clickable: false
	});
	
	$(".articlegalery .galery.idsufix .scrollable").each(function(){
		var idsufix = parseInt($(this).parents('.idsufix').attr('id'));
		if(idsufix){
			$(this).scrollable({
				size: 1,
				prev: ".fotogalery-prev"+idsufix,
				next: ".fotogalery-next"+idsufix,
				globalNav: true, 
				clickable: false
			});
		}
	});
	
	$('.content_image>a').fancybox({
		speedIn : 200, 
		speedOut : 200
	});

	set_galleries_list = function(){
		$(".galeries-list:not(.big)").each(function() {
			$(this).find(".items").each(function() {
				var items = $(this).find(".item").length;
				$(this).css("width", (items * 135));
			});
		});
	
		$(".galeries-list:not(.big) .scrollable").each(function(i) {
			if($(this).hasClass('idsufix')){
				var counter = $(this).attr('id');
			}else{
				var counter = (i + 1);
			}
			$(this).scrollable({
				size: 4,
				clickable: false,
				globalNav: true,
				prev: ".fotogalery-prev" + counter,
				next: ".fotogalery-next" + counter
			});
		});
	}
	
	set_galleries_list();
	
	updateMediaComments = function(idmedia) {
		$('#send-comment').attr('idmedia', idmedia);
		
		if(!$('div.pw-window.galeryview').is(':visible')) {
			$.ajax({
				url: "/ajax.php",
				type: "POST",
				dataType: "html",
				data: "plugin_name=fotogalleries&action=get_media_comments&idmedia=" + idmedia,
				beforeSend : function() {
				},
					success: function(html) {
					$('#media-comments-list').html(html);
				}
			});
		} else {
			$('#window-send-comment').attr('idmedia', idmedia);
			$.ajax({
				url: "/ajax.php",
				type: "POST",
				dataType: "html",
				data: "plugin_name=fotogalleries&action=get_window_media_comments&idmedia=" + idmedia,
				beforeSend : function() {
				},
				success: function(html) {
					$('#window-media-comments-list').html(html);
					$('span.count_media_comments').html($('#window-media-comments-list ul.items li').length);
				}
			});
		}
	};
	
	setBigGalery = function(){
		var api1 = null;
		$(".galeries-list.big .scrollable").each(function(i) {
			if($(this).parent().parent().hasClass('idsufix')){
				var counter = $(this).parent().parent().attr('id');
			}else{
				var counter = (i + 1);
			}
			var putName = function(e) {
				if(!e){
					var visible_items = $('.galeries-list.big .scrollable').data('scrollable').getVisibleItems();
				}else{
					var visible_items = e.currentTarget.getVisibleItems();
				}
				if(visible_items){
					var item = visible_items.find('img');
					$('.fotos-header').text(item.attr('alt'));
					if(item.attr('alt')){
						window.location.hash = item.attr('alt');
					}
					if(parseInt(item.attr('rating'))>=0 && item.attr('idmedia')){
						var val = (item.attr('rating')>0 ? item.attr('rating')-1 : '');
						$('.rating-form-value input').rating('select',val);
						$('.rating-form-value').attr('id', 'rating-form-idmedia-'+item.attr('idmedia')).attr('name', 'rating-form-idmedia-'+item.attr('idmedia'));
					}
	
					updateMediaComments(item.attr('idmedia'));
				}
			};
			api1 = $(this).scrollable({
				size: 1,
				clickable: false,
				globalNav: true,
				api: true,
				prev: ".fotogalery-prev" + counter,
				next: ".fotogalery-next" + counter,
				onSeek : putName 
			});
			if($('#big-gallery-view').length && api1){
				var urlparam = new String(window.location.hash);
				urlparam = urlparam.replace('#comments', '');
				urlparam = urlparam.replace('#', '');
				
				if(urlparam){
					var items = $(this).find('.items').find('img[alt*='+urlparam+'], img[src*='+urlparam+'], img[title*='+urlparam+']');
					if(items.length){
						items = items.first();
						if(items.parent().is('.item')){
							if(items.parent().index()!=0){
								api1.seekTo(items.parent().index());
							}else{
								putName();
							}
						}
					}
				}else{
					putName();
				}
			}
		});
		return api1;
	}
	setBigGalery();
	
	$('a.ajaxgaleryview').live('click', function(e){
		e.preventDefault();
		var href = $(this).attr('href');
		if(href.indexOf('?')>0){
			href = href.substr(href.indexOf('?'));
		}else if(href.indexOf('&')>0){
			href = href.substr(href.indexOf('&'));
		}
		if(href.indexOf('#')>0){
			var img = href.substr(href.indexOf('#'));
			window.location.hash = img;
			href = href.replace(img, '');
		}
		$.ajax({
			url: "/ajax.php",
			type: "POST",
			dataType: "xml",
			data: "plugin_name=fotogalleries"+href,
			beforeSend : function() {
				$.fancybox.showActivity();
			},
			success: function(xml) {
				var sections = [];
				$(xml).find('galery section').each(function(){
					sections.push($(this).text());
				});
				openPwWindow({
					'header' : $(xml).find('galery header').text(),
					'headerclasses' : ['fotos-header'], 
					'sections' : sections, 
					'footer' 	: $(xml).find('galery footer').text(), 
					'wide' 		: true, 
					'windowclasses' : ['galeryview'] 
				}, {
					'onstart' : function(){ 
									setBigGalery(); 
									$('input[type=radio].star').rating(); 
									if(typeof set_FM == 'function'){ 
										set_FM('.pw-window.galeryview'); 
									}
									$.fancybox.hideActivity();
									updateGalleryNav();
								}
				});
			}
		});
	});
	
	$('.giveAttention').die().live('click', function(e){
		e.preventDefault();
		var button = $(this);
		openPwWindow({
			'header' : 'Zgłoś '+(button.hasClass('abuse')?'nadużycie':'uwagę'), 
			'sections' : ['<div class="give-attention-form"><form id="giveAttentionForm"><input type="hidden" name="stype" value="'+(button.hasClass('abuse')?'abuse':'standard')+'" /><span class="info">E-mail</span><br /><input type="text" name="semail" /><br /><br /><span class="info">Komentarz</span><br /><textarea name="scomment"></textarea></form></div>'],
			'footer' 	: '<div id="btn-cancle-answer" class="button left"><div class="red"><div class="button-wrapper-left"><div class="button-wrapper-right"><a href="#" class="close">Anuluj</a></div></div></div></div><div id="btn-send-answer" class="button right">				<div class="green"><div class="button-wrapper-left"><div class="button-wrapper-right"><a href="#" class="send-comment">Wyślij</a></div></div></div></div><div class="clear"></div>',
			'wide' 		: false,
			'windowclasses' : ['giveAttentionWindow'] 
		}, {
			'onstart' : function(){
				$('.giveAttentionWindow .send-comment').click(function(e){
					e.preventDefault();
					var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
					if($('#giveAttentionForm input[name=semail]').val() && $('#giveAttentionForm textarea[name=scomment]').val() && reg.test($('#giveAttentionForm input[name=semail]').val())!=false){
						$.ajax({
							url: "/ajax.php",
							type: "POST",
							dataType: "json",
							data: "plugin_name=give_attention&surl="+document.location+'&'+$('#giveAttentionForm').serialize(),
							beforeSend : function() {
								$.fancybox.showActivity();
							},
							success: function(json) {
								$.fancybox.hideActivity();
								if(json.added){
									openPwWindow(
									{
										'header' : 'Zgłaszanie uwag', 
										'sections' : ['Dziękujemy za zgłoszenie']
									}
									);
								}else{
									openPwWindow(
									{
										'header' : 'Zgłaszanie uwag', 
										'sections' : ['Złożyłeś już zgłoszenie na tej stronie']
									}
									);
								}
							}
						});	
					}else{
						if(!$('#giveAttentionForm input[name=semail]').val() || reg.test($('#giveAttentionForm input[name=semail]').val())==false){
							$('#giveAttentionForm input[name=semail]').addClass('error');
						}else{
							$('#giveAttentionForm input[name=semail]').removeClass('error');
						}
						if(!$('#giveAttentionForm textarea[name=scomment]').val()){
							$('#giveAttentionForm textarea[name=scomment]').addClass('error');
						}else{
							$('#giveAttentionForm textarea[name=scomment]').removeClass('error');
						}
					}
				});
			}
		});
	});

	var article_pagination = $('#pagesCounter[class^=PB_]');
	if(article_pagination.length){
		var pagebreak = article_pagination.attr('class').replace('PB_', '');
		var pagePrev = article_pagination.find('.pagePrev');
		var pageNext = article_pagination.find('.pageNext');
		var pages = article_pagination.find('.pageNumerator').length;
		article_pagination.find('.pageNumerator').click(function(e){
			e.preventDefault();
			var i = $(this).attr('id').replace('pageNo', '');
			if(i!=0) 		 pagePrev.removeClass('disabled');
			else 	 		 pagePrev.addClass('disabled');
			if(i==(pages-1)) pageNext.addClass('disabled');
			else 	 		 pageNext.removeClass('disabled');
			article_pagination.find('.pageNumerator.current').removeClass('current');
			$(this).addClass('current');
			$("."+pagebreak+":visible").fadeOut("fast", function(){
			    //$('html,body').animate({scrollTop: ($('.article-header').offset().top-10)}, 200);
				$("."+pagebreak+":eq("+i+")").fadeIn('fast');
			});
		});
		pagePrev.click(function(e){
			e.preventDefault();
			var i = $("."+pagebreak).index($("."+pagebreak+":visible"));
			if(i!=0){
				$('#pageNo'+(i-1)).click();
			}
		}).addClass('disabled');
		pageNext.click(function(e){
			e.preventDefault();
			var i = $("."+pagebreak).index($("."+pagebreak+":visible"));
			if((i+1)<pages){
				$('#pageNo'+(i+1)).click();
			}
		});
	}

	$("#comments .see-more a").toggle(function() {
		$(this).parents(".text").find(".comment").css({
			"height": "auto",
			"overflow": "auto"
		});
		
		$(this).find("img").attr("src", "img/faq-arrow-close.png");
		return false;

	}, function() {
		$(this).parents(".text").find(".comment").css({
			"height": "30px",
			"overflow": "hidden"
		});

		$(this).find("img").attr("src", "img/faq-arrow-open.png");
		return false;
	});
	
	$('a.preventDefault').click(function(e){
		e.preventDefault();
	});
	
	$('.ad').each(function(){
		if(!$(this).find('img:visible, div:visible, iframe:visible, object:visible, embed:visible').length){
			$(this).addClass('empty');
		}
	});
	
	$('.ad-push-wrapper').each(function(){
		if(!$(this).find('img:visible, iframe:visible, object:visible, embed:visible').length){
			$(this).addClass('empty');
		} else {
			$(this).css("position", "relative");
			$(this).css("height", "120px");
			$(this).css("overflow", "visible");
		}
	});
	
	$('.ad-push-wrapper .ad-push').each(function(){
		if($(this).find('img:visible, iframe:visible, object:visible, embed:visible').length && !$('#ad-billboardpush').length){
			this.id = 'ad-billboardpush';
			$(this).css("height", "100px");
		}
	});
	
	//Okienka
	$('.pw-window-open').fancybox({
		modal : true,
		padding : 0,
		margin : 0, 
		titleShow : false,
		opacity : true,
		centerOnScroll : false,
		overlayOpacity : 0.6,
		overlayColor : '#000',
		scrolling : false, 
		onComplete : function(){
			$($('#fancybox-inner input[type=text], #fancybox-inner textarea')[0]).focus();
			$('embed, object, select').css('visibility', 'hidden');
			$('.pw-window-open embed, .pw-window-open object, .pw-window-open select').css({ 'visibility' : 'visible' });
		}, 
		onClosed : function() {
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
	});
	$('.pw-window .close').live('click', function(e){
		e.preventDefault();
		$.fancybox.close();
	});
	openPwWindow = function(content, callback){
		if(!callback){
			callback = {};
		}
		if(!callback.onclose){
			callback.onclose = function() { };
		}
		if(!callback.onstart){
			callback.onstart = function() { };
		}
		var addclass='';
		if(content.wide){
			addclass=' wide';
		}
		if(content.windowclasses){
			$.each(content.windowclasses, function() {
				addclass += ' '+this;
			});
		}
		var addheaderclass = '';
		if(content.headerclasses){
			$.each(content.headerclasses, function() {
				addheaderclass += ' '+this;
			});
		}
		
		var htmlcontent = '<div class="pw-window'+addclass+'"><div class="header"><h2 class="'+addheaderclass+'">'+content.header+'</h2><a href="#" class="close">Zamknij to okno</a></div>';
		if(content.sections){
			$.each(content.sections, function() {
            	htmlcontent += '<div class="content section">'+this+'</div>';
        	}); 
		}
		if(content.footer){
			htmlcontent += '<div class="footer section">'+content.footer+'</div>';
		}
		htmlcontent += '</div>';
		
		$.fancybox(
			htmlcontent,
			{
				modal : true,
				padding : 0,
				margin : 0, 
				titleShow : false,
				opacity : true,
				centerOnScroll : false,
				overlayOpacity : 0.6,
				overlayColor : '#000',
				scrolling : false, 
				//onStart : callback.onstart, 
				onComplete : function(){
					callback.onstart();
					$($('#fancybox-inner input[type=text], #fancybox-inner textarea')[0]).focus();
					$('embed, object, select').css('visibility', 'hidden');
					$('.pw-window embed, .pw-window object, .pw-window select').css({ 'visibility' : 'visible' });
				},
				onClosed : function() {
					callback.onclose();
					$('embed, object, select').css({ 'visibility' : 'visible' });
				}
			}
		);
	}
	//////////////////////////////////


	// Komentarze w okienkach
	$('.window-show-comments').live('click', function(e) {
		e.preventDefault();

		if($('.window-return-to-gallery').length > 0) {
			$('.window-return-to-gallery').addClass('window-add-comment');
			$('.window-return-to-gallery').html('+ Dodaj komentarz');
			$('.window-return-to-gallery').removeClass('window-return-to-gallery');
		}

		if($('.window-return-to-comments').length > 0) {
			$('.window-return-to-comments').addClass('window-add-comment');
			$('.window-return-to-comments').html('+ Dodaj komentarz');
			$('.window-return-to-comments').removeClass('window-return-to-comments');
		}		
		
		new bmPagination('main-section-comments', 3);
		$(this).addClass('window-hide-comments');
		$(this).html('Powrót');
		$(this).removeClass('window-show-comments');
		$(this).parent().parent().find('.main-section-content').hide();
		$(this).parent().parent().find('.main-section-add-comment').hide();
		$(this).parent().parent().find('.main-section-comments').fadeIn();
		
	});
	
	$('.window-hide-comments').live('click', function(e) {
		e.preventDefault();
		
		$(this).addClass('window-show-comments');
		$(this).html('Wasze komentarze (<span class="count_media_comments">0</span>)');
		$(this).removeClass('window-hide-comments');
		
		$(this).parent().parent().find('.main-section-add-comment').hide();
		$(this).parent().parent().find('.main-section-comments').hide();
		$(this).parent().parent().find('.main-section-content').fadeIn();

		if($('.window-return-to-gallery').length > 0) {
			$('.window-return-to-gallery').addClass('window-add-comment');
			$('.window-return-to-gallery').html('+ Dodaj komentarz');
			$('.window-return-to-gallery').removeClass('window-return-to-gallery');
		}

		if($('.window-return-to-comments').length > 0) {
			$('.window-return-to-comments').addClass('window-add-comment');
			$('.window-return-to-comments').html('+ Dodaj komentarz');
			$('.window-return-to-comments').removeClass('window-return-to-comments');
		}
		
	});

	// Komentarze w okienkach
	$('.window-add-comment').live('click', function(e) {
		e.preventDefault();
		
		if($(this).hasClass('logged-out')) {
			$('.pw-window-open[href=#login-box]').click();
		} else {
			if($('.window-hide-comments').length > 0) {
				$(this).addClass('window-return-to-comments');
				$(this).html('Powrót do listy komentarzy');
				$(this).removeClass('window-add-comment');
			} else {
				$(this).addClass('window-return-to-gallery');
				$(this).html('Powrót');
				$(this).removeClass('window-add-comment');
			}
		}
		
		$(this).parent().parent().find('.main-section-content').hide();
		$(this).parent().parent().find('.main-section-comments').hide();
		$(this).parent().parent().find('.main-section-add-comment').fadeIn();
		
	});

	
	
	$('.window-return-to-gallery').live('click', function(e) {
		e.preventDefault();
		
		$(this).addClass('window-add-comment');
		$(this).html('+ Dodaj komentarz');
		$(this).removeClass('window-return-to-gallery');
		
		$(this).parent().parent().find('.main-section-add-comment').hide();
		$(this).parent().parent().find('.main-section-comments').hide();
		$(this).parent().parent().find('.main-section-content').fadeIn();
		
	});

	
	
	$('.window-return-to-comments').live('click', function(e) {
		e.preventDefault();
		
		new bmPagination('main-section-comments', 3);
		$(this).addClass('window-add-comment');
		$(this).html('+ Dodaj komentarz');
		$(this).removeClass('window-return-to-comments');
		
		$(this).parent().parent().find('.main-section-add-comment').hide();
		$(this).parent().parent().find('.main-section-content').hide();
		$(this).parent().parent().find('.main-section-comments').fadeIn();
		
	});
	
	$('.see-more-comment a').live('click', function(e) {
		e.preventDefault();
	});
	
	
	// Oceny w okienkach
	$('#fancybox-outer .rating .star').live('click', function() {
		var formid = $(this).parents().find('form').first().attr('id');
		var is_media = formid.match("idmedia") ? true : false;
		if(is_media) {
			var idmedia = formid.replace('rating-form-idmedia-', '');
		} else {
			var idvalue = formid.replace('rating-form-idvalue-', '');
		}
		var votevalue = $("input[name='star2']:checked").val();
		votevalue = votevalue ? votevalue : 0;
		$.ajax({
			url: "/ajax.php",
			type: "POST",
			data: "plugin_name=new_rating&action=rate_article&formid=" + formid + (is_media ? ("&idmedia=" + idmedia) : ("&idvalue=" + idvalue)) + "&votevalue=" + votevalue,
			beforeSend: function() {},
			success: function(xml) {
				var formid = $("formid", xml).text();
				var status = $("status", xml).text();
				var average = $("average", xml).text();
				// wyświetlenie odpowiedniego komunikatu w zależności od statusu powodzenia
				if(status == 1) {
					openPwWindow({'header':'Głos oddany', 'sections': ['Dziękujemy za oddanie głosu']});
				} else if(status == -1) {
					//openPwWindow({'header':'Głos nieważny', 'sections': ['Tylko zalogowani użytkownicy mogą oddawać głosy']});
					$('.pw-window-open[href=#login-box]').click();
				} else if(status == -2) {
					openPwWindow({'header':'Błąd', 'sections': ['Wystąpił błąd przy oddawaniu głosu']});
				} else if(status == -3) {
					openPwWindow({'header':'Głos nieważny', 'sections': ['Użytkownik może oddać tylko jeden głos']});
				}
			},
			complete: function() {}
		});
	});
	
	$('.window-send-comment').live('click', function(e) {
		e.preventDefault();

		var idmedia = $(this).attr('idmedia');
		var sComment = $('#window-comment-content').val();

		if(sComment.length > 0) {
			$.ajax({
				url: "/ajax.php",
				type: "POST",
				data: "plugin_name=new_comment&action=send_media_comment&idmedia=" + idmedia + "&scomment=" + sComment,
				beforeSend: function() { },
				success: function(html) {
					if(html == '1') {
						openPwWindow({'header':'Komentarz wystawiony', 'sections': ['Dziękujemy za wystawienie komentarza. Wkrótce pojawi się on na stronie']});
					} else if(html == '-1') {
						openPwWindow({'header':'Nie dodano komentarza', 'sections': ['Aby wystawić komentarz trzeba być zalogowanym']});
					} else if(html == '0') {
						openPwWindow({'header':'Nie dodano komentarza', 'sections': ['Nie powiodło się zapisywanie komentarza']});
					}
				},
				complete: function() { }
			});
		} else {
			$('#window-comment-alert').html('<span style="color: #f00;">Nie podano treści komentarza</span>');
		}
	});
	
	$('.window-close').live('click', function(e) {
		e.preventDefault();
		if($('.window-return-to-gallery').length > 0) {
			$('.window-return-to-gallery').click();
		}

		if($('.window-return-to-comments').length > 0) {
			$('.window-return-to-comments').click();
		}
	});
	
	// Komentarze w okienkach
	
	
	$('a.addtofavorites[href]').live('click', function(e){
		e.preventDefault();
		
		if($(this).hasClass('logged-out')) {
			$('.pw-window-open[href=#login-box]').click();
		} else {
			var idvalue = parseInt($(this).attr('href'));
			$.ajax({
				url: "/ajax.php",
				type: "POST",
				dataType: "json",
				data: "plugin_name=add_to_favorites&idvalue="+idvalue,
				beforeSend : function() {
					$.fancybox.showActivity();
				},
				success : function(json) {
					openPwWindow(
						{'header' : 'Dodawanie do ulubionych', 'sections' : [json.info]}, 
						{'onstart' : function(){
							$.fancybox.hideActivity();
						}}
					);
				}
			});
		}
	});
	
	//////////////////////////////////
	
	$('form input').keypress(function(e){
		if(e.keyCode == '13'){
			$(this).submit();
		}
	});
	
	loginCallback = function(){
		if($('.star').length > 0 || $('.reservation-link').length > 0 || $("a:contains('Dodaj opinię')") ) {
			location.reload();
		}
	};
	
	//Login box
	$('#login-box .button .green a').click(function(){
		$('#login-box .login-form').submit();
	});
	$(".login-form").submit(function() {
		$.fancybox.showActivity();
		var form = $('#login-box .login-form');
		if(!form.find('#slogin').val()){
			form.find('#slogin').addClass('error');
			$.fancybox.hideActivity();
		}else if(!form.find('#spassword').val()){
			form.find('#slogin').removeClass('error');
			form.find('#spassword').addClass('error');
			$.fancybox.hideActivity();
		}else{ 
			form.find('#slogin, #spassword').removeClass('error');
			var result = user.loginUser('#login-box .login-form');
			if(result){
				$("#user-area").html($(result).html());
				loginCallback();
				$.fancybox.close();
			}else{
				$('#login-box .messages').text('Niepoprawny login lub hasło').fadeIn('fast', $.fancybox.resize).delay(4000).fadeOut('fast', $.fancybox.resize);
			}
			$.fancybox.hideActivity();
		}
		return false;
	});
  //User profile
  /*$('#user-area .login-button').click(function(){
    $('#user-area #user-area-inner .user-avatar, #user-area #user-area-inner .user-actions').hide();
    $('#user-area #user-area-inner .login-form').show();
  });*/
  /*$("#form_login_user").submit(function() {
    user.loginUser();
    return false;
  });
  $("#form_login_user input").keypress(function (e) {  
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
      $('#btn_login_user a').click();  
      return false;  
    }else{  
      return true;  
    }  
  });  
  $('#btn_login_user a').click(function(){
    $(this).parents('form').submit();
  });*/
  ////////////////////////////////////////////////////////////////
	//////////////////////////////////
	
	//MainSearchPanel
	//-Tips
	$('#search-tips-button').click(function(e) {
		e.preventDefault();
		$('#search-panel-poi').fadeTo('normal', 0);
                $('#search-panel-poi .submit-group.left').fadeTo('normal', 0);
		$('#search-tips-options').fadeIn('fast');
                var p = $('#search-panel-poi-tab-content').position();
                $('#search-tips-options').css("left", p.left+"px").css("top", p.top+"px");
	});
	$('#search-tips-button-clicked img').click(function(e) {
		e.preventDefault();
		$('#search-panel-poi').fadeTo('normal', 1);
                $('#search-panel-poi  .submit-group.left').fadeTo('normal', 1);
		$('#search-tips-options').fadeOut();
	});
	
	$('#search-tips-options .tab1 .tabfooter .submit').click(function(){
		var form = $(this).parent().parent().find('.form form');
		var tags = [];
		$('#search-tips-options .tab1 .tabcontent .tag.selected').each(function(){
			tags.push($(this).text());
		});
		if(tags.length){
			form.find('input[name=tagi]').remove();
			$('<input type="hidden" name="tagi" value="'+tags+'" />').appendTo(form);
			form.submit();
		}else{
			openPwWindow({
				'header' : 'Wskazówka', 
				'sections' : [
					'Aby wyszukać wybierz kliknięciem typ wypoczynku. <br />Możesz dodatkowo wpisać nazwę miejscowości i określić obszar poszukiwań.'
				]
			});
		}
	});
	$('#search-tips-options .tab1 .tabfooter .form form').submit(function(){
		if($(this).find('input[name=tagi]').length && $(this).find('input[name=tagi]').val()){
			return true;
		}else{
			$('#search-tips-options .tab1 .tabfooter .submit').click();
			return false;
		}
	});
	
	$('#search-tips-options .tab1 .tabcontent a.tag').toggle(function(){
		$(this).addClass('selected');
	}, function(){
		$(this).removeClass('selected');
	});
	$('#search-tips-options .tips-tabs-menu .t1, #search-tips-options .tips-tabs-menu .t2').click(function(e){	
		e.preventDefault();
		$('#search-tips-options .tips-tabs-menu .open').removeClass('open');
		$(this).addClass('open');
		if($(this).hasClass('t1')){
			$('#search-tips-options .tab2').hide();
			$('#search-tips-options .tab1').show();
		}else if($(this).hasClass('t2')){
			$('#search-tips-options .tab1').hide();
			$('#search-tips-options .tab2').show();
		}
	});
	//////////
	//-- Close-Open
	var main_search_panel_switch = function(){
		if(!$(this).hasClass('closed')){
			$(this).addClass('closed');
			$("#main-search-panel #search-panel-tabs ul, #main-search-panel #search-panel-form-wrapper, #main-search-panel #search-panel-poi-suggest, #main-search-panel .main-search-panel-recomended").fadeOut('fast');
		}else{
			$(this).removeClass('closed');
			$("#main-search-panel #search-panel-tabs ul, #main-search-panel #search-panel-form-wrapper, #main-search-panel #search-panel-poi-suggest, #main-search-panel .main-search-panel-recomended").fadeIn('fast');      
		}
	};
	
	$("#main-search-panel #search-panel-switch").click(main_search_panel_switch);
	if($("div.closed #main-search-panel").length!=0)
		$("#main-search-panel #search-panel-switch").click();
  //-------------
  //-- Tabs
	$('#search-panel-tabs ul li').click(function(e){
		e.preventDefault();
		$('#search-panel-tabs ul li').removeClass('active');
		$(this).addClass('active');
		var tab = parseInt($(this).find('a').attr('tab'))-1;
		$('#search-panel-poi div.open').addClass('closed').removeClass('open');
		$('#search-panel-poi>div:eq('+tab+')').addClass('open').removeClass('closed'); 
		$('div.open .multiselect.loadwithtab').multiSelect({
	        selectAllText: 'Zaznacz wszystkie',
	        noneSelected: 'Zaznacz opcje',
	        oneOrMoreSelected: '% zaznaczono'
	    });
	});
	$('#search-panel-poi div a.submit').click(function(){
		var form = $($(this).parents('form.search-panel-form')[0]);
		if(form){
			var errors = 0;
			var required_one = {
				'exists' : false,
				'counter' : 0
			};
			form.find('input').each(function(){
				if($(this).hasClass('required') && !$(this).val()){
					$(this).addClass('error');
					errors++;
				}
			});
			if(!errors){
				form.submit();
			}
		}
	});
  //
  //-- Advanced search
  $('#search-panel-poi .search-more a').click(function(e){
    e.preventDefault();
    var tab = parseInt($(this).attr('tab'))-1;
    $(this).slideUp();
    $($('#search-panel-poi .search-more-options')[tab]).slideDown().find('.multiselect').multiSelect({
        selectAllText: 'Zaznacz wszystkie',
        noneSelected: 'Zaznacz opcje',
        oneOrMoreSelected: '% zaznaczono'
    });
  });
  ////////////////////////////////////////////////////////////////
  
  //Multselect lists
  set_multiselect = function(){
    $(".multiselect").multiSelect();
  };
  ////////////////////////////////////////////////////////////////
  
	//Tags tabs
	$('#tags-search-types li a').click(function(e){
		e.preventDefault();
		var tab = $(this).attr('href').substring(1);
		$('#tags-big-cloud #grouped-tags .empty-list').hide();
		$('#tags-big-cloud #all-tags .empty-list').hide();
		
		switch (tab){
			case 'popular':	
				if(!$('#tags-big-cloud #popular-tags .tag').length){
					var maxSize = 0;
					$('#tags-big-cloud #all-tags .tag').each(function(){
						var classes = $(this).attr('class');
						classes = classes.substring(classes.indexOf('size'), (classes.indexOf('size')+5));
						var size = parseInt(classes.substring(4));
						if(size>maxSize) maxSize=size;
					});
					$('#tags-big-cloud #all-tags .tag.size'+maxSize+', #tags-big-cloud #all-tags .tag.size'+(maxSize-1)).clone().show().appendTo('#tags-big-cloud #popular-tags .inner-content');
				}
				tagGroupsShowHide("popular");
				break;
			case 'pois':
				$('#tags-big-cloud #grouped-tags .tag').hide().parent().find('.pois').show();
				
                    tagGroupsShowHide("grouped");

                    if($('#tags-big-cloud #grouped-tags .tag:visible').length==0)
                    {
                        $('#tags-big-cloud #grouped-tags .empty-list').show();
                    }
                                
				break;
			case 'places':
				$('#tags-big-cloud #grouped-tags .tag').hide().parent().find('.places').show();

                	tagGroupsShowHide("grouped");

				if($('#tags-big-cloud #grouped-tags .tag:visible').length==0)
					$('#tags-big-cloud #grouped-tags .empty-list').show();
				break;
			case 'trips':
				$('#tags-big-cloud #grouped-tags .tag').hide().parent().find('.trips').show();

                	tagGroupsShowHide("grouped");

				if($('#tags-big-cloud #grouped-tags .tag:visible').length==0)
					$('#tags-big-cloud #grouped-tags .empty-list').show();
				break;
			default:
				tagGroupsShowHide("all");
		}
		$('#tags-search-types li a.active').removeClass('active');
		$(this).addClass('active');
	});
	//
	
	//Pagination goto
	$('#pagination-go-to-page-button').click(function(){
		var field = $(this).parent().find('#pagination-go-to-page');
		if(field.val()=='' || parseInt(field.val())==0 || parseInt(field.val())>parseInt(field.attr('maxvalue'))){
			field.addClass('error');
		}else{
			field.removeClass('error');
			document.location = field.attr('linkbase')+field.val();
		}
	});
	/////////////////////////
	
	if($(".info-tooltip").parent().is('a')){
		$(".info-tooltip").parent().click(function(e){ e.preventDefault(); });
	}
	$(".info-tooltip").hover(
		function(){
			var p = $(this).position();
			var imgwidth = $(this).outerWidth();
			imgwidth = imgwidth ? imgwidth : 0;
			
			var content = "<h3>"+$(this).attr("title")+"</h3><p>"+$(this).attr("alt")+"</p>"+
			"<img src=\"/_items/_new/img/dziubek1.png\" class=\"dziubek1\" />";
		
			var box = $('<div/>', {
				"class": "click-tooltip",
				html:  content
			});
			var image = $("<img src=\"/_items/_new/img/dziubek.gif\" class=\"dziubek\" />");
			$(box).appendTo("body");
			$(image).appendTo("body");
			
			$(image).css("top",p.top-11)
				  .css("left",p.left-4+imgwidth);
			
			$(box).css("top",p.top-$(box).height()-25)
				  .css("left",p.left-4+imgwidth);
			$(box).fadeIn("normal");
			$(image).fadeIn("normal");
		}, 
		function(){
			$("img.dziubek").fadeOut("normal", function(){$(this).remove();});
			$(".click-tooltip").fadeOut("normal", function(){$(this).remove();});
		}
	);
	
	/*$('.image-wrapper img').each(function() {
		if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
			var w = $(this).width();
			switch(w){
				case 100:
					$(this).attr('src', '/_items/_upload/_files/mini/100x72_default_img.jpg');
					break;
			}
		}
	});*/
	$('.image-wrapper img').error(function(){
		$(this).unbind('error');
		var w = $(this).width();
		switch(w){
			case 100:
				$(this).attr('src', '/_items/_upload/_files/mini/100x72_default_img.jpg');
				break;
		}
	});
	
	$('.print-this').click(function(e){
		e.preventDefault();
		window.print();
	});
	
	/*************OBSLUGA SZARZENIA PRZYCISKOW DO PRZESUWANIA GALERII**********/
	if ($(".articlegalery.fotogalery .scrollable").length > 0)
	{
		var el = $(".articlegalery.fotogalery .scrollable").scrollable();
		var pi = el.getPageIndex();
		var sizes = el.getSize(); 
		
		if (pi == sizes - 1)
			$(".articlegalery.fotogalery .navigation-next.left")
				.children("img")
				.attr("src", "/_items/_new/img/buttons/fotogaleria-gray-next.png");
		if (pi == 0)
			$(".articlegalery.fotogalery .navigation-prev.left")
				.children("img")
				.attr("src","/_items/_new/img/buttons/fotogaleria-gray-prev.png");
			
		$(".articlegalery.fotogalery .navigation-next.left").click(function(){
			var el = $(".articlegalery.fotogalery .scrollable").scrollable();
			var pi = el.getPageIndex();
			var sizes = el.getSize(); 
			
			if (pi == sizes - 1)
			{
				$(this).children("img").attr("src", "/_items/_new/img/buttons/fotogaleria-gray-next.png");
			}
			if (pi != 0)
			{
				$(this).siblings(".navigation-prev")
					   .children("img")
					   .attr("src", "/_items/_new/img/buttons/fotogaleria-prev.png");
			}
		});
		$(".articlegalery.fotogalery .navigation-prev.left").click(function(){
			var el = $(".articlegalery.fotogalery .scrollable").scrollable();
			var pi = el.getPageIndex();
			var sizes = el.getSize();  
			
			if (pi != sizes - 1)
			{
				$(this).siblings(".navigation-next")
					   .children("img")
					   .attr("src", "/_items/_new/img/buttons/fotogaleria-next.png");
			}
			if (pi == 0)
			{
				$(this).children("img").attr("src","/_items/_new/img/buttons/fotogaleria-gray-prev.png");
			}
			
		});
	}
	
	jQuery.fn.activeXOverlap = function() { 
		$(this).each(function(i){
		    var h   = $(this).outerHeight();
		    var w   = $(this).outerWidth();
		    var iframe  = '<!--[if IE 6]>' +
		                  '<iframe src="javascript:false;" style="height: ' +
		                  h +
		                  'px; width: ' +
		                  w +
		                  'px" class="selectOverlap">' +
		                  '</iframe>' +
		                  '<![endif]-->'
		    $(this).prepend(iframe);
		});
	};
	
	showAdPopup = function(){
		if($('#adpopup').length){
			var embed = $('#adpopup').find('embed[src*=ankieta],object param[name=movie][value*=ankieta]');
			if(embed.length){
				if(!$.browser.msie){
					var filename = embed.attr('src');
				}else{
					var filename = embed.attr('value');
				}
				filename = new String(filename.match(/filename=(.*?\.swf)/gi));
				filename = filename.replace('filename=','pw-ad-');
				if(filename){
					if(getCookie(filename)){
						$('#adpopup').addClass('empty');
					}else{
						var exdate = new Date();
						exdate.setDate(exdate.getDate() + 5000);
						setCookie(filename, '1', exdate);
					}
				}
			}
		
			if($('#adpopup').hasClass('empty')){
				closeAdPopup();
			}else{
				$('#adpopup').css("top", ( $(window).height() - $('#adpopup').height() ) / 2+$(window).scrollTop() + "px").css("left", ( $(window).width() - $('#adpopup').width() ) / 2+$(window).scrollLeft() + "px").show();
				$('#adpopup').activeXOverlap();
				$(window).unbind('scroll');
				$(window).scroll(function () { 
					$('#adpopup').animate({'top':( $(window).height() - $('#adpopup').height() ) / 2+$(window).scrollTop() + "px"}, {queue: false, duration: 350}, "easing");
				});
				//workaround
				setTimeout("$('#fancybox-overlay').fadeTo('normal', 0.4);",100);
			}
		}
	};
	closeAdPopup = function(){
		$('#fancybox-overlay').fadeTo('normal', 0).hide();
		$('#adpopup').remove();
		$(window).unbind('scroll');
	};
	showAdPopup();
	
	$('#big-gallery-view img[class*="fotogalery-prev"], #big-gallery-view img[class*="fotogalery-next"]').live('click', function() {
		updateGalleryNav();
	});
	
	$('.galleries_pag_items img[class*="fotogalery-prev"], .galleries_pag_items img[class*="fotogalery-next"]').live('click', function() {
		updateGalleryNav();
	});
	updateGalleryNav();

});

function tagGroupsShowHide(toShow)
{    
    var els = ["grouped","all", "popular"];

    for (var i=0; i<els.length; i++)
    {
        if (toShow == els[i])
            $('#tags-big-cloud #'+els[i]+'-tags').show();
        else
            $('#tags-big-cloud #'+els[i]+'-tags').hide();
    }
}

function getCookie(name) {
	name = name + "=";
	var carray = document.cookie.split(';');
	for(var i=0;i < carray.length;i++) {
		var c = carray[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
	}
	return null;
}

function setCookie(name, value, expire) {
	document.cookie = name + "=" + escape(value) + ((expire==null)?"" : ("; expires=" + expire.toGMTString()))+"; path=/";
}

function updateGalleryNav() {
	// Aktualizacja strzałek w galerii
	$('#big-gallery-view img:not(.disabled)[src*="/_items/_new/img/buttons/fotogaleria-next.png"]').each(function() {
		if($(this).first().parent().parent('#big-gallery-view').find('.item').length == 1) {
			$(this).addClass('disabled');
		}
	});
	
	$('#big-gallery-view img.disabled[src*="/_items/_new/img/buttons/fotogaleria-prev.png"]').each(function() {
    $(this).attr('src', '/_items/_new/img/buttons/fotogaleria-gray-prev.png');
	});
	$('#big-gallery-view img.disabled[src*="/_items/_new/img/buttons/fotogaleria-next.png"]').each(function() {
		$(this).attr('src', '/_items/_new/img/buttons/fotogaleria-gray-next.png');
	});
	$('#big-gallery-view img:not(.disabled)[src*="/_items/_new/img/buttons/fotogaleria-gray-prev.png"]').each(function() {
		$(this).attr('src', '/_items/_new/img/buttons/fotogaleria-prev.png');
	});
	$('#big-gallery-view img:not(.disabled)[src*="/_items/_new/img/buttons/fotogaleria-gray-next.png"]').each(function() {
		$(this).attr('src', '/_items/_new/img/buttons/fotogaleria-next.png');
	});
	
	// Aktualizacja strzałek na liscie galerii
	$('.galleries_pag_items img:not(.disabled)[src*="/_items/_new/img/buttons/fotogaleria-gray-next.png"]').each(function() {
		if($(this).first().parent().parent('.pag_item').find('.item').length == 4) {
			$(this).addClass('disabled');
		}
	});
	
	$('.galleries_pag_items img.disabled[src*="/_items/_new/img/buttons/fotogaleria-prev.png"]').each(function() {
		$(this).attr('src', '/_items/_new/img/buttons/fotogaleria-gray-prev.png');
	});
	$('.galleries_pag_items img.disabled[src*="/_items/_new/img/buttons/fotogaleria-next.png"]').each(function() {
		$(this).attr('src', '/_items/_new/img/buttons/fotogaleria-gray-next.png');
	});
	$('.galleries_pag_items img:not(.disabled)[src*="/_items/_new/img/buttons/fotogaleria-gray-prev.png"]').each(function() {
		$(this).attr('src', '/_items/_new/img/buttons/fotogaleria-prev.png');
	});
	$('.galleries_pag_items img:not(.disabled)[src*="/_items/_new/img/buttons/fotogaleria-gray-next.png"]').each(function() {
		$(this).attr('src', '/_items/_new/img/buttons/fotogaleria-next.png');
	});
	
	// Aktualizacja strzałek na liscie galerii w okienku
	$('#big-gallery-view img:not(.disabled)[src*="/_items/_new/img/buttons/fotogaleria-next-small.png"]').each(function() {
		if($(this).first().parent().parent('#big-gallery-view').find('.item').length == 1) {
			$(this).addClass('disabled');
		}
	});
	
	$('#big-gallery-view img.disabled[src*="/_items/_new/img/buttons/fotogaleria-prev-small.png"]').each(function() {
		$(this).attr('src', '/_items/_new/img/buttons/fotogaleria-gray-prev-small.png');
	});
	$('#big-gallery-view img.disabled[src*="/_items/_new/img/buttons/fotogaleria-next-small.png"]').each(function() {
		$(this).attr('src', '/_items/_new/img/buttons/fotogaleria-gray-next-small.png');
	});
	$('#big-gallery-view img:not(.disabled)[src*="/_items/_new/img/buttons/fotogaleria-gray-prev-small.png"]').each(function() {
		$(this).attr('src', '/_items/_new/img/buttons/fotogaleria-prev-small.png');
	});
	$('#big-gallery-view img:not(.disabled)[src*="/_items/_new/img/buttons/fotogaleria-gray-next-small.png"]').each(function() {
		$(this).attr('src', '/_items/_new/img/buttons/fotogaleria-next-small.png');
	});
}

// Rozwijalny baner reklamowy - rozwijanie/ukrywanie diva, aby pod ukrytym można było klikać w linki
function rozwinBillboard() {
	document.getElementById('ad-billboardpush').style.height = "300px"; // expanded height
}
function zwinBillboard() {
	document.getElementById('ad-billboardpush').style.height = "100px"; // normal height   
}


