function initTabs() {
	var i = 0
	$('.zakladki').each(function () {
		var cont = $(this)
		var headers = $(this).find('h5.tytul')
		var tabs = $('<ul>').addClass('tabs').addClass('clearfix').prependTo($(this))
		
		var j = 0;
		$(headers).each(function () {
			var tab_container = $(this).next('div')
			tab_container.attr('id', 'tab-container-'+i+'-'+j).addClass('tab').addClass('clearfix').hide()
			var li = $('<li>').appendTo(tabs)
			var a = $('<a>').data('i', i).data('j', j).attr('href', '#').attr('id', 'tab-switcher-'+i+'-'+j).appendTo(li).click(function () {
				//alert($(this).data('i')+'-'+$(this).data('j'))
				$(this).parent().parent().find('li').removeClass('active')
				$(this).parent().addClass('active')
				$('div.tab', cont).hide()
				$('#tab-container-'+$(this).data('i')+'-'+$(this).data('j')).show()
				return false
			})
			var span = $('<span>').html($(this).html()).appendTo(a)
			$(this).remove()
			j++
		})
		
		$('ul.tabs li:first', this).addClass('active')
		$('div.tab:first', this).show()
		
		i++
	})
}

if(typeof jQuery != 'undefined') {
	jQuery(function($) {
		$.fn.extend({
			fvOSPSwiatnikiGallery: function(options) {
				var settings = $.extend({}, $.fn.fvOSPSwiatnikiGallery.defaults, options);
				var timeout = null;
				var loading = 0
				
				$('<div></div>')
					.css({position: 'absolute', top: -30, left: 20})
					.attr('id', 'indicator')
					.appendTo(settings.container+' .wrapper')
					.html('Wczytywanie zdjęcia...')
				
				setLoadIndicator = function(state) {
					if (state == true) {
						loading++
						$(settings.container).find('#indicator').stop().animate({top: 20, opacity: 1}, 600, 'easeOutElastic')
					}
					else {
						loading--
						$(settings.container).find('#indicator').stop().animate({top: -30, opacity: 0}, 1600, 'easeOutElastic')
					}
					
					//if (loading <= 0) {
						
					//} else {
					//}
				}
				
				getIndex = function(obj){
					var $p = obj.parent().children()
					return $p.index(obj)
				}
				
				getPhotoData = function(obj) {
					var vars = {
						src: $(obj).find('a').attr('href')
					}
					
					$(obj).data('loading', true)
					
					var img = new Image()
					img.onload = function () {
						
						vars.original_width  = img.width
						vars.original_height = img.height
						
						if (vars.original_height > settings.max_height) {
							vars.height = settings.max_height
							
							var proportion = vars.height*100/vars.original_height
							vars.width = vars.original_width*(proportion/100)
						} else {
							vars.width = img.width
							vars.height = img.height
						}
						
						vars.left = settings.container_width/2-vars.width/2
						
						$(obj).data('loading', false)
						setLoadIndicator(false)
						
						var imgObj = $('<div>')
							.addClass('photoPreview')
							//.addClass('current')
							.attr('id', 'photoPreview'+getIndex(obj))
							.css({
								'left'   : settings.container_width/2-vars.width/2,
								'top'    : vars.height+(2*settings.container_padding),
								'width'  : vars.width
							})
							.append('<img src="'+vars.src+'" alt="Podgląd zdjęcia" />')
							.appendTo(settings.container+' .wrapper')
							.hide()
						
						pushPhoto(obj, vars)
						
					}
					
					setLoadIndicator(true)
					img.src = vars.src
					
					$(obj).data('vars', vars)
					return vars
				}

				initGalleryButtons = function() {
					
					var btnGalleryContainer = $('<div></div>')
						.css({position: 'absolute', 'z-index': 380})
						.attr('id', 'btnGalleryContainer')
						.appendTo('.viewport-gallery #intro .wrapper')
					
					$('<a href="#">odtwórz pokaz</a>')
						.attr('id', 'btnGalleryPlay')
						.appendTo('#btnGalleryContainer')
						.click(function () {
							/*if (galleryRunning == false) {
								clearTimeout(galleryTimeout)
								galleryTimeout = setTimeout('shuffleGalleryImages()', 4000)
								galleryRunning = true
							}*/
							clearTimeout(timeout)
							settings.play = true
							shuffleImages()
							return false
						})
					$('<a href="#">zatrzymaj</a>')
						.attr('id', 'btnGalleryPause')
						.appendTo('#btnGalleryContainer')
						.click(function () {
							/*if (galleryRunning == true) {
								clearTimeout(galleryTimeout)
								galleryRunning = false
							}*/
							clearTimeout(timeout)
							settings.play = false
							return false
						})
					$('<a href="#">poprzednie</a>')
						.attr('id', 'btnGalleryPrevious')
						.appendTo('#btnGalleryContainer')
						.click(function () {
							/*galleryDirection = 'left'
							galleryShowImage(galleryImagesCurrent-1)*/
							settings.direction = 'left'
							shuffleImages()
							return false
						})
						
					$('<a href="#">następne</a>')
						.attr('id', 'btnGalleryNext')
						.appendTo('#btnGalleryContainer')
						.click(function () {
							/*galleryDirection = 'right'
							galleryShowImage(galleryImagesCurrent+1)*/
							settings.direction = 'right'
							shuffleImages()
							return false
						})
						
					$('.viewport-gallery #intro .wrapper').hover(
						function () {
							$(btnGalleryContainer).stop().animate({opacity: 100})
							$(this).mousemove(function (e) {
								$(btnGalleryContainer).stop().animate({'top': e.pageY-$('#intro').offset().top-14}, 1)
							})
						},
						function () {
							$(btnGalleryContainer).stop().animate({opacity: 0})
							$(btnGalleryContainer).stop().animate({
								'top': $('#intro').height()/2-$(btnGalleryContainer).height()/2
							}, 1000, 'easeOutElastic')
						}
					)
					
					$('#btnGalleryContainer a').ifixpng({pixel: '/static/frontend/images/pixel.gif'})
				}
				
				displayPhoto = function(obj) {
					// Nie ładuj ponownie
					if ($(obj).data('loading') == true) { return false }
					
					var vars = $(obj).data('vars')
					if (typeof vars == 'undefined') {
						getPhotoData(obj)
					}
					else {
						pushPhoto(obj, vars)
					}
				}
				
				nextPhoto = function() {
					var next = $('li.'+settings.photo_class+'.current').next()
					var first = $('li.'+settings.photo_class+':first')
					//var last = $('li.'+settings.photo_class+'.current:first')
					settings.direction = 'right'
					
					if (next.size() == 0) {
						return first
					}
					return next
				}

				prevPhoto = function() {
					var prev = $('li.'+settings.photo_class+'.current').prev()
					//var first = $('li.'+settings.photo_class+'.current:first')
					var last = $('li.'+settings.photo_class+':last')
					settings.direction = 'left'
					if (prev.size() == 0) {
						return last
					}
					return prev
				}
				
				shuffleImages = function() {
					//alert($(this).find('li.current').size())
					
					if (settings.direction == 'right') {
						displayPhoto(nextPhoto())
						//displayPhoto($('li.'+settings.photo_class+'.current').next())
					} else {
						displayPhoto(prevPhoto())
						//displayPhoto($('li.'+settings.photo_class+'.current').prev())
					}
				}
				
				pushPhoto = function(obj, vars) {
					
					var previous = $('.'+settings.photo_class+'.current')
					$(previous).css({'z-index': 1})
					$(obj).css({'z-index': 20})
					$('.'+settings.photo_class).removeClass('current')
					$(obj).addClass('current')
					
					// Nie animuj jeśli wyświetlamy aktualne zdjęcie
					if ($(settings.container+' .wrapper').find('.photoPreview.current img').attr('src') == vars.src) { return false }
					
					if (settings.direction == 'right') {
						
						$(settings.container+' .wrapper').find('.photoPreview.current').removeClass('current').stop().animate({top: -vars.height-(2*settings.container_padding)}, 500, 'easeOutSine', function () {
							$(this).hide()
						})
						
						$(settings.container+', '+settings.container+' .wrapper').stop().animate({height: (4*settings.container_padding)+vars.height}, 1000, 'easeOutSine')

						var img = $('#photoPreview'+getIndex(obj))
							.addClass('current')
							.hide()
							.stop()
							.css({top: (2*settings.container_padding)+vars.height, height: vars.height})
							.animate({top: settings.container_padding, height: vars.height}, 1700, 'easeOutElastic')
						$('img', img).css({height: vars.height, width: vars.width})
						
					} else {
						
						$(settings.container+' .wrapper').find('.photoPreview.current').removeClass('current').stop().animate({top: settings.max_height+(2*settings.container_padding)}, 500, 'easeOutSine', function () {
							$(this).hide()
						})
						
						$(settings.container+', '+settings.container+' .wrapper').stop().animate({height: (4*settings.container_padding)+vars.height}, 1000, 'easeOutSine')
						
						var img = $('#photoPreview'+getIndex(obj))
							.addClass('current')
							.hide()
							.stop()
							.css({top: -(2*settings.container_padding)-vars.height, height: vars.height})
							.animate({top: settings.container_padding, height: vars.height}, 1700, 'easeOutElastic')
							
						$('img', img).css({height: vars.height, width: vars.width})
						
					}
					
					if (getIndex(obj) > getIndex(previous) && ! $(obj).is(':first') && ! $(obj).is(':last')) {
						settings.direction = 'right'
					} else if (getIndex(obj) <= getIndex(previous) && ! $(obj).is(':first') && ! $(obj).is(':last')) {
						settings.direction = 'left'
					}
					
					clearTimeout(timeout)
					if (settings.play == true) {
						timeout = setTimeout("shuffleImages()", settings.timeout)
					}
					
				}
				
				return this.each(
						function() {
							if($.fn.jquery < '1.2.6') { return; }
							var $t = $(this);
							var o = $.metadata ? $.extend({}, settings, $t.metadata()) : settings;
							
							$('<div></div>').attr('id', 'mlody').html('&nbsp;').appendTo('.viewport-gallery #content')
							$('#mlody').ifixpng({pixel: '/static/frontend/images/pixel.gif'})
							
							$('.viewport-gallery #link-galleries').addClass('active')
							
							var photos = $t.find('.'+o.photo_class)
							o.count = photos.size()
							
							photos.each(function () {
								$(this).click(function () {
									displayPhoto($(this))
									return false
								})
							})
							
							initGalleryButtons()
							displayPhoto($(this).find('li:first'))
						} // function
				) // return
				
			} // fvOSPSwiatnikiGallery
		}) // fn.extend
		
		$.fn.fvOSPSwiatnikiGallery.defaults = {
			photo_class: 'gallery-photo',
			direction: 'right',
			max_height: 400,
			timeout: 9000,
			container: '#intro',
			container_width: 960,
			container_padding: 20,
			play: true
		} // defaults
	}) // jQuery
}

$(function () {
	
	/*$('#submenu-articles').each(function () {
		var _height = 0
		$('li', this).each(function () { _height = _height + $(this).height() })
		$(this).data('height', _height).css({height: 0, opacity: 0, overflow: 'hidden'})
	})*/
	initTabs()
	$.ifixpng('/static/frontend/images/pixel.gif')
	$('#osp, #banner-zosprp img, #puchar, #submenu-articles img').ifixpng()
	
	$(".news-gallery li a, a[rel^='prettyPhoto']").prettyPhoto();
	
	//$.sifr({ path: '/static/frontend/flash/' });
	$('h2#header-').sifr({ path: '/static/frontend/flash/', font: 'sifr', color: '#e80000', fontSize: '16pt' });
	
	$('body:not(.viewport-gallery) #intro .wrapper').flash(
			{ src: '/static/frontend/flash/promotion.swf',
				width: 960,
				height: 230,
				wmode: 'transparent'},
				{ version: 9 }
	)
	
	$('#btn-trawy').html('')
	$('#btn-trawy').flash(
			{ src: '/static/frontend/flash/trawy.swf',
				width: 193,
				height: 130},
				{ version: 9 }
	)
	
	initImages()
	
	$('#box-latest-photos ul li').hover(
		function () {
			$(this).find('.details').stop(true).animate({'height': 'hide'}, {'duration': 0})
			$(this).find('.details').stop(true).animate({'height': '21px', 'top': '-21px'}, {'duration': 500, 'method': 'easeOutBounce'})
			$(this).find('.details').click(function () { $(this).prev().click() })
		},
		function () {
			$(this).find('.details').stop(true).animate({'height': 'hide', 'top': '+20px'}, {'duration': 100, 'method': 'easeInBounce'})
		}
	)
	
	$('.gallery li').hover(
		function () {
			$(this).addClass('hover')
		},
		function () {
			$(this).removeClass('hover')
		}
	)
	
	$('li#link-articles').hover(
		function () {
			$(this).addClass('active').addClass('expanded')
			$('#submenu-articles').stop().animate({opacity: 1.0}, 300)
			$('#submenu-articles').show().animate({height: $('#submenu-articles').data('height')}, 300, 'easeOutBounce')
		},
		function () {
			$(this).removeClass('active').removeClass('expanded')
			$('#submenu-articles').stop().animate({height: 0, opacity: 0}, 300)
		}
	)
	
	$('.list-news .news').hover(function () { $('.more', this).show() }, function () { $('.more', this).hide() })
	
	initFormComment()
	//initGallery()
	$('.gallery').fvOSPSwiatnikiGallery()
	
})

function initFormComment() {
	
	$('#form-comment').each(function () {
		$(this).load('/komentarz?'+$(this).attr('rel'), function () {
			ajaxifyFormComment(this)
			$('.buttons input', this).val('').addClass('btn-send')
			$('#puchar').css({bottom: '-30px'})
			$('#viewport-bottom').css({bottom: '-11px'})
			initImages()
		})
	})
	
}

function ajaxifyFormComment(e) {
	if (e) {
		$('form', e).ajaxForm({ target: '#form-comment', success: function () {
				ajaxifyFormComment(e)
				$('.buttons input', this).val('').addClass('btn-send')
				initImages()
			},
			beforeSubmit: function () {
				$('.buttons input', e).attr('disabled', 'disabled')
				$('form input, form textarea', e).attr('disabled', 'disabled')
			}
		})
	}
}

function initImages() {
	if ($('#viewport .wrapper').height() < 1000) {
		//$('#banner-zosprp').hide()
		$('#btn-trawy').hide()
	} else {
		//$('#banner-zosprp').show()
		$('#btn-trawy').show()
	}
}



var galleryImagesCount   = 0
var galleryImagesCurrent = 0
var galleryDirection     = 'right'
var galleryRunning       = true
var galleryTimeout       = null
var max_height           = 400

function initGallery() {
	i = 0
	galleryImagesCount = $('.gallery .gallery-photo').size()
	
	$('<div></div>').attr('id', 'mlody').html('&nbsp;').appendTo('.viewport-gallery #content')
	$('#mlody').ifixpng({pixel: '/static/frontend/images/pixel.gif'})
	
	$('.viewport-gallery #link-galleries').addClass('active')
	
	$('.gallery .gallery-photo').each(function () {
		
		var preview     = $(this)
		var imageBigSrc = $('a', this).attr('href')
		var image       = new Image()
		
		image.src    = imageBigSrc
		image.onload = function () {
			var _height = image.height
			var _width  = image.width
			
			if (_height > max_height) {
				_height = max_height
				
				var proportions = _height*100/image.height
				_width = image.width*(proportions/100)
			}
			
			$('<div>')
				.attr('id', 'photoPreview'+i)
				.addClass('photoPreview')
				.css({
					'left'   : 960/2-_width/2,
					'top'    : max_height+40,
					'width'  : _width,
					'height' : 0
				})
				.append('<img src="'+imageBigSrc+'" alt="KSRG OSP Świątniki Górne" />')
				.data('_height', _height)
				.data('_width', _width)
				.appendTo('#intro .wrapper')
				.hide()
				
			$(preview).data('relatedId', i)
			
			i++
			
			$(preview).click(function () {
				galleryShowImage(parseInt($(preview).data('relatedId')))
				return false
			})
			
			if (i == galleryImagesCount-1) {
				if (galleryImagesCount > 0) {
					initGalleryButtons()
					galleryShowImage(0)//galleryImagesCurrent)
				}
			}
		}
	})
}

function initGalleryButtons() {
	
	var btnGalleryContainer = $('<div></div>')
		.css({position: 'absolute'})
		.attr('id', 'btnGalleryContainer')
		.appendTo('.viewport-gallery #intro .wrapper')
	
	$('<a href="#">odtwórz pokaz</a>')
		.attr('id', 'btnGalleryPlay')
		.appendTo('#btnGalleryContainer')
		.click(function () {
			if (galleryRunning == false) {
				clearTimeout(galleryTimeout)
				galleryTimeout = setTimeout('shuffleGalleryImages()', 4000)
				galleryRunning = true
			}
			return false
		})
	$('<a href="#">zatrzymaj</a>')
		.attr('id', 'btnGalleryPause')
		.appendTo('#btnGalleryContainer')
		.click(function () {
			if (galleryRunning == true) {
				clearTimeout(galleryTimeout)
				galleryRunning = false
			}
			return false
		})
	$('<a href="#">poprzednie</a>')
		.attr('id', 'btnGalleryPrevious')
		.appendTo('#btnGalleryContainer')
		.click(function () {
			galleryDirection = 'left'
			galleryShowImage(galleryImagesCurrent-1)
			return false
		})
		
	$('<a href="#">następne</a>')
		.attr('id', 'btnGalleryNext')
		.appendTo('#btnGalleryContainer')
		.click(function () {
			galleryDirection = 'right'
			galleryShowImage(galleryImagesCurrent+1)
			return false
		})
		
	$('.viewport-gallery #intro .wrapper').hover(
		function () {
			$(btnGalleryContainer).stop().animate({opacity: 100})
			$(this).mousemove(function (e) {
				$(btnGalleryContainer).stop().animate({'top': e.pageY-$('#intro').offset().top-14}, 1)
			})
		},
		function () {
			$(btnGalleryContainer).stop().animate({opacity: 0})
			$(btnGalleryContainer).stop().animate({
				'top': $('#intro').height()/2-$(btnGalleryContainer).height()/2
			}, 1000, 'easeOutElastic')
		}
	)
	
	$('#btnGalleryContainer a').ifixpng({pixel: '/static/frontend/images/pixel.gif'})
}

function shuffleGalleryImages() {
	clearTimeout(galleryTimeout)
	if (galleryDirection == 'right') {
		galleryShowImage(galleryImagesCurrent+1)
	} else {
		galleryShowImage(galleryImagesCurrent-1)
	}
}

function galleryShowImage(i) {
	
	if (i < 0) { i = galleryImagesCount - 1 }
	if (i > galleryImagesCount-1) { i = 0 }
	
	if (galleryImagesCurrent == i && i != 0) { return false }
	
	if (galleryDirection == 'right') {
		$('.viewport-gallery #intro .wrapper #photoPreview'+i).css({height: 0, top: $('#photoPreview'+galleryImagesCurrent).data('_height')+100})
		$('.viewport-gallery #intro .wrapper .photoPreview:visible').stop().animate({top: -$('#photoPreview'+galleryImagesCurrent).data('_height')-100, height: 0})
		$('.viewport-gallery #intro .wrapper #photoPreview'+i).stop().animate({top: 10, height: $('#photoPreview'+i).data('_height')})
	} else {
		$('.viewport-gallery #intro .wrapper #photoPreview'+i).css({height: 0, top: -$('#photoPreview'+i).data('_height')-100})
		$('.viewport-gallery #intro .wrapper .photoPreview:visible').stop().animate({top: $('#photoPreview'+i).data('_height')+100, height: 0})
		$('.viewport-gallery #intro .wrapper #photoPreview'+i).stop().animate({top: 10, height: $('#photoPreview'+i).data('_height')})
	}
		
	$('.viewport-gallery #photoPreview'+i+' img').css({height: $('#photoPreview'+i).data('_height')})
	$('.viewport-gallery #photoPreview'+i).stop().animate({'height': $('#photoPreview'+i).data('_height'), 'width': $('#photoPreview'+i).data('_width'), top: 10}, 1000, 'easeOutSine')
	$('.viewport-gallery #intro .wrapper, .viewport-gallery #intro').stop().animate({'height': $('#photoPreview'+i).data('_height')+60}, 1000, 'easeOutSine')
	
	galleryImagesCurrent = i
	
	if (galleryRunning == true) {
		clearTimeout(galleryTimeout)
		galleryTimeout = setTimeout('shuffleGalleryImages()', 4000)
	}
}

