Cufon.replace('span.cufon');
Cufon.replace('nav.mainmenu ul li a');
Cufon.replace('div.board ul.nav li');
Cufon.replace('#flights ul.schedule li ul.legend li');

$(function(){
	// zegar
	var angleSec = new Array();
	var angleMin = new Array();
	var angleHour = new Array();

	for(var i=1;i<=3;++i)
		{
		$('#clock'+i+' .second').rotate(0);
		$('#clock'+i+' .minute').rotate(0);
		$('#clock'+i+' .hour').rotate(0);

		angleSec[i] = $('#clock-second'+i).val() * 6;
		angleMin[i] = $('#clock-minute'+i).val() * 6;
		angleHour[i] = ($('#clock-hour'+i).val() * 5 + $('#clock-minute'+i).val() / 12) * 6;

		$('#clock'+i+' .second').rotate(angleSec[i]);
		$('#clock'+i+' .minute').rotate(angleMin[i]);
		$('#clock'+i+' .hour').rotate(angleHour[i]);
		}

	setInterval(function()
		{
		for(var i=1;i<=3;++i)
			{
			angleSec[i] += 6;
			$('#clock'+i+' .second').rotate(angleSec[i]);

			angleMin[i] += 0.1;
			$('#clock'+i+' .minute').rotate(angleMin[i]);

			angleHour[i] += 0.004166667;
			$('#clock'+i+' .hour').rotate(angleHour[i]);
			}
		}
		,1000);

	// banner w fancyboxie
	var element = $('#banner-fancybox').html();

	if(element != null)
		{
		$.fancybox(
			element,
			{
			padding: 0,
			margin: 0,
			scrolling: 'no',
			overlayShow: false,
			centerOnScroll: true
			});
		}

	/* ajax */
	$('form.ajax').submit(function(e){
		e.preventDefault();
		$(this).find('p.error').removeClass('error');
		var ajaxStatus = $(this).find('span.ajaxstatus');
		ajaxStatus.show();
		var form = $(this);
		var ajaxResponse = $(this).find('.ajax-response');
		ajaxResponse.removeClass('error').hide();
		ajaxResponse.find('p').empty();
		ajaxResponse.find('ul').empty();
		$.ajax({
			type: 'POST',
			url: form.attr('action'),
			dataType: 'json',
			data: form.serialize(),
			success: function(data){
				if((data.saved != undefined  && !data.saved) || (data.sent != undefined  && !data.sent)){
					$.each(data,function(index, value){
						if(form.find('*[name="'+index+'"]').size() > 0 || index == 'send' || index == 'logged' || index == 'answer_id'){
							form.find('*[name="'+index+'"]').parent().addClass('error');
							ajaxResponse.find('ul').append('<li>'+value+'</li>');
						}
					});
					ajaxResponse.addClass('error');
				}else{
					if (typeof data.answers != 'undefined') {
						form.find('ul.answers').empty().addClass('results');
						$.each(data.answers_list, function(index, value){
							form.find('ul.answers').append('<li>'+value+' ('+Math.round(data.answers_votes[index]*100/data.votes_count)+'%) głosów: '+data.answers_votes[index]+'</li>');
						});
						form.find('ul.answers').after('<p class="allvotes">(ogółem głosowało: '+data.votes_count+')</p>');
						form.find('ul.answers').before('<img src="http://chart.apis.google.com/chart?chf=bg,s,65432100&amp;chco=BA222E&amp;chs=200x80&amp;chd=t:'+data.votes+'&amp;cht=p3&amp;chl='+data.answers_legend+'"/>');
						form.find('input.submit').hide();
					}
				}
				ajaxResponse.find('p').text(data.msg);
				ajaxResponse.show();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				ajaxResponse.find('p').addClass('error').text(textStatus);
				ajaxResponse.show();
			},
			complete: function(){
				ajaxStatus.hide();
			}
		});
	});

	//ocena artykułu
	$('#rate-article span.thumb').live('click',function(){
		$('#rate-article span.ajaxstatus').show();
		if(!$(this).hasClass('disabled')){
			$(this).siblings('.active').removeClass('active');
			$(this).addClass('active');
		}
		var url = $('#rate-article form').attr('action');
		var resource_type = $('#rate-article input[name="resource_type"]').val();
		var resource_id = $('#rate-article input[name="resource_id"]').val();
		if($(this).hasClass('thumb-up')){
			var rate = 1;
		}else{
			var rate = -1;
		}
		var dataString = 'resource_type='+resource_type+'&resource_id='+resource_id+'&rate='+rate;
		var ajaxResponse = $('section.rating .ajax-response');
		ajaxResponse.removeClass('error').hide();
		ajaxResponse.find('p').empty();
		ajaxResponse.find('ul').empty();
		$.ajax({
			type: 'POST',
			url: url,
			dataType: 'json',
			data: dataString,
			success: function(data){
				if(data.saved){
					$('#rate-current').text(data.rate);
					$('#rate-article span.thumb').addClass('disabled');
				}else{
					ajaxResponse.addClass('error');
				}
				if(typeof data.logged != 'undefined') ajaxResponse.find('ul').append('<li>'+data.logged+'</li>');
				ajaxResponse.find('p').text(data.msg);
				ajaxResponse.show();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				ajaxResponse.find('p').addClass('error').text(textStatus);
				ajaxResponse.show();
			},
			complete: function(){
				$('#rate-article span.ajaxstatus').hide();
			}
		});
	});

	  // Reset Font Size
	  var originalFontSize = 11;
	    $("span.resize .normal").click(function(){
	    $('section.wysiwyg').css('font-size', originalFontSize);
	  });
	  // Increase Font Size
	  $("span.resize .big").click(function(){
	    var currentFontSize = $('section.wysiwyg').css('font-size');
	    var currentFontSizeNum = parseFloat(currentFontSize, 10);
	    var newFontSize = currentFontSizeNum*1.2;
	    $('section.wysiwyg').css('font-size', newFontSize);
	    return false;
	  });
	  // Decrease Font Size
	  $("span.resize .small").click(function(){
	    var currentFontSize = $('section.wysiwyg').css('font-size');
	    var currentFontSizeNum = parseFloat(currentFontSize, 10);
	    var newFontSize = currentFontSizeNum*0.8;
	    $('section.wysiwyg').css('font-size', newFontSize);
	    return false;
	  });

	//input button
	$("input[type='button']").click(function(){
		var href = $(this).attr('data-href');
		if(typeof href != 'undefined'){
			window.location = href;
		}else{
			$(this).parents("div.box").find("div.ajax-response").show();
		}
	});
	//pagination select
	$("#perpage").change(function(){
		window.location=$("#perpage option:selected").attr('data-href');
	})

	//slider
	$("#slider-scrollable:not(.disabled)").scrollable({circular: true}).navigator({
		navi: "#slider-nav",
		naviItem: "li"
	}).autoscroll({
		interval: 5000
	});

	//banner-slider
	var easingNumber = $('#banner-breadcrumbs-slider div.cycle').attr('data-animation');

	if(easingNumber != undefined)
		{
		var fx;
		var speed;

		switch(easingNumber[0])
			{
			case '1': fx='fade'; speed=1000; break;
			case '2': fx='fadeZoom'; speed=1000; break;
			case '3': fx='blindY'; speed=1000; break;
			case '4': fx='curtainY'; speed=1000; break;
			case '5': fx='scrollUp'; speed=1000; break;
			case '6': fx='turnDown'; speed=1000; break;
			case '7': fx='wipe'; speed=1000; break;
			case '8': fx='zoom'; speed=1000; break;

			default: fx='fade'; speed=1000;
			}

		$('#banner-breadcrumbs-slider div.cycle').cycle({
			fx: fx,
			speed: speed,
			timeout: 7000,
			prev: '',
			next: '',
			pager: '#banner-breadcrumbs-slider ul.nav',
			pagerAnchorBuilder: function(idx, slide)
				{
				return '#banner-breadcrumbs-slider ul.nav li:eq('+ idx+') a';
				}
			});
		}

	//historical
	$(".historical .scrollable-historical").scrollable({circular: true}).navigator({
		navi: "nav",
		naviItem: "li"
	}).autoscroll({
		interval: 5000
	});

	//gallery
	$("div.scrollable-gallery").scrollable({circular: true});

	//important
	$("div.scrollable-important").scrollable({circular: true});

	$("aside div.box span.expand").tooltip({
		delay: 10000,
		position: 'center right',
		relative: true,
		events: {
			def: 'click,mouseout'
			}
	});
	$('#important-expand h3 a.close').click(function(){
		$("aside div.box span.expand").data('tooltip').hide();
	})


	//tabs
	$("ul.jtabs").tabs("div.jpanes > div",{current: "active", tabs: "li"});

	//tooltip
	$(".jtooltip").tooltip({
		offset: [-3, 0]
	});

    //wyszukiwarka - domyślna wartośc pola
    $("header form .text").focus(function(){
        if($(this).val() == $(this).attr("data-pattern")){
            $(this).val("");
        }
    });
    $("header form input.text").blur(function(){
        if($(this).val() == ""){
            $(this).val($(this).attr("data-pattern"));
        }
    });

    //youtube player
    if($("#yt-container").size() > 0){
	    $("#yt-container").tubeplayer({
	        width: 458,
	        height: 290,
	        initialVideo: $("#yt-initial").val()
	    });
	    $("#yt-list a").bind("click",function(){
	        $(this).parents('#yt-list').find("a.active").removeClass("active");
	        $(this).addClass("active");
	        $("#yt-container").tubeplayer("cue", $(this).attr("href").substr(31,$(this).attr("href").length));
	        var text = $(this).parent("div.item").find("p.desc").text();
        	$("#yt-description").text(text);
	        return false;
	    });
    }
    $("#yt-player-container").tubeplayer({
        width: 198,
        height: 133,
        initialVideo: $("#yt-initialVideo").val()
    });

	//fancybox
	$('a.fancybox').fancybox();

	$("section.wysiwyg a:has(img):not(.fancybox)").click(function(){
		var arr = ['jpg','gif','png']
		var ext = $(this).attr('href')
		ext = ext.substr(ext.length-3,3)
		if($.inArray(ext.toLowerCase(), arr)>=0){
			$.fancybox({
				'href' : this.href,
				'titleShow' : false,
				'hideOnContentClick' : true
			})
			return false
		} else {
			return true
		}
	});

	//history go back
	$('a.historyBack').click(function(e){
		e.preventDefault();
		history.go(-1);
	});

	//rozwijanie dropdown list
	function dropdown(selector){
	    $(selector).parent("li").siblings().find(".dropdown").slideUp(function(){
	        $(this).prev(".selected").removeClass("selected");
	    });
	    $(selector).unbind("click");
	    $(selector).toggleClass("selected");
	    $(selector).next(".dropdown").slideToggle(function(){
	        $(selector).bind("click",function(){
	            dropdown(selector);
	        });
	    });
	}

    //wybór języka
    $("nav.topmenu li.language img.roll").bind("click",function(){
        dropdown(this);
    });
    $("nav.topmenu li.language div.dropdown a").bind("click",function(){
        $(this).parent("div.dropdown").hide();
        $(this).hide();
        $(this).siblings().show();
        var alt = $(this).find("img").attr("alt");
        var src = $(this).find("img").attr("src");
        $("nav.topmenu li.language img.current").attr("alt",alt).attr("src",src);
    });

    //dropdown listy dla logowania, rejestracji, panelu usera
    $("nav.topmenu li.ext > a").bind("click",function(){
        dropdown(this);
    });

    //chowamy wszystkie dropdowny listy po opuszczeniu headera, powinno byc po czasie od opuszczenie pola
    $("nav.topmenu li.ext, nav.topmenu li.language").bind("mouseleave",function(){
        var ext = $(this);
        var slideUpTimeout = setTimeout(function(){
            ext.find("div.dropdown").slideUp(function(){
                $(this).prev(".selected").removeClass("selected");
            });
        }, 1500);
        ext.bind("mouseenter",function(){
            clearTimeout(slideUpTimeout);
        });
    });

    //user panel
    $("#user-panel").add("a.notices").add("a.firms").bind("click",function(){
        dropdown(this);
    });

	// przełączanie miesięcy w kalendarzu imprez
	$('#calendar div.content div.month span.prev, #calendar div.content div.month span.next').live('click',function()
		{
		$('#calendar div.content').hide();
		$('#calendar div.ajaxstatus').show();

		$.ajax({
			url: $(this).attr('rel'),
			dataType: 'html',
			success: function(data)
				{
				$('#calendar div.content').html(data).show();
				},
			complete: function()
				{
				$('#calendar div.ajaxstatus').hide();
				}
			});
		});

	// wyświetlenie wszystkich wydarzeń z danego miesiąca
	$('#calendar div.content > p a').live('click',function()
		{
		$('#calendar div.content ul.list li').removeClass('disabled');
		$(this).hide();

		return false;
		});

	// kalendarz
	$('.jqdate').datepicker({
		showOn: 'button',
		buttonImage: '/user/styles/images/icons/calendar.png',
		buttonImageOnly: true,
		dateFormat: 'yy-mm-dd'
		});

	// lista lotów w topie strony
	var tab = 0;

	function board()
		{
		// lista lotów w topie strony - taby
		$('div.board ul.nav').tabs('div.board div.content div.list ul',
			{
			current: 'active',
			tabs: 'li:not(.schedule)',
			initialIndex: tab,
			onClick: function(event,i)
				{
				// zapamiętanie w zmiennej globalnej identyfikatora aktualnie wybranego taba
				tab = i;

				// aktywny tab
				var el = $('#t'+parseInt(i+1))
				el.siblings().removeClass('active')
				el.addClass('active');

				// odświeżenie cufona
				Cufon.refresh('div.board ul.nav li');

				// różne nazwy miejsca docelowego w ang. wersji językowej
				var direction = $('div.board div.content ul.legend li.direction');
				var directionArrivals = direction.attr('data-en-arrivals');
				var directionDepartures = direction.attr('data-en-departures');
				
				if((directionArrivals != '') && (directionDepartures != ''))
					{
					if(i == 0) direction.text(directionArrivals);
						else direction.text(directionDepartures);
					}

				// lista lotów w topie strony - scroller
				$('div.board div.content div.list ul').jScrollPane({showArrows:true});

				// przewijanie statusu lotu i jego opisu
				$('div.board div.content div.list ul li div.status.scroller > div').each(function(index,value)
					{
					$jScroller.add('div.board div.content div.list ul li div.status.scroller',$(value),'left',2,true);
					})
				
				$jScroller.start();
				}
			});
		}

	board();

	// lista lotów w topie strony - odczyt listy AJAX'em
	if($('div.board div.content div.list').size() > 0)
		{
		setInterval(function()
			{
			$.ajax({
				type: 'GET',
				url: $('div.board div.content div.list').attr('data-href'),
				dataType: 'html',

				success: function(data)
					{
					$('div.board div.content div.list').html(data);
					board();
					}
				});
			}
			,20000);
		}

	// pasek informacyjny
	$('#informations ul').cycle({
		fx: 'fade',
		speed: 500,
		timeout: 5000,
		pause: 1
		});

	// box lotów (tablica/wyszukiwarka) na stronie głównej
	$('#index div.flights ul.footer li.arrow').click(function()
		{
		$(this).parents('div.board').toggle(0,function()
			{
			$(this).parents('div.flights').find('div.search').toggle(0);
			});

		$(this).parents('div.search').toggle(0,function()
			{
			$(this).parents('div.flights').find('div.board').toggle();
			});
		});

	// wyszukiwarka lotów na stronie głównej
	$('#index div.flights div.search form p select[name="type"], #flights div.search form p select[name="type"]').change(function()
		{
		$(this).parents('form').attr('action',$(this).find('option:selected').attr('data-action'));
		});

	// odczyt pogody dla wybranego miasta w boksie
	$('aside div.box #weather select[name="city"]').change(function()
		{
		$.ajax({
			url: $('aside div.box #weather select[name="city"] option:selected').val(),
			dataType: 'html',
			success: function(data)
				{
				$('#temperature-box').html(data);
				}
			});
		});

	// odczyt pogody dla wybranego miasta
	$('#content #weather div.content div.cities select[name="city"]').change(function()
		{
		$.ajax({
			url: $('#content #weather div.content div.cities select[name="city"] option:selected').val(),
			dataType: 'html',
			success: function(data)
				{
				$('#temperature').html(data);
				}
			});
		});

	// partnerzy - scroller
	var partners = $('#partners div.scrolling');
	if(partners.size() > 0) partners.jStockTicker({interval:20});

	$('#partners div.scrolling img').hover(function()
		{
		var substitute = $(this).attr('data-substitute');

		if((substitute != $(this).attr('src')) && (substitute != '')) $(this).attr('src',substitute);
			else $(this).attr('src',$(this).attr('data-source'));
		});

	// parking - kalkulator
	$('#parking form').submit(function(e)
		{
		e.preventDefault();

		var ajaxStatus = $(this).find('span.ajaxstatus');
		ajaxStatus.show();

		var form = $(this);

		$.ajax({
			type: 'POST',
			url: form.attr('action'),
			dataType: 'json',
			data: form.serialize(),

			success: function(data)
				{
				ajaxStatus.hide();

				var ajaxResponse = $('#parking div.ajax-response');
				ajaxResponse.html(data.msg).show();

				if(!data.calculated)
					{
					ajaxResponse.removeClass('ok');
					ajaxResponse.addClass('error');
					}
				else
					{
					ajaxResponse.removeClass('error');
					ajaxResponse.addClass('ok');
					}
				}
			});
		});

	// facebook
	$('#facebook div.content').html('<iframe src="http://www.connect.facebook.com/widgets/fan.php?id=125944264104174&amp;width=300&amp;height=400&amp;connections=15&amp;stream=false&amp;header=false" scrolling="no" frameborder="0" allowTransparency="true"></iframe>');

	$('#facebook:not(:animated) div.trigger').bind('mouseenter',function()
		{
		$(this).parent('#facebook').stop(true,false).animate({right:0},600);
		});

	$('#facebook:not(:animated)').bind('mouseleave',function()
		{
		$(this).stop(true,false).animate({right:-300},600);
		});
	});

/* Google Maps */
$(function()
	{
	var lat = $('#localization-lat').val();
	var lng = $('#localization-lng').val();

	if($('#interactiveMap').size() > 0)
		{
		new google.maps.Map(document.getElementById('interactiveMap'),
			{
		        center: new google.maps.LatLng(lat,lng),
		        zoom: 13,
			mapTypeId: google.maps.MapTypeId.ROADMAP
			});
		}

	if($('#gmaps').size() > 0)
		{
		$.ajax(
			{
			type: "GET",
			url: $('#mapResourceUrl').val(),
			dataType: "xml",
			success: function(xml)
				{
				var zoom = parseInt($(xml).find('map zoom').text());

				var map = new google.maps.Map(document.getElementById('gmaps'),
					{
					center: new google.maps.LatLng(lat, lng),
					zoom: zoom,
					mapTypeId: $(xml).find('map typeId').text()
					});

				var bounds = new google.maps.LatLngBounds();
				var infowindow = new google.maps.InfoWindow();

				$(xml).find('objects marker').each(function(index, value)
					{
					var title = $(this).find('title').text();
					var description = $(this).find('description').text();
					var lat = $(this).find('latLng').attr('lat');
					var lng = $(this).find('latLng').attr('lng');
					var icon = $(this).find('icon').text();

					var marker = new google.maps.Marker(
						{
						position: new google.maps.LatLng(lat, lng),
						title: title,
						map: map,
						icon: icon
						});

					var content = "<div id='infowindow'>" +
								"<h4>"+title+"</h4>" +
								"<p>"+description+"</p>" +
							"</div>";

					google.maps.event.addListener(marker, 'click', function()
						{
						infowindow.setContent(content);
						infowindow.open(map, marker);
						});

					bounds.extend(new google.maps.LatLng(lat, lng));
					});

				$(xml).find('objects polyline').each(function()
					{
					var title = $(this).find('title').text();
					var description = $(this).find('description').text();

					var polylineOptions = {
						strokeColor : $(this).find('strokeColor').text(),
						strokeOpacity : 1,
						strokeWeight : $(this).find('strokeWeight').text()
						};

					    var polyline = new google.maps.Polyline(polylineOptions);

					    polyline.setMap(map);

						$(this).find('latLng').each(function(){
							polyline.getPath().push(new google.maps.LatLng($(this).attr('lat'), $(this).attr('lng')));
							bounds.extend(new google.maps.LatLng($(this).attr('lat'), $(this).attr('lng')));
						})

						var content = "<div id='infowindow'>" +
									"<h4>"+title+"</h4>" +
									"<p>"+description+"</p>" +
								"</div>";

						google.maps.event.addListener(polyline, 'click', function(event) {
							infowindow.setContent(content);
							infowindow.position = event.latLng;

							infowindow.open(map);
						});
					});

				$(xml).find('objects polygon').each(function()
					{
					var title = $(this).find('title').text();
					var description = $(this).find('description').text();

					var polygonOptions = {
						strokeColor : $(this).find('strokeColor').text(),
						strokeOpacity : 1,
						strokeWeight : $(this).find('strokeWeight').text(),
						fillColor: $(this).find('fillColor').text()
					    };
					    var polygon = new google.maps.Polygon(polygonOptions);

					    polygon.setMap(map);

						$(this).find('latLng').each(function(){
							polygon.getPath().push(new google.maps.LatLng($(this).attr('lat'), $(this).attr('lng')));
							bounds.extend(new google.maps.LatLng($(this).attr('lat'), $(this).attr('lng')));
						})

						var content = "<div id='infowindow'>" +
									"<h4>"+title+"</h4>" +
									"<p>"+description+"</p>" +
								"</div>";

						google.maps.event.addListener(polygon, 'click', function(event) {
							infowindow.setContent(content);
							infowindow.position = event.latLng;

							infowindow.open(map);
						});
					});

				if(!bounds.isEmpty())
					{
					map.fitBounds(bounds);
					map.setZoom(zoom);
					}
				}
			});
		}
	});
/* end of Google Maps */
