$(function(){
	Cufon.replace('span.cufon, header nav.mainmenu ul li a, #slider-scrollable div.content h2 a, #content div.list > div.item:not(.short) h4 a');

	// banner w fancyboxie

	if($('#banner-fancybox').size() > 0)
		{
		$.fancybox(
			$('#banner-fancybox').html(),
			{
			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=334778&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
	if($("#slider-scrollable:not(.disabled)").size() > 0)
		{
		$("#slider-scrollable:not(.disabled)").scrollable({circular: true}).navigator(
			{
			navi: "#slider-nav",
			naviItem: "li"
			})
		.autoscroll(
			{
			interval: 5000
			});
		}

	//banner-slider
	if($('#banner-slider div.cycle > div').size() > 1)
		{
		var fx;
		var speed;

		var easingNumber = $('#banner-slider div.cycle').attr('data-animation');

		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-slider div.cycle').cycle({
			fx: fx,
			speed: speed,
			timeout: 7000,
			prev: '#banner-slider a.prev',
			next: '#banner-slider a.next'
			});
		}

	//banner-prepage
	if($('#banner-prepage div.cycle > div').size() > 1)
		{
		var fx;
		var speed;

		var easingNumber = $('#banner-prepage div.cycle').attr('data-animation');

		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-prepage div.cycle').cycle({
			fx: fx,
			speed: speed,
			timeout: 7000,
			prev: '#banner-prepage a.prev',
			next: '#banner-prepage a.next'
			});
		}

	//historical
	if($(".historical .scrollable-historical").size() > 0)
		{
		$(".historical .scrollable-historical").scrollable({circular: true}).navigator({
			navi: "nav",
			naviItem: "li"
		}).autoscroll({
			interval: 5000
		});
		}

	//gallery
	if($("div.scrollable-gallery").size() > 0)
		{
		$("div.scrollable-gallery").scrollable({circular: true});
		}

	//important
	if($("div.scrollable-important").size() > 0)
		{
		$("div.scrollable-important").scrollable({circular: true});
		}

	if($("aside div.box span.expand").size() > 0)
		{
		$("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
	if($("ul.jtabs").size() > 0)
		{
		$("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: 478,
	        height: 300,
	        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;
	    });
    }

	if($("#yt-player-container").size() > 0)
		{
		$("#yt-player-container").tubeplayer({
			width: 204,
			height: 135,
			initialVideo: $("#yt-initialVideo").val()
			});
		}

    $("#yt-gallery a").bind("click",function(){
        $(this).addClass("active").siblings("a").removeClass("active");
        $("#yt-player-container").tubeplayer("cue", $(this).attr("href").substr(31,$(this).attr("href").length));
        return false;
    });

	//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('data-href'),
			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'
	});

	/* trigger for product list display style */
	$('div#content div h3 a.list').click(function()
		{
		$(this).addClass('selected').siblings().removeClass('selected');
		$('div#content').find('div.grid').addClass('list').removeClass('grid');
		});
	$('div#content div h3 a.grid').click(function()
		{
		$(this).addClass('selected').siblings().removeClass('selected');
		$('div#content').find('div.list').addClass('grid').removeClass('list');
		});

	// questions
	$('div.jaccordion h5').click(function()
		{
		var api = $('div.jaccordion').data('tabs');
		if (api.getIndex() == $(this).index()/2) {
			api.getCurrentPane().slideToggle();
			api.getCurrentTab().toggleClass('current');
			}
		});

	$("div.jaccordion").tabs("div.jaccordion div.pane", {tabs: 'h5', effect: 'slide', initialIndex: null});
	});

/* Google Maps */

$(function(){
	var lat = $('#localization-lat').val();
	var lng = $('#localization-lng').val();
	function infoCallback(infowindow, object, map) {
		return function() {
			infowindow.open(map, object);
		};
	}
	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){
		var mapResourceUrl = $('#mapResourceUrl').val();
		var mapDiv = document.getElementById('gmaps');
	    var map = new google.maps.Map(mapDiv, {
	        center: new google.maps.LatLng(lat, lng),
	        zoom: 13,
	        mapTypeId: google.maps.MapTypeId.ROADMAP
	    });
	    var bounds = new google.maps.LatLngBounds();

	    $.ajax({
			type: "GET",
			url: mapResourceUrl,
			dataType: "xml",
			success: function(xml) {
				$(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 infowindow = new google.maps.InfoWindow({
						content:
						"<div id='infowindow'>" +
		                	"<h4>"+title+"</h4>" +
		                	"<p>"+description+"</p>" +
		                "</div>"
					});

					google.maps.event.addListener(marker, 'click', infoCallback(infowindow, marker, map));

					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 infowindow = new google.maps.InfoWindow({
						content:
						"<div id='infowindow'>" +
		                	"<h4>"+title+"</h4>" +
		                	"<p>"+description+"</p>" +
		                "</div>"
					});

					google.maps.event.addListener(polyline, 'click', function(event) {
						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 infowindow = new google.maps.InfoWindow({
						content:
						"<div id='infowindow'>" +
		                	"<h4>"+title+"</h4>" +
		                	"<p>"+description+"</p>" +
		                "</div>"
					});

					google.maps.event.addListener(polygon, 'click', function(event) {
						infowindow.position = event.latLng;
						infowindow.open(map);
					});
				});

				if(!bounds.isEmpty()){
					map.fitBounds(bounds);
					if (map.getZoom() > 15) {
				    	map.setZoom(15);
				  	}
			  	}
			}
		});
	}
});
/* end of Google Maps */
