jQuery(document).ready(function() {

	jQuery('.comment_input').click(function() {
	 
		if(jQuery(this).val() == 'Napisz komentarz')
		{
			jQuery(this).val('');
		}
	});
	
	if(jQuery("#top_box").attr('id'))
	{
		if(parseInt(jQuery("#top_box").html().length) > 0)
		{
			jQuery("#top_box").dialog({
				width:		400,
		        position:	['center','center'],
		        resizable:	false,
		        autoOpen:	true,
		        zIndex:		90000,
		        title:		'Nowe Zdjęcie tygodnia w portalu Party-Info',
		        modal:		true,
		        buttons: {
					"Dalej (publikuj)": function() {
				
						jQuery.ajax({
							type: "POST",
							url: "http://party-info.pl/ajax/publikujtop",
							async: true
						});
				
						jQuery( this ).dialog( "close" );
					},
					"Pomiń": function() {
						
						jQuery.ajax({
							type: "POST",
							url: "http://party-info.pl/ajax/niepublikujtop",
							async: true
						});
						
						jQuery("#top_box").dialog( "close" );
					}
				},
				closeOnEscape: false,
				open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); }
			});
		}
	}
	
	jQuery("#online_box").dialog({
		width:		400,
		height:		400,
        position:	['center','center'],
        resizable:	false,
        autoOpen:	false,
        zIndex:		90000,
        title:		'Użytkownicy online',
        open:		function () {
			jQuery('#online_box').html('<div id="loading2"><img src="/images/loading2.gif" alt="" /></div>');
			
			jQuery.ajax({
				type: "POST",
				url: "http://party-info.pl/ajax/users_online",
				async: true,
				success: function(data) {
					jQuery('#online_box').html(data);
				}
			});
		}
	});
	
	jQuery("#oznaczeni_box").dialog({
		width:		400,
		height:		400,
        position:	['center','center'],
        resizable:	false,
        autoOpen:	false,
        zIndex:		90000,
        title:		'Użytkownicy oznaczeni na zdjęciu',
        open:		function () {
			jQuery('#online_box').html('<div id="loading2"><img src="/images/loading2.gif" alt="" /></div>');
			
			jQuery.ajax({
				type: "POST",
				url: "http://party-info.pl/ajax/oznaczeni",
				data: { id: jQuery('#oznaczeni').attr('rel') },
				async: true,
				success: function(data) {
					jQuery('#oznaczeni_box').html(data);
				}
			});
		},
		close:		function () {
			jQuery('#oznaczeni_box').html('');
		}
	});
	
	jQuery('#online').click(function() {
		jQuery('#online_box').dialog("open");
	});
	
	jQuery('#oznaczeni').click(function() {
		jQuery('#oznaczeni_box').dialog("open");
	});
	
	jQuery('.comment_input').blur(function() {
		 if(jQuery(this).val().length == 0)
		 {
			 jQuery(this).val('Napisz komentarz');
		 }
	});
	
	jQuery("#comment_form").validate({
		rules: {
			comment: {
				required: true,
				maxlength: 250,
				comment: true,
				wulgaryzmy: true
			}
		}
	});

	jQuery.validator.addMethod(
	        "comment",
	        function(value, element, regexp) {
	           if(value == 'Napisz komentarz')	return false;
	           else								return true;
	        },
	        "Proszę wprowadzić komentarz."
	);
	
	jQuery.validator.addMethod("wulgaryzmy", function(value, element, regexp) { 
		  
		jQuery.ajax({
			type: "POST",
			url: "http://party-info.pl/wulgaryzmy.php",
			data: { value: value },
			async: false,
			success: function(data) {
				if(parseInt(data) > 0)	return_val	= false;
				else					return_val	= true;
			}
		});
		
		return return_val;
		
	}, "Nie przeklinaj!");


	//jQuery(".datepicker").datepicker({ dateFormat: 'yy-mm-dd' });
	jQuery('#club_select').change(function() {
		
		if(jQuery(this).val() == 'polecane')
		{
			jQuery('#search_date').attr('disabled', 'true');
		}
		else
		{
			jQuery('#search_date').removeAttr('disabled');
		}
	});
	
	jQuery('#club_show').click(function() {
		 if(jQuery('#club_id').val().length > 0)
		 {
			 window.location.replace('http://party-info.pl'+jQuery('#club_id').val());
			 
		 }
		 else
		 {
			alert("Najpierw wybierz klub") 
		 }
	});
	
	jQuery('.fb_setting').click(function() {

		var status	= 1;
		
		if(jQuery(this).attr('id') == 'chat')
		{
			status	= 0;
			
			if (jQuery(this).is(':checked')) {
				status	= 1;
			}
		}
		else
		{
			if (jQuery(this).is(':checked')) {
				status	= 0;
						
				jQuery('#'+jQuery(this).attr('id').split('_')[1]+'_title').removeAttr('disabled')
				jQuery('#'+jQuery(this).attr('id').split('_')[1]+'_caption').removeAttr('disabled')
				
			}
			else
			{
				jQuery('#'+jQuery(this).attr('id').split('_')[1]+'_title').attr('disabled','true')
				jQuery('#'+jQuery(this).attr('id').split('_')[1]+'_caption').attr('disabled','true')
			}
		}
		
		jQuery.ajax({
			type: "POST",
			url: "http://party-info.pl/ajax/save_param",
			data: { status: status, param: jQuery(this).attr('id') },
			async: true
		});
	});
	
	jQuery('#pomin_obecnosc').change(function() {
		if (jQuery(this).is(':checked')) {
			jQuery('#jestem_link').attr('href', jQuery('#jestem_link').attr('rel')+'/pomin')
		}
		else
		{
			jQuery('#jestem_link').attr('href', jQuery('#jestem_link').attr('rel'))
		}
	});
	
	jQuery('.template').click(function() {
		
		jQuery.ajax({
			type: "POST",
			url: "http://party-info.pl/ajax/save_param",
			data: { status: jQuery('input[name=template]:checked').val(), param: 'template' },
			async: true
		});
	});
	
	
	jQuery('#korzystam').click(function() {
		
		jQuery('.korzystam').html('Korzystasz z tej promocji');
	
		jQuery.ajax({
			type: "POST",
			url: "http://party-info.pl/ajax/korzystam",
			data: { promo: jQuery(this).attr('rel') },
			async: true
		});
	});
	
	jQuery('#wez_udzial').click(function() { udzial(jQuery(this).attr('rel')) });
	jQuery('#zrezygnuj').click(function() { zrezygnuj(jQuery(this).attr('rel')) });
	
	function udzial(id)
	{
		jQuery('#wez_udzial').unbind('click');
		
		if (jQuery('#pomin_event').is(':checked'))	{ var pomin = 1; }
		else 										{ var pomin = 0; }
		
		jQuery.ajax({
			type: "POST",
			url: "http://party-info.pl/ajax/wez_udzial",
			data: { id: id, pomin: pomin },
			async: true,
			success: function(data) {
				ret = data.split(';');
				
				if(parseInt(ret[0]) == 1)
				{
					jQuery('#zgloszenie').css({'display':'none'});
					jQuery('#zgloszony').css({'display':'block'});
					
					jQuery('.members_count').html(ret[1]);
				}
			}
		});
	}

	function zrezygnuj(id)
	{
		jQuery('#zrezygnuj').unbind('click');
		
		jQuery.ajax({
			type: "POST",
			url: "http://party-info.pl/ajax/zrezygnuj",
			data: { id: id },
			async: true,
			success: function(data) {
				
				ret = data.split(';');
				
				if(parseInt(ret[0]) == 1)
				{
					jQuery('#zgloszony').css({'display':'none'});
					jQuery('#zgloszenie').css({'display':'block'});
					
					jQuery('.members_count').html(ret[1]);
				}
			}
		});
	}
	
	jQuery('#comments_top').click(function() {
		jQuery.ajax({
			type: "POST",
			url: "http://party-info.pl/ajax/get_comments_top",
			data: { days: jQuery('#days_type').html() },
			async: true,
			success: function(data) {
				jQuery('#top_ten_pic').html(data);
			}
		});
	});
	
	jQuery('#rated_top').click(function() {
		jQuery.ajax({
			type: "POST",
			url: "http://party-info.pl/ajax/get_rated_top",
			data: { days: jQuery('#days_type').html() },
			async: true,
			success: function(data) {
				jQuery('#top_ten_pic').html(data);
			}
		});
	});
	
	jQuery('#comments_top_gallery').click(function() {
		
		jQuery.ajax({
			type: "POST",
			url: "http://party-info.pl/ajax/get_comments_top_gallery",
			data: { days: jQuery('#days_type').html() },
			async: true,
			success: function(data) {
			
				array = data.split('---===!!!@@@#%#%#@@@!!!===---',1);
				
				var galeria		= array[0]
				var poczekalnia	= array[1]
			
				jQuery('#top_ten_pic').html(galeria);
				jQuery('#poczekalnia').html(poczekalnia);
			}
		});
	});
	
	jQuery('#jestem_link').click(function() {
		jQuery('#jestem').html('<span class="jestem"><img src="/images/added.png" id="jestem_img" alt="" /> Jesteś na tym zdjęciu!</span>');
	});
	
	jQuery('#comment').keyup(function(event){  
		
		var val	= jQuery(this).val();
		var add	= 0;
		
		for(i=0;i<val.length;i++)
		{
			if(val[i] == '\n')
			{
				add++
			}
		}
		
		var lines	= Math.ceil(jQuery(this).val().length/35)
		if(lines == 0)	lines	= 1;
		
		lines	= lines+add;
		
		var	height	= lines*17+'px'
		
		if(jQuery('#comment').css('height') != height)
		{
			jQuery('#comment').css('height', height);
		}
	});
	
	jQuery.QShout({
		bBorderColor: "#522d50" 
	});
	
	if(jQuery('.datepicker').attr('id') != undefined)
	{
		jQuery('.datepicker').DatePicker({
			date: [new Date(), new Date()],
			current: jQuery('#search_date').val(),
			calendars: 2,
			mode: 'range',
			starts: 1,
			onChange: function(formated) {
			
				jQuery('#search_date').val(formated.join(' ÷ '))
			}
		});
	}
	
	if(jQuery('.datepicker_one').attr('id') != undefined)
	{
		jQuery('.datepicker_one').DatePicker({
			date: [new Date(), new Date()],
			calendars: 1,
			starts: 1,
			position: 'top',
			onChange: function(formated) {
				jQuery('#date').val(formated)
				jQuery(this).hide();
			}
		});
	}
	
	if(jQuery('.datepicker_start').attr('id') != undefined)
	{
		jQuery('.datepicker_start').parent().DatePicker({
			date: [new Date(), new Date()],
			calendars: 1,
			starts: 1,
			onChange: function(formated) {
			
				jQuery('#start').val(formated)
			}
		});
	}
	
	if(jQuery('.datepicker_stop').attr('id') != undefined)
	{
		jQuery('.datepicker_stop').parent().DatePicker({
			date: [new Date(), new Date()],
			calendars: 1,
			starts: 1,
			onChange: function(formated) {
			
				jQuery('#stop').val(formated)
			}
		});
	}
	
	jQuery('#top_tygodnia, #top_miesiaca').click(function() {
		
		if(jQuery(this).attr('id') == 'top_tygodnia')	type = 1;
		if(jQuery(this).attr('id') == 'top_miesiaca')	type = 2;
		
		var	template	= jQuery('#template').html();
		
		if(type == 1)
		{
			jQuery('#top_tygodnia').removeClass('top_tygodnia_'+template);
			jQuery('#top_tygodnia').addClass('top_tygodnia_'+template+'_active');
			
			jQuery('#top_miesiaca').removeClass('top_miesiaca_'+template+'_active');
			jQuery('#top_miesiaca').addClass('top_miesiaca_'+template);
		}
		
		if(type == 2)
		{
			jQuery('#top_tygodnia').removeClass('top_tygodnia_'+template+'_active');
			jQuery('#top_tygodnia').addClass('top_tygodnia_'+template);
			
			jQuery('#top_miesiaca').removeClass('top_miesiaca_'+template);
			jQuery('#top_miesiaca').addClass('top_miesiaca_'+template+'_active');
		}
		
		jQuery.ajax({
			type: "POST",
			url: "http://party-info.pl/ajax/get_right_box",
			data: { type: type },
			async: true,
			success: function(data) {
			
				jQuery('#right_items').html(data);
				
				var api = jQuery(".scrollable2").data("scrollable");
				
				api.seekTo(0);
			}
		});
	});
	
	jQuery('#mapa_button').click(function() {
		//alert(jQuery('#miasta').val());
		
		jQuery('#map_loading').css({'display':'block'});
		
		var mapa		= new GMap2(document.getElementById("mapa"));
		var geocoder	= new GClientGeocoder();
		var bounds		= new GLatLngBounds();

		var lat			= 54.42404359857531;
		var lng			= 18.55316162109375;
		var zoom		= 10;

		mapa.addControl(new GLargeMapControl());
		mapa.addControl(new GMapTypeControl());
		mapa.setCenter(new GLatLng(lat, lng), zoom);
		
		jQuery.ajax({
			type: "POST",
			url: "http://party-info.pl/ajax/get_map_events/",
			data: { city: jQuery('#miasta').val() },
			async: true,
			success: function(data) {
				
				if(parseInt(data) == 0) {
				
					alert('Niestety w systemie nie ma imprez pasujących do wybranych kryteriów')
					jQuery('#map_loading').css({'display':'none'});
					return true;
				}
				
				elements_array = data.split('!!!@@@###@@@!!!');
				
				if(elements_array == '')
				{
					
				}
				
				znaczniki	= new Array();
				
				for(i=0;i<elements_array.length;i++) {
					
					var baseIcon = new GIcon();  
					baseIcon.iconSize=new GSize(32,32);  
					baseIcon.shadowSize=new GSize(56,32);  
					baseIcon.iconAnchor=new GPoint(16,32);  
					baseIcon.infoWindowAnchor=new GPoint(16,0); 
					
					var ikona = new GIcon(baseIcon, 'http://maps.google.com/mapfiles/kml/pal2/icon19.png', null, 'http://maps.google.com/mapfiles/kml/pal2/icon19s.png');
					
					data_array	= elements_array[i].split('!@!@!@');
					
					var pt		= new GLatLng(data_array[8], data_array[9]);
					
					var point	= createMarker(pt, data_array, ikona)
					
					bounds.extend(pt);
					
					mapa.addOverlay(point);
				}
				
				mapa.setZoom(mapa.getBoundsZoomLevel(bounds)-1);
				var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
				var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
				mapa.setCenter(new GLatLng(clat,clng));
					
				jQuery('#map_loading').css({'display':'none'});
			}
		});
		
	});
	
	jQuery('.tab_active, .tab_non_active').click(function() {
		
		jQuery('.tab_active,.tab_non_active').addClass('tab_non_active');
		jQuery('.tab_active,.tab_non_active').removeClass('tab_active');
		
		jQuery(this).addClass('tab_active');
	});
	
	function createMarker(point, data, icon) {  
		var marker = new GMarker(point, icon);  
		GEvent.addListener(marker, "mouseover", function() {  
			marker.openInfoWindowHtml("<a href='/"+data[10]+"-i"+data[0]+".html'>"+data[1]+"</a><br /><br /><b>Klub: </b><a href='/club-"+data[6]+".html'>"+data[5]+"</a> "+data[7]);  
		});  
		
		GEvent.addListener(marker, "click", function() {
	    	window.location = "/club-"+data[6]+".html";
		});
		
		return marker;  
	} 
	
	jQuery('#event_comments,#club_comments,#event_peoples,#event_map,#club_map').click(function() {
	
		jQuery('#comments,#membersk,#map').css({'display':'none'});
		jQuery('#loading').css({'display':'block'});
		
		var id		= jQuery(this).attr('rel');
		var type	= jQuery(this).attr('id');
		
		if(type == 'event_comments' || type == 'club_comments')
		{
			jQuery('#loading').css({'display':'none'});
			jQuery('#comments').css({'display':'block'});
		}
		else if(type == 'event_map' || type == 'club_map')
		{
			jQuery.ajax({
				type: "POST",
				url: "http://party-info.pl/ajax/get_address",
				data: { id: id },
				async: true,
				success: function(data) {
					
					if (GBrowserIsCompatible())
					{
						var mapa		= new GMap2(document.getElementById("map"),{ size: new GSize(440,300)});

						//mapa.checkResize(); 
						
						var lat			= 54.42404359857531;
						var lng			= 18.55316162109375;
						var zoom		= 15;

						//mapa.addControl(new GLargeMapControl());
						//mapa.addControl(new GMapTypeControl());
						//mapa.setCenter(new GLatLng(lat, lng), zoom);
						
						data_array = data.split('@');
						
						//mapa.addControl(new GLargeMapControl());
					    //mapa.addControl(new GMapTypeControl());
					    
					    var baseIcon = new GIcon();  
						baseIcon.iconSize=new GSize(32,32);  
						baseIcon.shadowSize=new GSize(56,32);  
						baseIcon.iconAnchor=new GPoint(16,32);  
						baseIcon.infoWindowAnchor=new GPoint(16,0); 
						
						var ikona	= new GIcon(baseIcon, 'http://maps.google.com/mapfiles/kml/pal2/icon19.png', null, 'http://maps.google.com/mapfiles/kml/pal2/icon19s.png');
						
						var pt		= new GLatLng(data_array[0], data_array[1]);
						
						var point	= createMarker(pt, null, ikona)
						
						//var marker = new GMarker(pt);  
						
						mapa.addOverlay(point);
					    
						mapa.addControl(new GLargeMapControl());
						mapa.addControl(new GMapTypeControl());
						
						mapa.setCenter(pt, 16);
					}
					
					jQuery('#loading').css({'display':'none'});
					jQuery('#map').css({'display':'block'});
				}
			});
		}
		else
		{
			jQuery.ajax({
				type: "POST",
				url: "http://party-info.pl/ajax/get_members/",
				data: { id: id },
				async: true,
				success: function(data) {
					
					ret = data.split('#@!@#@!@#');
					
					jQuery('#membersk').html(ret[1]);
					
					jQuery('.members_count').html(ret[0]);
					
					jQuery('#loading').css({'display':'none'});
					jQuery('#membersk').css({'display':'block'});
				}
			});
		}
	});
		
		/*jQuery( "#search_club" ).autocomplete({
			source: "clubs.php",
			minLength: 1,
			select: function(event, ui) {
				window.location.href=ui.item.rel;
            }
		});*/
	
	jQuery.widget( "ui.combobox", {
		_create: function() {
			var self = this,
				select = this.element.hide(),
				selected = select.children( ":selected" ),
				value = selected.val() ? selected.text() : "";
			var input = this.input = jQuery( "<input>" )
				.insertAfter( select )
				.val( value )
				.attr('name','club_name')
				.autocomplete({
					delay: 0,
					minLength: 0,
					source: function( request, response ) {
						var matcher = new RegExp( jQuery.ui.autocomplete.escapeRegex(request.term), "i" );
						response( select.children( "option" ).map(function() {
							var text = jQuery( this ).text();
							if ( this.value && ( !request.term || matcher.test(text) ) )
								return {
									label: text.replace(
										new RegExp(
											"(?![^&;]+;)(?!<[^<>]*)(" +
											jQuery.ui.autocomplete.escapeRegex(request.term) +
											")(?![^<>]*>)(?![^&;]+;)", "gi"
										), "<strong>$1</strong>" ),
									value: text,
									option: this
								};
						}) );
					},
					select: function( event, ui ) {
						window.location.href=ui.item.option.id;
					},
					change: function( event, ui ) {
						if ( !ui.item ) {
							var matcher = new RegExp( "^" + jQuery.ui.autocomplete.escapeRegex( jQuery(this).val() ) + "jQuery", "i" ),
								valid = false;
							select.children( "option" ).each(function() {
								if ( jQuery( this ).text().match( matcher ) ) {
									this.selected = valid = true;
									return false;
								}
							});
							if ( !valid ) {
								// remove invalid value, as it didn't match anything
								jQuery( this ).val( "" );
								select.val( "" );
								input.data( "autocomplete" ).term = "";
								return false;
							}
						}
					}
				})
				.addClass( "search_club2" );

			input.data( "autocomplete" )._renderItem = function( ul, item ) {
				return jQuery( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a>" + item.label + "</a>" )
					.appendTo( ul );
			};

			this.button = jQuery( "<button>&nbsp;</button>" )
				.attr( "tabIndex", -1 )
				.attr( "title", "Show All Items" )
				.insertAfter( input )
				.button({
					icons: {
						primary: "ui-icon-triangle-1-s"
					},
					text: false
				})
				//.removeClass( "ui-corner-all" )
				.addClass( "ui-corner-right ui-button-icon button" )
				.click(function() {
					// close if already visible
					if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
						input.autocomplete( "close" );
						return false;
					}

					// pass empty string as value to search for, displaying all results
					input.autocomplete( "search", "" );
					input.focus();
					
					return false;
				});
		},

		destroy: function() {
			this.input.remove();
			this.button.remove();
			this.element.show();
			jQuery.Widget.prototype.destroy.call( this );
		}
	});
	
	jQuery( "#search_club" ).combobox();
	
	jQuery.ajax({
		type: "POST",
		url: "http://party-info.pl/ajax/session_check",
		async: true
	});
	
	jQuery('.promo_type').change(function() {
		
		if(jQuery(this).val() == 1)
		{
			jQuery('#promo_one').css('display','none');
			jQuery('#promo_cycle').css('display','block');
		}
		
		if(jQuery(this).val() == 2)
		{
			jQuery('#promo_cycle').css('display','none');
			jQuery('#promo_one').css('display','block');
		}
	});
	
	jQuery(".uib").button();
	
	jQuery("#profile").validate({
		errorElement: 'em',
		rules: {
			reg: { required: true },
			email: {
				required: true,
				email: true
			},
			com_title: { required: true },
			com_caption: { required: true },
			rate_title: { required: true },
			rate_caption: { required: true },
			photos_title: { required: true },
			photos_caption: { required: true },
			events_title: { required: true },
			events_caption: { required: true },
			top_title: { required: true },
			top_caption: { required: true }
		}
	});
});



