Cufon.replace('span.cufon');

$(function(){
	// banner w fancyboxie
	var element = $('#banner-fancybox').html();

	if(element != null)
		{
		$.fancybox(
			element,
			{
			padding: 0,
			margin: 0,
			scrolling: 'no',
			overlayShow: false,
			centerOnScroll: true
			});
		}

	// górne menu
	$('header nav.mainmenu ul li').not('.line, .home').hover(function()
		{
		$(this).unbind('hover');

		$(this).prev('li.line').toggleClass('disabled');
		$(this).next('li.line').toggleClass('disabled');
		});

	/* 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;
	    $("section.resize .normal").click(function(){
	    $('section.wysiwyg').css('font-size', originalFontSize);
	  });
	  // Increase Font Size
	  $("section.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
	  $("section.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: "div:not(.img)"
	}).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: 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('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'
	});

	/* 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');
		});
	});

/* 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 */
