var Mysport = {

	start: function() {
		this.tweakLayout();
		this.tweakButtons();
		this.addFunctionalities();
		this.addRating();
		//this.addWysiwyg();
		this.addSuggestions();
		this.startCalendar();
		this.addValidation();
		this.addConfirmations();
		this.albumFunctions();
		this.addingToObserved();
		this.addTooltips();
		this.startNotifications();
		this.socialButtons();
		this.countChars();
		this.initFlashes(4);
		this.initBanners();
		this.initMap();
		this.loadPilot();
		this.preloadImages();
	},
	
	
	tweakLayout: function() {
		// Sign inputs for IE
		if ($.browser.msie) {
			$('input').each(function() {
				if ($(this).attr('type') == 'text') {
					$(this).addClass('text');
				}
				else if ($(this).attr('type') == 'password') {
					$(this).addClass('password');
				}
				else if ($(this).attr('type') == 'checkbox') {
					$(this).addClass('checkbox');
				}
				else if ($(this).attr('type') == 'radio') {
					$(this).addClass('radio');
				}
			});
		}
		
		if ($.browser.opera) {
			$('html').addClass('opera');
		}
		
		if ($.browser.mozilla && /Firefox\/2.0/.test(navigator.userAgent)) {
			$('html').addClass('ff20');
		}
		
		$('#register-page .remember-lbl a').attr('href', 'http://www.my-sport.pl/regulations');

		$('#masthead').each(function() {
			var $masthead = $(this);
			//$masthead.prepend('<a id="report-button" href="#">Zgłoś błąd</a>');
			$('#report-button').click(function() {
				if (!document.getElementById('report-bug-form')) {
					var form_html = '<form id="report-bug-form">' +
										'<fieldset>' +
											'<textarea id="report-body"></textarea>' +
											'<div class="btn">' +
												'<a class="button right" href="#" id="cancel-report"><span class="btn-inner">Anuluj</span></a>' +
												'<a class="button right space" href="#" id="send-report"><span class="btn-inner">Zgłoś</span></a>' +
											'</div>' +
										'</fieldset>' +
									'</form>';
					$('#site').append(form_html);
					$('#send-report').click(function(e) {
						$(this).remove();
						$.ajax({
							type: 'POST',
							dataType: 'json',
							url: '/action?action=sendmail&subject=Error BUG Report',
							data: 'body='+$('#report-body').val() + ' | Od: ' + $('#user-box .nick a').text() + ' z adresu: ' + location.href + '&ax',
							success: function(data) {
								if (data) {
									$('#report-bug-form').remove();
									Mysport.displayPageMsg(e, 'Dziękujemy za pomoc we współtworzeniu serwisu.');
								}
								else {
									$('#report-bug-form').remove();
								}
							}
						});
						return false;
					});
					$('#cancel-report').click(function() {
						$('#report-bug-form').remove();
					});
				}
			});
		});
		
		//Fix png links in IE6
		if ($.browser.msie && /MSIE 6.0/.test(navigator.userAgent)) {
			//logo
			if (document.getElementById('name')) {
				if ($('#name a').length) {
					var href = $('#name a:first').attr('href');
					$('#masthead').append('<a href="' + href + '" id="logo-fix"></a>');
				}
			}
		}
		
	
		// Give hovers for IE6
		if ($.browser.msie && /MSIE 6.0/.test(navigator.userAgent)) {
			function giveHover($el) {
				$el.hover(function() {
					$el.addClass('fHover');
				}, function() {
					$el.removeClass('fHover');
				});
			}
			
			$('#mysport-table tbody tr').each(function() {
				giveHover($(this));
			});
			$('#profile-mysport .wide-table tr').each(function() {
				giveHover($(this));
			});
			$('.elements-list li').each(function() {
				giveHover($(this));
			});
			$('.notify-disciplines li').each(function() {
				giveHover($(this));
			});
			$('.users-list li').each(function() {
				giveHover($(this));
			});
			$('.users-extra-list li').each(function() {
				giveHover($(this));
			});
		}
		
		//form submit by enter key for IE
		if ($.browser.msie) {
			$('form').each(function() {
				var $this = $(this);
				setListener($this.find('input[type="password"]'));
				setListener($this.find('input[type="text"]'));
				
				function setListener($input) {
					$input.keypress(function(e) {
						if (/^13$/.test(e.keyCode)) {
							$this.submit();
						}
					});
				}
			});
		}
		
		//login captions
		$('#login-box').each(function() {
			function clearPre() {
				$this.find('input[name="login"]').val('').unbind('focus');
				$fake_pass.remove();
				$pass.show();
				$this.removeClass('pre');
			}
			var $this = $(this);
			if ($this.find('input[name="login"]').val() == '' || $this.find('input[name="login"]').val() == 'login') {
				$this.addClass('pre');
				$this.find('input[name="login"]').val('login').focus(function() {
					clearPre();
				});
				var $pass = $this.find('input[name="password"]');
				$pass.after('<input class="text" type="text" value="hasło" />');
				
				var $fake_pass = $pass.next();
				$pass.hide();
				$fake_pass.focus(function() {
					clearPre();
					$pass.focus();
				});
			}
		});
		
		//objects box captions
		function giveBoxCaptions($box, caption) {
			$box.find('form:first').each(function() {
				function clearPre() {
					$this.find('input[name="q"]').val('').unbind('focus');
					$this.removeClass('pre');
				}
				
				function execute() {
					if ($this.find('input[name="q"]').val() == '' || $this.find('input[name="q"]').val() == caption) {
						$this.addClass('pre');
						$this.find('input[name="q"]').val(caption).focus(function() {
							clearPre();
						}).blur(function() {
							if ($this.find('input[name="q"]').val() == '') {
								execute();
							}
						});
					}
				}
				
				var $this = $(this);
				
				$this.submit(function() {
					$this.find('input[name="q"]').val($this.find('input[name="q"]').val().replace('np. ', ''));
				});
				
				execute();
			});
		}
		giveBoxCaptions($('#find-objects'), 'np. basen Bydgoszcz');
		//giveBoxCaptions($('#find-services'), 'np. Warszawa');
		//giveBoxCaptions($('#find-organizations'), 'np. Warszawa');
		
		//relocateBubble for IE
		if ($.browser.msie) {
			$('#bubble').each(function() {
				var $this = $(this);
				$('#site').css('position', 'relative').append('<div id="bubble" style="display:block">' + $this.html() + '</div>');
				$this.remove();
				Mysport.startNotifications();
			});
		}
		
		//hide bubble2
		$('#bubble2').each(function() {
			var $this = $(this);
			setTimeout(function() {
				$this.remove();
			}, 6000);
		});
	},
	
	tweakButtons: function() {
		$('input.button').each(function() {
			var $submit = $(this);
			var val = $submit.val();
			var classes = this.className;
			$submit.after('<a href="#" class="' + classes + '"><span class="btn-inner">' + val + '</span></a>');
			$submit.next().click(function() {
				//$submit.click();
				$submit.parents().filter('form:first').submit();
				return false;
			});
			$submit.hide();
		});
		
		$('input.search-mysport-btn').each(function() {
			var $submit = $(this);
			var val = $submit.val();
			var classes = this.className;
			$submit.after('<a href="#" class="' + classes + '">' + val + '</a>');
			$submit.next().click(function() {
				//$submit.click();
				$submit.parents().filter('form:first').submit();
				return false;
			});
			$submit.hide();
		});
		
		$('input.small-button').each(function() {
			var $submit = $(this);
			var val = $submit.val();
			var classes = this.className;
			if ($submit.hasClass('search-button')) {
				$submit.after('<a href="#" class="button search-button">szukaj</a>');
			}
			else {
				$submit.after('<a href="#" class="' + classes + '">' + val + '</a>');
			}
			$submit.next().click(function() {
				$submit.parents().filter('form:first').submit();
				return false;
			});
			$submit.hide();
		});
	},
	
	addFunctionalities: function() {
		//show/hide media-form
		if (document.getElementById('add-media-form')) {
			var $form = $('#add-media-form');
			var visible = $form.hasClass('display');
			$('#add-media a:first').toggle(function() {
				if (visible) {
					$form.slideUp();
				}
				else {
					$form.slideDown(function() {
						$form.find('input:first').focus();
					});
				}
				return false;
			}, function() {
				if (visible) {
					$form.slideDown(function() {
						$form.find('input:first').focus();
					});
				}
				else {
					$form.slideUp();
				}
				return false;
			});
		}
		
		//change title
		$('.edit-title').each(function() {
			var $this = $(this);
			var $form = $this.next();
			var $title = $this.prev();
			$title.click(function() {
				$form.find('input.input-title').val($('#blog-title h3').text());
				$title.hide();
				$this.hide();
				$form.show();
				return false;
			});
			$this.click(function() {
				$form.find('input.input-title').val($('#blog-title h3').text());
				$title.hide();
				$this.hide();
				$form.show();
				return false;
			});
			$form.find('.cancel-title-change').click(function() {
				$form.hide();
				$title.show();
				$this.show();
				return false;
			});
			$form.submit(function() {
				Mysport.disableButton($form.find('a.button:first'));
				Mysport.disableButton($form.find('.cancel-title-change'));
				$.ajax({
					type: 'POST',
					dataType: 'json',
					url: $form.attr('action'),
					data: $form.serialize() + '&ax',
					success: function(data) {
						if (data) {
							$form.hide();
							$title.text($form.find('input[type="text"]:first').val()).show();
							$this.show();
							Mysport.enableButton($form.find('.button:first'));
							Mysport.enableButton($form.find('.cancel-title-change'));
						}
						else {
							alert('Wystąpił błąd, nowa nazwa nie została zapisana.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
						}
					}
				});
				return false;
			});
		});
		
		//blog months sliding functionality
		$('#profile-blog .years').each(function() {
			var $this = $(this);
			var $years = $this.find('> li');
			$years.each(function() {
				var $year = $(this);
				var $months = $year.find('.months');
				$year.find('.year').click(function() {
					if (!$year.hasClass('active')) {
						$this.find('li.active .months').slideUp();
						$this.find('li.active').removeClass('active');
						$months.slideDown();
						$year.addClass('active');
					}
					return false;
				});
			});
		});
		
		//sel/diselect all messages in mail
		$('#sel-all-msgs').click(function() {
			var $this = $(this);
			var $checks = $this.parents().find('table:first tbody input:checkbox');
			if (this.checked) {
				$checks.each(function() {
					this.checked = 1;
				});
			}
			else {
				$checks.each(function() {
					this.checked = 0;
				});
			}
		});
		
		//del single-message
		$('#user-messages .wide-table').each(function() {
			var $table = $(this);
			$table.find('tr').each(function() {
				var $tr = $(this);
				$tr.find('.del').click(function() {
					if (window.confirm('Czy na pewno chcesz usunąć wiadomość?')) {
						$table.find(':check').each(function() {
							this.checked = 0;
						});
						$tr.find('input')[0].checked = 1;
						$('#messages-list-form').submit();
					}
					return false;
				});
			});
		});
		
		//team settings achievements
		$('#team-settings-achievements').each(function() {
			var $settings = $(this);
			
			function setListeners() {
				$settings.find('fieldset').each(function() {
					var $fieldset = $(this);
					$fieldset.find('.remove-achievement').unbind('click').click(function() {
						$fieldset.remove();
						return false;
					});
				});
			}
			
			var new_achiev = '<fieldset>' +
								'<div class="fieldset-inner">' +
									'<div class="cell">' +
										'<label>Nazwa turnieju/konkursu</label>' +
										'<div class="fields">' +
											'<input name="competitionname" type="text" />' +
										'</div>' +
									'</div>' +
									'<div class="cell">' +
										'<label>Osiągnięcie</label>' +
										'<div class="fields">' +
											'<div class="block-line">' +
												'<input name="attainment" type="text" />' +
											'</div>' +
											'<a href="#" class="remove-achievement button"><span class="btn-inner">Usuń</span></a>' +
										'</div>' +
									'</div>' +
								'</div>' +
							'</fieldset>';
			
			$('#add-achievement').click(function() {
				$(this).parent().parent().before(new_achiev);
				setListeners();
				return false;
			});
			
			setListeners();
		});
		
		//Albums
		$('#add-new-album').toggle(function() {
			$('#add-album-form').slideDown();
			return false;
		}, function() {
			$('#add-album-form').slideUp();
			return false;
		});
		
		//show invite-players-form
		$('#invite-player-form').each(function() {
			var $this = $(this);
			$('#invite-player').toggle(function() {
				$this.slideDown();
				return false;
			}, function() {
				$this.slideUp();
				return false;
			});
		});
		
		//add next album field
		$('#add-next-album').each(function() {
			var $this = $(this);
			var $this_fields = $this.parent().parent();
			var $select = $this_fields.find('select:first');
			var select_html = $select.html();
			var select_name = $select.attr('name');
			var html = 	'<div class="field-line">' +
							'<div class="block-line">' +
								'<select name="' + select_name +'">' +
									select_html +
								'</select>' +
							'</div>' +
							'<a class="remove-album button" href="#">' +
								'<span class="btn-inner">Usuń</span>' +
							'</a>' +
						'</div>';
			function setListener() {
				$this_fields.find('.field-line').each(function() {
					var $field = $(this);
					$field.find('.remove-album').unbind('click').click(function() {
						$field.remove();
						return false;
					});
				});
			}
			
			$this.click(function() {
				$this.parent().before(html);
				setListener();
				return false;
			});
		});
		
		//show/hide competition select while adding photo
		$('#is-competition-photo').each(function() {
			var $check = $(this);
			var $select = $('#competition-photo-choices');
			if (this.checked == 1) {
				$select.show();
			}
			$check.click(function() {
				if (this.checked == 1) {
					$select.show();
				}
				else {
					$select.hide();
				}
			});
		});
		
		//vote for photo in absurdalne-sciezki competition
		$('#competition-vote .competition-vote a').click(function() {
			var $a = $(this);
			$.ajax({
				type: 'GET',
				dataType: 'json',
				url: $a.attr('href'),
				data: 'ax',
				success: function(data) {
					if (data) {
						$a.parent().html('<span>Liczba oddanych głosów: ' + data[0] + '</span>');
					}
					else {
						alert('Wystąpił błąd, głos nie został zliczony.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
					}
				}
			});
			$a.unbind('a');
			return false;
		});
		
		//assign album
		$('#assign-album-form').each(function() {
			var $this = $(this);
			$('#assign-album').click(function() {
				$(this).hide();
				$this.slideDown();
				return false;
			});
			$('#cancel-album-assign').click(function() {
				$this.slideUp(function() {
					$('#assign-album').show();
				});
				return false;
			});
		});
		
		//delete album
		function delAlbum($list) {
			$list.find('li').each(function() {
				var $li = $(this);
				$li.find('.del-element').click(function() {
					if (window.confirm('Czy na pewno chcesz usunąć album: ' + $li.find('.name a').text() + '?\nWszystkie zdjęcia które znajdowały się tylko w tym albumie również zostaną usunięte!')) {
						$.ajax({
							type: 'GET',
							dataType: 'json',
							url: $(this).attr('href'),
							data: 'ax',
							success: function(data) {
								if (data) {
									$li.remove();
								}
								else {
									alert('Wystąpił błąd, album nie został usunięty.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
								}
							}
						});
					}
					return false;
				});
			});
		}
		delAlbum($('#profile-photos .albums-list'));
		delAlbum($('#profile-movies .albums-list'));
		
		//main page day-best
		$('#day-best').each(function() {
			var $wrapper = $(this);
			var $containers = $wrapper.find('.best-container');
			var $headers = $wrapper.find('.header-inner h2');
			$headers.each(function() {
				var $h2 = $(this);
				$h2.find('a').each(function() {
					$(this).click(function() {
						var id = $(this).attr('id') + '-container';
						$containers.removeClass('active');
						$('#' + id).addClass('active');
						$headers.removeClass('selected');
						$h2.addClass('selected');
						return false;
					});
				});
			});
		});
		
		//adding _blank
		$('a.blank').attr('target', '_blank');
		
		//check if login exists -> messages
		$('#to-login').each(function() {
			var $this = $(this);
			friends_list = [];
			
			$.ajax({
				type: 'GET',
				dataType: 'json',
				url: '/mailboxaction?action=sugestfriend',
				data: 'ax',
				success: function(data) {
					if (data) {
						for (i = 0; i < data.length; i++) {
							friends_list[i] = data[i];
						}
						$this.suggest(friends_list, {
							minchars: 1
						});
					}
				}
			});
			
			$this.blur(function() {
				if ($this.val() != '') {
					setTimeout(function() {
						$.ajax({
							type: 'GET',
							dataType: 'json',
							url: '/mailboxaction',
							data: 'action=checkuser&login='+$this.val() + '&ax',
							success: function(data) {
								if (data) {
									if (data) {
										if (!$this.next().hasClass('inserted')) {
											$this.after('<input class="inserted" type="hidden" name="to" value="' + data + ' />');
										}
										else {
											$this.next().val(data);
										}
									}
								}
								else {
									Mysport.displayError($this.parents('.cell:first'), 'Taki użytkownik nie istnieje!');
								}
							}
						});
					}, 200);
				}
			});
		});
		
		//check if login exists 
		function checkIfUserExists($cell, nick) {
			$.ajax({
				type: 'GET',
				dataType: 'json',
				url: '/check',
				data: 'login='+nick + '&ax',
				success: function(data) {
					if (data) {
						if (data[0] == 'exists') {
							Mysport.displayError($cell, 'Taki użytkownik jest już zarejestrowany!');
						}
						else if (data[0] == 'vulgar') {
							Mysport.displayError($cell, 'Login nie może zawierać niecenzuralnych słów!');
						}
					}
				}
			});
		}
		function checkIfEmailExists($cell, email) {
			$.ajax({
				type: 'GET',
				dataType: 'json',
				url: '/check',
				data: 'email='+email + '&ax',
				success: function(data) {
					if (data) {
						Mysport.displayError($cell, 'Taki e-mail jest już użyty przez innego użytkownika!');
					}
				}
			});
		}
		$('#register-page input[name="register_login"]').each(function() {
			var $this = $(this);
			$this.blur(function() {
				if ($this.val() !== '') {
					checkIfUserExists($this.parents('.cell:first'), $this.val());
				}
			});
		});
		$('#register-page input[name="register_email1"]').each(function() {
			var $this = $(this);
			$this.blur(function() {
				if ($this.val() !== '') {
					checkIfEmailExists($this.parents('.cell:first'), $this.val());
				}
			});
		});
		
		
		
		
		//my-sport rows clickable
		$('#mysport-table').each(function() {
			var $table = $(this);
			$table.addClass('clickable');
			$table.find('tbody tr').each(function() {
				var $tr = $(this);
				var href = $tr.find('a.description').attr('href');
				$tr.click(function() {
					window.location = href;
					return false;
				});
			});
		});
		$('#profile-mysport .wide-table.clickable').each(function() {
			var $table = $(this);
			$table.find('tbody tr').each(function() {
				var $tr = $(this);
				var href = $tr.find('.topic > a:first').attr('href');
				$tr.click(function(e) {
					if (!$(e.target).parents('#add-mysport-opinion').length) {
						window.location = href;
					}
				});
			});
		});
		
		//mark mysport form
		function setOpinionForm(link, mode) {
			var $this = $(link);
			var html = '<form id="add-mysport-opinion" action="" method="">' +
							'<fieldset>' +
							'<legend>Oceń my-sport</legend>' +
								'<div class="options">' +
									'<p class="title">Oceń:</p>' +
									'<label class="green"><input type="radio" name="score" value="3" checked="checked" /> <span>Pozytywnie</span></label>' +
									'<label class="yellow"><input type="radio" name="score" value="2" /> <span>Neutralnie</span></label>' +
									'<label class="red"><input type="radio" name="score" value="1" /> <span>Negatywnie</span></label>' +
								'</div>' +
								'<div class="field">' +
									'<p><textarea rows="5" cols="10" name="comment"></textarea></p>' +
									'<div class="btn">' +
										'<a id="close-opinion-form" href="#" class="button right"><span class="btn-inner">Anuluj</span></a>' +
										'<a id="add-mysport-opinion-button" href="#" class="button right space"><span class="btn-inner">Dodaj</span></a>' +
									'</div>' +
								'</div>' +
							'</fieldset>' +
						'</form>';
			$this.click(function() {
				if (!document.getElementById('add-mysport-opinion')) {
					$this.after(html);
					var $form = $('#add-mysport-opinion');
					$('#add-mysport-opinion-button').click(function(e) {
						var score = 0;
						$form.find(':radio').each(function() {
							if (this.checked) {
								score = $(this).val();
							}
						});
						var color = '';
						if (score == 1) {
							color = 'red';
						}
						else if (score == 2) {
							color = 'yellow';
						}
						else if (score == 3) {
							color = 'green';
						}
						if (mode == 'single') {
							$.ajax({
								type: 'GET',
								dataType: 'json',
								url: '/scoremysport',
								data: $form.serialize()+'&mysportid='+$this.attr('rel') + '&ax',
								success: function(data) {
									if (data) {
										$form.remove();
										if (!document.getElementById('my-sport')) {
											$this.before('<img src="http://static.my-sport.pl/static/' + color + '-card.gif" alt="" />');
										}
										$this.remove();
										Mysport.displayPageMsg(e, 'Dziękujemy, komentarz został zapisany');
									}
									else {
										alert('Wystąpił błąd, komentarz nie został dodany.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
									}
								}
							});
						}
						else if (mode == 'all') {
							$.ajax({
								type: 'GET',
								dataType: 'json',
								url: '/scoremysport',
								data: $form.serialize()+'&mysportid='+$this.attr('rel')+'&mode=all&ax',
								success: function(data) {
									if (data) {
										$form.remove();
										if (!document.getElementById('my-sport')) {
											$this.before('<img src="http://static.my-sport.pl/static/multicard.png" alt="" />');
											$this.parent().prev().remove();
										}
										$this.remove();
										Mysport.displayPageMsg(e, 'Dziękujemy, komentarz został zapisany');
									}
									else {
										alert('Wystąpił błąd, komentarz nie został dodany.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
									}
								}
							});
						}
						return false;
					});
					$('#close-opinion-form').click(function() {
						$form.remove();
						return false;
					});
				}
				return false;
			});
		}
		// $('.mark .mark-mysport').each(function() {
			// setOpinionForm(this, 'single');
		// });
		$('#my-sport #add-mysport-comment').each(function() {
			setOpinionForm(this, 'single');
		});
		
		//marking all users at once
		$('.mark .markall').each(function() {
			setOpinionForm(this, 'all');
		});
		
		//marking many users
		$('.mark .multimark').click(function() {
			var $a = $(this);
			var $tr = $a.parents('tr:first');
			var ppl_tr = '<tr class="mark-ppl">' +
								'<td colspan="7" class="mark-ppl-td">' +
								'</td>' +
							'</tr>';
			
			
			$tr.after(ppl_tr);
			var $ppl_tr = $tr.next();
			
			$a.hide();
			$a.parent().next().hide();
			$a.after('<a href="#">Anuluj</a>');
			$a.next().click(function() {
				$a.show();
				$(this).remove();
				$ppl_tr.remove();
				$a.parent().next().show();
				return false;
			});
			
			
			$ppl_tr.find('.mark-ppl-td').html('<div class="ppl-loader"><img src="http://static.my-sport.pl/static/loaders/form-loader.gif"> Wczytuję uczestników My-Sportu</div>');
			
			var mysportid = $a.attr('rel');		
			$.ajax({
				type: 'GET',
				dataType: 'json',
				url: '/mysportparticipants?',
				data: 'msid='+mysportid + '&ax',
				success: function(data) {
					if (data) {
						var ppl_html = '<table class="ppl wide-table nonclickable">' +
											'<colgroup>' +
												'<col class="size15" />' +
												'<col class="size24" />' +
												'<col class="size55" />' +
												'<col class="size6" />' +
											'</colgroup>' +
											'<thead>' +
												'<tr>' +
													'<th scope="col">Użytkownik</th>' +
													'<th scope="col">Ocena</th>' +
													'<th scope="col">Komentarz</th>' +
													'<th scope="col">Zapisz</th>' +
												'</tr>' +
											'</thead>' +
											'<tbody>';
						for (i = 0; i < data.length; i++) {
							ppl_html +=			'<tr>' +
													'<td class="organizer">' +
														'<a href="/' + data[i].login + '"><img src="' + data[i].avatar + '" alt="' + data[i].login + '" /></a>' +
														'<a href="/' + data[i].login + '">' + data[i].login + '</a>' +
													'</td>' +
													'<td class="card-score">' +
														'<label class="green"><input type="radio" name="score_' + data[i].id + '" value="3" checked="checked" /></label>' +
														'<label class="yellow"><input type="radio" name="score_' + data[i].id + '" value="2" /></label>' +
														'<label class="red"><input type="radio" name="score_' + data[i].id + '" value="1" /></label>' +
													'</td>' +
													'<td class="score-body">' +
														'<input type="text" class="comment" name="comment" />' +
													'</td>' +
													'<td class="actions">' +
														'<a href="#" class="button save-score" rel="' + data[i].id + '"><span class="btn-inner">Zapisz</span></a>' +
													'</td>' +
												'</tr>';
						}
						ppl_html +=			'</tbody>' +
										'</table>';
										
						$ppl_tr.find('.mark-ppl-td').html(ppl_html);
						$ppl_tr.find('table.ppl tbody tr').each(function() {
							var $this = $(this);
							$this.find('.save-score').click(function(e) {
								var $score_link = $(this);
								$score_link.hide();
								$score_link.after('<img class="loader" src="http://static.my-sport.pl/static/form-loader.gif" alt="" />')
								var score = $this.find('.card-score input:checked').val();
								var comment = $this.find('.comment').val();
								var userid = $(this).attr('rel');
								
								$.ajax({
									type: 'GET',
									dataType: 'json',
									url: '/scoremysport',
									data: 'mysportid='+mysportid+'&comment='+comment+'&score='+score+'&userid='+userid + '&ax',
									success: function(data) {
										if (data) {
											$this.remove();
											Mysport.displayPageMsg(e, 'Komentarz został zapisany.');
											if ($ppl_tr.find('table.ppl tbody tr').length == 0) {
												$ppl_tr.remove();
												$a.next().remove();
												$a.after('<img src="http://static.my-sport.pl/static/multicard.png" alt="kartki" />');
												$a.remove();
											}
										}
										else {
											$this.find('.loader').remove();
											$score_link.show();
											alert('Wystąpił błąd, komentarz nie został zapisany.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
										}
									}
								});

								return false;
							});
						});
					}
				}
			});
			
			return false;
		});
		
		//new my-sport form
		$('#new-mysport-form').add('#new-mysport-form2').each(function() {
			var $form = $(this);
			$form.find('#captains-teams').each(function() {
				var $this = $(this);
				if (document.getElementById('id_forteam_yes').checked) {
					$this.show();
					$form.find('.team_true').show();
					$form.find('.team_false').hide();
					$('#players-label').text('Drużyn');
				}
				$('#id_forteam_yes').click(function() {
					$this.show();
					$form.find('.team_true').show();
					$form.find('.team_false').hide();
					$('#players-label').text('Drużyn');
				});
				$('#id_forteam_no').click(function() {
					$this.hide();
					$form.find('.team_true').hide();
					$form.find('.team_false').show();
					$('#players-label').text('Zawodników');
				});
			});
			
			if (document.getElementById('set-end-date').checked) {
				$form.find('.ending-fields').show();
			}
			$('#set-end-date').click(function() {
				if (this.checked) {
					$form.find('.ending-fields').show();
				}
				else {
					$form.find('.ending-fields').hide();
				}
			});
			
			$('#new-mysport-form #mysport-types').each(function() {
				var $this = $(this);
				if ($this.find('.private')[0].checked) {
					$('#notify-who').show();
				}
				$this.find(':radio').click(function() {
					var $check = $(this);
					if ($check.hasClass('private')) {
						$('#notify-who').slideDown();
					}
					else {
						$('#notify-who').slideUp();
					}
				});
			});
			
		});
		
		//adding photos to blog
		/*
		$('#photos-action').each(function() {
			var $this = $(this);
			$this.click(function() {
				$this.prevAll().remove();
				$this.hide();
				$this.after('<img src="http://static.my-sport.pl/static/loaders/form-loader.gif" alt="" />');
				var $loader = $this.next();
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: '/alblist',
					data: 'userid='+userid+'&type=2',
					success: function(data) {
						if (data) {
							$loader.remove();
							var html = '<ul id="blog-albums" class="albums-list">';
								for (i = 0; i < data.length; i++) {
									html += '<li><a class="album" href="" rel="' + data[i].albid + '">';
										for (j = 0; j < data[i].imgs.length; j++) {
											html += '<img class="album-img img' + (j+1) + '" src="' + data[i].imgs[j] + '" alt="" />';
										}
									html += '</a><p class="name"><a href="">' + data[i].title + '</a></p></li>';
								}
							html +=		'</ul>';
							var albmus_html = html;
							$this.after(html);
							$('#blog-albums li').each(function() {
								var $li = $(this);
								$li.find('.album').each(function() {
									var $album = $(this);
									$album.click(function() {
										$('#blog-albums').after('<img src="http://static.my-sport.pl/static/loaders/form-loader.gif" alt="" />');
										var $loader = $('#blog-albums').next();
										$('#blog-albums').hide();
											$.ajax({
												type: 'GET',
												dataType: 'json',
												url: '/albcontent',
												data: 'albid='+$album.attr('rel')+'&type=2',
												success: function(data) {
													if (data) {
														$loader.remove();
														var html = '<div id="photos"><div class="btn"><a href="#" id="back-to-albums" class="button"><span class="btn-inner">Wybierz zdjęcie z innego albumu</span></a></div><ul class="elements-list">';
															for (k = 0; k < data.length; k++) {
																html += '<li><p class="pic"><a rel="' + data[k].id + '" href="#"><img src="' + data[k].link + '" alt="' + data[k].title + '" /></a></p></li>';
															}
														html += '</ul></div>';
														$('#blog-albums').after(html);
														$('#back-to-albums').click(function() {
															$('#photos').remove();
															$('#blog-albums').show();
															return false;
														});
														$('#photos .elements-list li').each(function() {
															var $li = $(this);
															$li.find('a:first').click(function() {
																$('#photoid').val($(this).attr('rel'));
																$('#photos').remove();
																$this.before('<div><img src="' + $li.find('img:first').attr('src') + '" alt="' + $li.find('img:first').attr('alt') + '"></div>');
																$this.find('span').text('Zmień zdjęcie').end().show();
																$('#blog-albums').remove();
																return false;
															});
														});
													}
												}
											});
										return false;
									});
								});
							});
						}
					}
				});
				return false;
			});
		});
		*/
		$('#add-entry-form .els-action').each(function() {
			function clearBuffer() {
				$buffer.html('');
				Mysport.enableButton($('#photos-action'));
				Mysport.enableButton($('#new-photo-action'));
			}
			function setCancelBuffer() {
				$buffer.append('<div class="btn"><a href="#" class="cancel-buffer button"><span class="btn-inner">Anuluj</span></a></div>');
				$els_action.find('.cancel-buffer').click(function() {
					clearBuffer();
					return false;
				});
			}
			function setDelElementAction($el, withAjax) {
				$el.find('.del-new-el').click(function() {
					var $a = $(this);
					if (withAjax) {
						Mysport.disableButton($a);
						$.ajax({
							type: 'GET',
							dataType: 'json',
							url: '/removemedia',
							data: 'type=2&itemid='+$a.attr('rel') + '&ax',
							success: function(data) {
								if (data) {
									$el.remove()
								}
								else {
									Mysport.enableButton($a);
									alert('Wystąpił błąd, zdjęcie nie zostało usunięte.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
								}
							}
						});
					}
					else {
						$el.remove();
					}
					return false;
				});
			}
			
			var $els_action = $(this);
			$('.album-action').each(function() {
				var $this = $(this);
				var $btn_container = $this.parent().parent();
				$btn_container.after('<div id="els-buffer"></div>')
				$buffer = $btn_container.next();
				var $container = $('#added-photos-container');
				$container.append('<ul class="elements-list"></ul>');
				var $els_container = $('#added-photos-container ul:first');
				$this.click(function() {
					$buffer.html('');
					Mysport.disableButton($this);
					$buffer.prepend('<img src="http://static.my-sport.pl/static/loaders/form-loader.gif" alt="" />');
					var $loader = $buffer.find('img:first');
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: '/alblist',
						data: 'userid='+userid+'&type=2&ax',
						success: function(data) {
							if (data) {
								$loader.remove();
								var html = '<p class="els-title">Wybierz zdjęcie:</div><ul class="blog-albums albums-list">';
									for (i = 0; i < data.length; i++) {
										html += '<li><a class="album" href="#" rel="' + data[i].albid + '">';
											for (j = 0; j < data[i].imgs.length; j++) {
												html += '<img class="album-img img' + (j+1) + '" src="' + data[i].imgs[j] + '" alt="" />';
											}
										html += '</a><p class="name"><a href="#">' + data[i].title + '</a></p></li>';
									}
								html +=		'</ul>';
								var albmus_html = html;
								$buffer.html(html);
								setCancelBuffer();
								$buffer.find('.blog-albums li').each(function() {
									var $li = $(this);
									$li.find('.album').each(function() {
										var $album = $(this);
										$album.click(function() {
											$buffer.find('.blog-albums').after('<img src="http://static.my-sport.pl/static/loaders/form-loader.gif" alt="" />');
											var $loader = $buffer.find('.blog-albums').next();
											$buffer.find('.blog-albums').hide();
											$.ajax({
												type: 'GET',
												dataType: 'json',
												url: '/albcontent',
												data: 'albid='+$album.attr('rel')+'&type=2&ax',
												success: function(data) {
													if (data) {
														$loader.remove();
														var html = '<div id="photos"><ul class="elements-list">';
															for (k = 0; k < data.length; k++) {
																html += '<li><p class="pic"><a rel="' + data[k].id + '" href="#"><img src="' + data[k].link + '" alt="' + data[k].title + '" /></a></p></li>';
															}
														html += '</ul><div class="btn"><a href="#" class="back-to-albums button"><span class="btn-inner">Wybierz zdjęcie z innego albumu</span></a></div></div>';
														$buffer.find('.blog-albums').after(html);
														$buffer.find('.back-to-albums').click(function() {
															$('#photos').remove();
															$buffer.find('.blog-albums').show();
															return false;
														});
														$('#photos .elements-list li').each(function() {
															var $li = $(this);
															$li.find('a:first').click(function() {
																if ($els_container.find('input[value="' + $(this).attr('rel') + '"]').length > 0) {
																	alert('To zdjęcie jest już wybrane.');
																}
																else {
																	if ($els_action.find('.to-insert').length == 0) {
																		$els_container.before('<div class="els-title to-insert">Wybrane zdjęcia:</div>')
																	}
																	var new_el_html = '<li><p class="pic"><img src="' + $li.find('img:first').attr('src') + '" alt="' + $li.find('img:first').attr('alt') + '"></p><input type="hidden" name="photoid" value="' + $(this).attr('rel') + '" /><p><a href="#" class="button del-new-el"><span class="btn-inner">Usuń</span></a></p></li>';
																	$els_container.append(new_el_html);
																	setDelElementAction($container.find('li:last'), false);
																	clearBuffer();
																}
																return false;
															});
														});
													}
												}
											});
											return false;
										});
									});
								});
							}
						}
					});
					return false;
				});
				$('#new-photo-action').each(function() {
					var $this = $(this);
					new Ajax_upload($this, {
				        action: '/addblogentryphoto',
				        name: 'mysportphoto',
						responseType: 'json',
				        onSubmit: function(file, ext) {
						   if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
								alert('Nieprawidłowy typ pliku. Dozwolone pliki: .jpg, .jpeg, .gif, .png');
								return false;
							}
							else {
								Mysport.disableButton($this);
								$this.next().after('<span id="file-loader"><img src="http://static.my-sport.pl/static/loaders/form-loader.gif" alt="" /> Wczytuję obrazek na serwer...</span>');
							}
				        },
				        onComplete: function(file, response) {
							$('#file-loader').remove();
							Mysport.enableButton($this);
							if ($els_action.find('.to-insert').length == 0) {
								$els_container.before('<div class="els-title to-insert">Wybrane zdjęcia:</div>')
							}
							var new_el_html = '<li><p class="pic"><img src="' + response[0] + response[1] + '" alt="' + file + '"></p><input type="hidden" name="photoid" value="' + response[1] + '" /><p><a rel="' + response[1] + '" href="#" class="button del-new-el"><span class="btn-inner">Usuń</span></a></p></li>';
							$els_container.append(new_el_html);
							setDelElementAction($container.find('li:last'), true);
				        }
				    });
				});
				$container.find('li').each(function() {
					setDelElementAction($(this), false);
				});
			});
		});
		
		//disciplines funtionalities
		$('#disciplines').each(function() {
			function setDelListeners() {
				$('#profile-settings #my-disciplines li').each(function() {
					var $li = $(this);
					$li.find('.del-discipline').each(function() {
						var $a = $(this);
						var disc_id = $a.attr('rel');
						$a.unbind('click').click(function() {
							$.ajax({
								type: 'GET',
								dataType: 'json',
								url: '/action?action=deletediscipline',
								data: 'disciplineid='+disc_id+'&ax',
								success: function(data) {
									if (data) {
										$li.remove();
									}
									else {
										alert('Wystąpił błąd, dyscyplina nie została usunięta.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
									}
								}
							});
							return false;
						});
					});
				});
				$('#profile-teams #my-disciplines li').each(function() {
					var $li = $(this);
					$li.find('.del-discipline').each(function() {
						var $a = $(this);
						$a.unbind('click').click(function() {
							$li.remove();
							return false;
						});
					});
				});
			}
			
			
			function hasAlreadyDiscipline(id) {
				var counter = 0;
				$('#my-disciplines li').each(function() {
					if ($(this).find('.del-discipline').attr('rel') == id) {
						counter++;
					}
				});
				if (counter >0) {
					return true;
				}
				else {
					return false;
				}
			}
			
			var $cont = $(this);
			$('#profile-settings #discipline-list li').each(function() {
				var $this = $(this);
				$this.find('a:first').click(function() {
					var $a = $(this);
					var disc_id = $a.attr('rel');
					var disc_name = $a.find('img').attr('alt');
					var disc_img = $a.find('img').attr('src');
					
					if (hasAlreadyDiscipline(disc_id)) {
						alert('Już masz tą dyscyplinę na swojej liście.');
					}
					else {
						$.ajax({
							type: 'GET',
							dataType: 'json',
							url: '/action?action=putdiscipline',
							data: 'disciplineid='+disc_id+'&ax',
							success: function(data) {
								if (data) {
									$('#my-disciplines').append('<li><div class="disc"><img src="' + disc_img + '" alt="disc_name" /> ' + disc_name + '</div><a class="del-discipline" href="" rel="' + disc_id + '" title="">Usuń dyscyplinę</a></li>')
									setDelListeners();
								}
								else {
									alert('Wystąpił błąd, dyscyplina nie została dodana.\nPrawdopodobnie masz już taką dyscyplinę przypisaną do konta.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
								}
							}
						});
					}
					return false;
				});
			});
			$('#profile-teams #discipline-list li').each(function() {
				var $this = $(this);
				$this.find('a:first').click(function() {
					var $a = $(this);
					var disc_id = $a.attr('rel');
					var disc_name = $a.find('img').attr('alt');
					var disc_img = $a.find('img').attr('src');
					
					if (hasAlreadyDiscipline(disc_id)) {
						alert('Już masz tą dyscyplinę na swojej liście.');
					}
					else {
						if (!document.getElementById('my-disciplines')) {
							$('#disciplines .right-col .discipline-box').append('<ul id="my-disciplines"></ul>');
						}
						$('#my-disciplines').append('<li><div class="disc"><img src="' + disc_img + '" alt="disc_name" /> ' + disc_name + '</div><a class="del-discipline" href="" rel="' + disc_id + '" title="">Usuń dyscyplinę</a><input type="hidden" value="' + disc_id + '" name="discipline" /></li>')
						setDelListeners();
					}
					return false;
				});
			});
			function addDisciplineToList() {
				var $form = $('#profile-settings #find-discipline');
				var wait = setInterval(function() {
					if ($form.find('input.discipline-id').length > 0) {
						var disc_id = $form.find('.discipline-id').val();
						var disc_img = $('#d_'+disc_id).find('img').attr('src');
						var disc_name = $('#d_'+disc_id).find('img').attr('alt');
						if (hasAlreadyDiscipline(disc_id)) {
							alert('Już masz tą dyscyplinę na swojej liście.');
						}
						else {
							$.ajax({
								type: 'GET',
								dataType: 'json',
								url: '/action?action=putdiscipline',
								data: 'disciplineid='+disc_id+'&ax',
								success: function(data) {
									if (data) {
										$('#my-disciplines').append('<li><div class="disc"><img src="' + disc_img + '" alt="disc_name" /> ' + disc_name + '</div><a class="del-discipline" href="" rel="' + disc_id + '" title="">Usuń dyscyplinę</a></li>')
										$form.find('.discipline-id').remove();
										$('#find-discipline .discipline-list').val('');
										setDelListeners();
									}
									else {
										alert('Wystąpił błąd, dyscyplina nie została dodana.\nPrawdopodobnie masz już taką dyscyplinę przypisaną do konta.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
									}
								}
							});
						}
						clearInterval(wait);
					}
				}, 200);
			}
			$('#profile-settings #find-discipline').each(function() {
				var $form = $(this);
				$form.find('#add-discipline-button').click(function() {
					addDisciplineToList();
					return false;
				});
			});
			$('#find-discipline .discipline-list').keypress(function(e) {
				//if ($('.ac_results').css('display') == 'none') {
					if (/^13$/.test(e.keyCode)) {
						//addDisciplineToList();
						return false;
					}
				//}
			});
						
			$('#profile-teams #find-discipline').each(function() {
				var $form = $(this);
				$form.find('#add-discipline-button').click(function() {
					var wait = setInterval(function() {
						if ($form.find('input.discipline-id').length > 0) {
							var disc_id = $form.find('.discipline-id').val();
							var disc_img = $('#d_'+disc_id).find('img').attr('src');
							var disc_name = $('#d_'+disc_id).find('img').attr('alt');
							if (hasAlreadyDiscipline(disc_id)) {
								alert('Już masz tą dyscyplinę na swojej liście.');
							}
							else {
								if (!document.getElementById('my-disciplines')) {
									$('#disciplines .right-col .discipline-box').append('<ul id="my-disciplines"></ul>');
								}
								$('#my-disciplines').append('<li><div class="disc"><img src="' + disc_img + '" alt="disc_name" /> ' + disc_name + '</div><a class="del-discipline" href="" rel="' + disc_id + '" title="">Usuń dyscyplinę</a><input type="hidden" value="' + disc_id + '" name="discipline" /></li>')
								$('#find-discipline .discipline-list').val('');
								setDelListeners();
							}
							
							clearInterval(wait);
						}
					}, 200);
					return false;
				});
			});
			
			setDelListeners();
		});
		
		//Deleting group and team - photos
		function delElements($list, kind, list_name) {
			$list.find('li').each(function() {
				var $li = $(this);
				$li.find('.del-element').click(function() {
					if (window.confirm('Czy na pewno chcesz usunąć ' + kind + ': ' + $li.find('.title a').text() + ' z ' + list_name + '?')) {
						$.ajax({
							type: 'GET',
							dataType: 'json',
							url: $(this).attr('href'),
							data: 'ax',
							success: function(data) {
								if (data) {
									$li.remove();
								}
								else {
									alert('Wystąpił błąd, ' + kind + ' nie zostało usunięte z ' + list_name + '.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
								}
							}
						});
					}
					return false;
				});
				$li.find('.del-user').click(function() {
					if (window.confirm('Czy na pewno chcesz usunąć ' + kind + ': ' + $li.find('.name a').text() + ' z ' + list_name + '?')) {
						$.ajax({
							type: 'GET',
							dataType: 'json',
							url: $(this).attr('href'),
							data: 'ax',
							success: function(data) {
								if (data) {
									$li.remove();
								}
								else {
									alert('Wystąpił błąd, ' + kind + ' nie zostało usunięte z ' + list_name + '.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
								}
							}
						});
					}
					return false;
				});
			});
		}
		delElements($('#group-gallery .elements-list:first'), 'zdjęcie', 'galerii grupy');
		delElements($('#group-movies .elements-list:first'), 'filmik', 'filmików grupy');
		delElements($('#team-gallery .elements-list:first'), 'zdjęcie', 'galerii drużyny');
		delElements($('#team-movies .elements-list:first'), 'filmik', 'filmików drużyny');
		delElements($('#mysport-gallery .elements-list:first'), 'zdjęcie', 'galerii My-Sportu');
		delElements($('#mysport-movies .elements-list:first'), 'filmik', 'filmików My-Sportu');
		delElements($('#profile-blogs-obs.observed #blogs-list'), 'wpis', 'obserwowanych wpisów');
		delElements($('#profile-photos-obs.observed .elements-list:first'), 'zdjęcie', 'obserwowanych zdjęć');
		delElements($('#profile-movies-obs.observed .elements-list:first'), 'filmik', 'obserwowanych filmików');
		delElements($('#profile-groups-obs .users-list:first'), 'grupę', 'obserwowanych grup');
		delElements($('#profile-users-obs .users-list:first'), 'użytkownika', 'obserwowanych użytkowników');
		delElements($('#profile-teams-obs .users-list:first'), 'drużynę', 'obserwowanych drużyn');
		
		$('#profile-mysports-obs .del-element').click(function() {
			if (window.confirm('Czy na pewno chcesz usunąć My-Sport: ' + $(this).parents('tr:first').find('.title').text() + ' z obserwowanych?')) {
				var $a = $(this);
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: $(this).attr('href'),
					data: 'ax',
					success: function(data) {
						if (data) {
							$a.parents('tr:first').remove();
						}
						else {
							alert('Wystąpił błąd, ' + kind + ' nie zostało usunięte z ' + list_name + '.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
						}
					}
				});
			}
			return false;
		});
		
		//delete blog entry
		$('#profile-blog .blog-entry').each(function() {
			var $entry = $(this);
			$entry.find('.del-entry').click(function() {
				if (window.confirm('Czy na pewno chcesz usunąć ten wpis?')) {
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: $(this).attr('href'),
						data: 'ax',
						success: function(data) {
							if (data) {
								$entry.remove();
							}
							else {
								alert('Wystąpił błąd, wpis nie został usunięty.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
							}
						}
					});
				}
				return false;
			});
		});
		
		
		//invite friend
		$('a.add-to-friends:not(.noaction)').click(function(e) {
			var $a  = $(this);
			if (!document.getElementById('user-box')) {
				return true;
			}
			else {
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: $(this).attr('href'),
					data: 'ax',
					success: function(data) {
						if (data) {
							if (data[0].ok) {
								$a.remove();
							}
							Mysport.displayPageMsg(e, data[0].msg);
						}
						else {
							alert('Wystąpił błąd, zaproszenie nie zostało wysłane.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
						}
					}
				});
				return false;
			}
		});
		
		//user-number options
		function checkNumberAvail($cell, e, val) {
			$.ajax({
				type: 'GET',
				dataType: 'json',
				url: '/checkpersonalnumber',
				data: 'personal_number='+val+'&ax',
				success: function(data) {
					if (data[0]) {
						Mysport.displayError($cell, 'Numerek już zajęty!');
					}
					else {
						Mysport.displayPageMsg(e, 'Numerek jest wolny');
					}
				}
			});
		}
		function generate($input) {
			var $field = $input;
			var value = $field.val();
			$.ajax({
				type: 'GET',
				dataType: 'json',
				url: '/getrandnumber',
				data: 'i=' + index++,
				success: function(data) {
					if (data[0]) {
						$field.val(data[0]);
					}
				}
			});
		}
		$('#number-avail-check').click(function(e) {
				checkNumberAvail($(this).parents('.cell:first'), e, $('#profile-settings input[name="personalnumber"]').val());
			return false;
		});
		var index = 0;
		$('#generate-number').click(function() {
			generate($('#profile-settings input[name="personalnumber"]'));
			return false;
		});
		
		//report abuse
		$('.report-abuse').click(function(e) {
			var $a = $(this);
			if (!document.getElementById('report-bug-form')) {
				var form_html = '<form id="report-bug-form" class="pre">' +
									'<fieldset>' +
										'<textarea id="report-body">Treść zgłoszenia</textarea>' +
										'<div class="btn">' +
											'<a class="button right" href="#" id="cancel-report"><span class="btn-inner">Anuluj</span></a>' +
											'<a class="button right space" href="#" id="send-report"><span class="btn-inner">Zgłoś</span></a>' +
										'</div>' +
									'</fieldset>' +
								'</form>';
				$('#site').append(form_html);
				$('#report-bug-form').css({'top':  (e.pageY-100)+'px', 'left': (e.pageX+20)+'px'});
				$('#report-bug-form textarea').focus(function() {
					$('#report-bug-form').removeClass('pre');
					$(this).val('').unbind('focus');
				});
				$('#send-report').click(function(e) {
					$(this).remove();
					$a.addClass('loading');
					$.ajax({
						type: 'POST',
						dataType: 'json',
						url: '/action?action=sendmail&subject=Error BUG Report',
						//data: 'body='+$('#report-body').val() + ' | Od: ' + $('#user-box .nick a').text() + ' z adresu: ' + location.href + '&ax',
						data: 'body=Naruszone zasady pod adresem: ' + location.href + ' Wysłane przez: ' +  $('#user-box .nick a:first').text() + ' o treści: ' + $('#report-body').val() + '&ax',
						success: function(data) {
							if (data) {
								$('#report-bug-form').remove();
								$a.remove();
								Mysport.displayPageMsg(e, 'Zgłoszenie naruszenia zasad zostało wysłane. Dziękujemy.');
							}
							else {
								$('#report-bug-form').remove();
							}
						}
					});
					return false;
				});
				$('#cancel-report').click(function() {
					$('#report-bug-form').remove();
					return false;
				});
			}
			
			
			// $a.addClass('loading');
			// $.ajax({
				// type: 'POST',
				// dataType: 'json',
				// url: '/action?action=sendmail&subject=Naruszenie zasad',
				// data: 'body=Naruszone zasady pod adresem: ' + location.href + ' Wysłane przez: ' +  $('#user-box .nick a').text() + '&ax',
				// success: function(data) {
					// if (data) {
						// $a.remove();
						// Mysport.displayPageMsg(e, 'Zgłoszenie naruszenia zasad zostało wysłane. Dziękujemy.');
					// }
				// }
			// });
			return false;
		});
		
		//pilot
		function gotoLi(x) {
			x--;
			var move = x * -988;
			$('#pilot-panels').animate({'left': move+'px'});
		}
		$('#pilot').each(function() {
			var $pilot = $(this);
			$('#main-page-guide').click(function() {
				$('#content').addClass('with-pilot');
				$pilot.animate({'left': '0px'});
				$(this).hide();
				return false;
			});
			$pilot.find('.next').click(function() {
				 gotoLi($(this).attr('rel').replace('pilot', ''));
				return false;
			});
			$pilot.find('.prev').click(function() {
				 gotoLi($(this).attr('rel').replace('pilot', ''));
				return false;
			});
			$pilot.find('.close-pilot').click(function() {
				$pilot.animate({'left': '988px'});
				$('#content').removeClass('with-pilot');
				$('#main-page-guide').show();
				return false;
			});
			/*
			$pilot.find('#goto-registration').click(function() {
				$pilot.animate({'left': '988px'});
				$('#content').removeClass('with-pilot');
				$('#main-page-guide').show();
				return false;
			});
			*/
		});
		
		//main page-rotator

		function setRotator($section, sex, rotate, time) {
			var currentIndex = 0;
			
			if (rotate) {
				var interval = setInterval(function(){}, 9999);
			}
			
			var $ul = $section.find('ul:first');
			$ul.addClass('elements');
			var $lis = $ul.find('li');
			if ($lis.length > 1) {
				var pgr_html = '<div class="pgr"><ul>'
				$lis.each(function(i) {
					pgr_html += '<li><a href="#">' + (i+1) + '</a></li>';
					
				});
				pgr_html += '</ul></div>';
				$ul.after(pgr_html);
				var $pgr = $ul.next();
				if (sex) {
					$pgr.append('<a class="prev-rot" href="#">&laquo; poprzedni</a><a class="next-rot" href="#">następny &raquo;</a>');
				}
				else {
					$pgr.append('<a class="prev-rot" href="#">&laquo; poprzednia</a><a class="next-rot" href="#">następna &raquo;</a>');
				}
				var $prev = $pgr.find('.prev-rot');
				var $next = $pgr.find('.next-rot');
				$pgr.find('li:first').addClass('selected');
				if ($pgr.find('li').length > 1) {
					$next.show();
				}
				$pgr.find('li').each(function(i) {
					var $pgr_li = $(this);
					$pgr_li.find('a').click(function() {
						selectTab(i);
						return false;
					});
				});
				$prev.click(function() {
					selectTab(currentIndex - 1);
					if (rotate) {
						clearInterval(interval);
						startRotating();
					}
					return false;
				});
				$next.click(function() {
					selectTab(currentIndex + 1);
					if (rotate) {
						clearInterval(interval);
						startRotating();
					}
					return false;
				});
				
				function selectTab(i) {
					$lis.hide();
					$ul.find('li:eq(' + i + ')').show();
					$pgr.find('.selected').removeClass('selected');
					$pgr.find('li:eq(' + i + ')').addClass('selected');
					if ($pgr.find('li:eq(' + i + ')').prevAll().length > 0) {
						$prev.show();
					}
					else {
						$prev.hide();
					}
					if ($pgr.find('li:eq(' + i + ')').nextAll().length > 0) {
						$next.show();
					}
					else {
						$next.hide();
					}
					currentIndex = i;
				}
				function startRotating() {
					var q = $pgr.find('li').length - 1;
					var j = currentIndex;
					
					interval = setInterval(function() {
						if (j > q) {
							j = 0;
						}
						selectTab(j++);
					}, (time*1000));
				}
				
				if (rotate) {
					startRotating();
				}
			}
		}
		
		setRotator($('#is-news'), 1, 0, 0);
		setRotator($('#is-events'), 1, 0, 0);
		setRotator($('#newest-threads'), 1, 0, 0);
		setRotator($('#find-objects'), 1, 1, 4);
		setRotator($('#find-services'), 1, 0, 0);
		setRotator($('#find-organizations'), 1, 0, 0);
		setRotator($('#best-mysport'), 1, 0, 0);
		setRotator($('#competition-link'), 1, 0, 0);
		
		//Add another firend field
		$('#next-friend-field').each(function() {
			var $this = $(this);
			var $this_fields = $this.parent().parent();
			var $input = $this_fields.find('input:first');
			var input_name = $input.attr('name');
			var html = 	'<div class="field-line">' +
							'<div class="block-line">' +
								'<input class="long email" name="' + input_name + '" type="text" maxlength="255"/>' +
							'</div>' +
							'<a class="remove-field button" href="#">' +
								'<span class="btn-inner">Usuń</span>' +
							'</a>' +
						'</div>';
			function setListener() {
				$this_fields.find('.field-line').each(function() {
					var $field = $(this);
					$field.find('.remove-field').unbind('click').click(function() {
						$field.remove();
						return false;
					});
				});
			}
			
			$this.click(function() {
				$this.parent().before(html);
				setListener();
				return false;
			});
		});
		
		//How they see me
		$('#how-they-see').each(function() {
			var $this = $(this);
			$('#how-they-see-more').click(function() {
				var $details = $('#how-they-see-details');
				if ($details.css('display') == 'none') {
					$details.slideDown();
				}
				else {
					$details.slideUp();
				}
				return false;
			})
			$this.find('input.reload-profil-param').click(function() {
				var value = $(this).attr('value')
				var oldlocation = window.location.href;
				if (window.location.href.split('?').length > 1){
					var oldlocation = window.location.href.split('?')[0];
				}
				window.location = oldlocation +'?showprofileas='+value;
				return false;
			});
		});
		
		//show/hide my-sport time options
		$('#ms-time-features').each(function() {
			var $this = $(this);
			if ($('#ms-has-time')[0].checked) {
				$this.show();
			}
			$('#ms-has-time').click(function() {
				$this.show();
			});
			$('#ms-hasnt-time').click(function() {
				$this.hide();
			});
		});
		
		//setting element privacy
		$('#set-public-element').click(function(e) {
			$.ajax({
				type: 'GET',
				dataType: 'json',
				url: '/setitemprivacy?level=0&itemid='+itemid+'&moduleid='+moduleid,
				data: 'ax',
				success: function(data) {
					if (data) {
						Mysport.displayPageMsg(e, 'Poprawnie zmieniono ustawienia wyświetlania.');
					}
				}
			});
		});
		$('#set-private-element').click(function(e) {
			$.ajax({
				type: 'GET',
				dataType: 'json',
				url: '/setitemprivacy?level=1&itemid='+itemid+'&moduleid='+moduleid,
				data: 'ax',
				success: function(data) {
					if (data) {
						Mysport.displayPageMsg(e, 'Poprawnie zmieniono ustawienia wyświetlania.');
					}
				}
			});
		});
		
		//preload promo options icons
		$('.promo-options').each(function() {
			$.imgpreload([ //preload loaders
				'http://www.kkuliczkowski.dev.sportmediagroup.pl/view/css/i/icons/set-main-photo-h.gif',
				'http://www.kkuliczkowski.dev.sportmediagroup.pl/view/css/i/common/eye-small-h.gif',
				'http://www.kkuliczkowski.dev.sportmediagroup.pl/view/css/i/icons/abuse-h.gif'
			], '');
		});
		
		//set notification as read
		$('#notifications-list tr.unread').each(function() {
			var $tr = $(this);
			$tr.find('.subject a:first').each(function() {
				var $a = $(this);
				$a.click(function() {
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: '/action?action=setread',
						data: 'id='+$tr.find('input[name="id"]').val() + '&ax',
						success: function(data) {
							if (data) {
								document.location.href = $a.attr('href');
							}
							else {
								document.location.href = $a.attr('href');
							}
						}
					});
					return false;
				});
			});
		});
		
		//edit photo and video title and tags
		$('#change-element-title').each(function() {
			var $form = $(this);
			var $link = $('a.edit-element');
			$link.click(function() {
				$link.hide();
				$form.slideDown();
				return false;
			});
			$form.find('.cancel-title-change').click(function() {
				$form.slideUp(function() {
					$link.show();
				});
				return false;
			});
		});
		
		//competition functions
		$('#competition').each(function() {
			$('#show-terms').click(function() {
				if (!$('#competition-terms').hasClass('shown')) {
					$('#competition-terms').slideDown().addClass('shown');
				}
				else {
					$('#competition-terms').slideUp().removeClass('shown');
				}
				if (document.getElementById('memorial_hjw-competition') || document.getElementById('skoki-competition') || document.getElementById('eurobasket-competition') || document.getElementById('sciezki-competition') || document.getElementById('plsvk-competition') || document.getElementById('trytobe-competition') || document.getElementById('rugby-competition') || document.getElementById('podwodnyswiat-competition') || document.getElementById('niewiarygodnepredkosci-competition')) {
					return false;
				}
			});
			$('#show-result').click(function() {
				if (!$('#competition-result').hasClass('shown')) {
					$('#competition-result').slideDown().addClass('shown');
				}
				else {
					$('#competition-result').slideUp().removeClass('shown');
				}
				if (document.getElementById('memorial_hjw-competition') || document.getElementById('skoki-competition') || document.getElementById('eurobasket-competition') || document.getElementById('sciezki-competition') || document.getElementById('plsvk-competition') || document.getElementById('trytobe-competition') || document.getElementById('rugby-competition') || document.getElementById('podwodnyswiat-competition') || document.getElementById('niewiarygodnepredkosci-competition')) {
					return false;
				}
			});
			$('#show-prizes').click(function() {
				if (!$('#competition-prizes').hasClass('shown')) {
					$('#competition-prizes').slideDown().addClass('shown');
				}
				else {
					$('#competition-prizes').slideUp().removeClass('shown');
				}
				if (document.getElementById('memorial_hjw-competition') || document.getElementById('skoki-competition') || document.getElementById('eurobasket-competition') || document.getElementById('sciezki-competition') || document.getElementById('plsvk-competition') || document.getElementById('trytobe-competition') || document.getElementById('rugby-competition') || document.getElementById('podwodnyswiat-competition') || document.getElementById('niewiarygodnepredkosci-competition')) {
					return false;
				}
			});
		});
		
		$('#niewiarygodnepredkosci-competition').each(function() {
			var $this = $(this);
			$this.find('#question-form').submit(function() {
				if ($(this).find('input:checked').length > 0) {
					return true;
				}
				else {
					alert('Proszę wybrać odpowiedź!');
					return false;
				}
			});
			$this.find('#answer-submit-button').click(function() {
				$this.find('#question-form').submit();
				return false;
			});
		});
		
		$('#piklareczna-competition').each(function() {
			var $this = $(this);
			$this.find('#question-form').submit(function() {
				if ($(this).find('input:checked').length > 0) {
					return true;
				}
				else {
					alert('Proszę wybrać odpowiedź!');
					return false;
				}
			});
			$this.find('#answer-submit-button').click(function() {
				$this.find('#question-form').submit();
				return false;
			});
		});
		
		//magnify photos
		$('a[rel="magnify"]').each(function(i) {
			var $a = $(this);
			var $img = $a.find('img:first')
			var img_url = $a.attr('href').replace('/b/', '/o/');
			$('body:first').append('<div id="magnify-img' + i + '" class="magnify-img"></div>');
			var $magnify_img = $('#magnify-img' + i);
			$('<img />')
				.attr('src', img_url)
				.load(function(){
					$magnify_img.append( $(this) );
					var img_width = $magnify_img.find('img:first').width();
					var img_height = $magnify_img.find('img:first').height();
					$magnify_img.remove();
					$a.click(function() {
						var src = img_url;
						
						var left = screen.width/2 - img_width/2;
						var top = screen.height/2 - img_height/2;
						
						var config = 'left=' + left + ',top=' + top + ', height=' + img_height + ', width=' + img_width + ',innerheight=' + img_height + ',innerwidth=' + img_width + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no';
							
						
						html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"' +
							'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' +
						'<html xmlns="http://www.w3.org/1999/xhtml">' +
						'<head>' +
							'<title>Galeria :: My-Sport.pl</title>' +
							'<meta http-equiv="content-type" content="text/html;charset=utf-8" />' +
							'<meta name="description" content="My sport - my life. Dołącz, poznaj, umów się, zagraj! Darmowy serwis społecznościowy o tematyce sportowej, dostępny dla każdego." /> ' +
							'<meta name="keywords" content="mysport, my-sport, my, sport, my sport, sport, imprezy, sportowe, gry, rekreacja"/> ' +
							'<link rel="shortcut icon" type="image/x-icon" href="http://static.my-sport.pl/static/favicon.ico" /> ' +
							'<meta http-equiv="Cache-Control" content="no-cache" />' +
							'<meta http-equiv="Pragma" content="no-cache" />' +
							'<style type="text/css">' +
								'html {padding: 0;margin: 0;}' +
								'body {padding: 0;margin: 0;mafont: normal 75% Arial, Helvetica, sans-serif;background-color:#fff}' +
								'.img {text-align: center;margin-bottom: 10px;}' +
							'</style>' +
						'</head>' +
						'<body>' +
							'<div id="mag-container">' +
								'<div class="img">' +
									'<img src="' + src + '" alt="" />' +
								'</div>' +
							'</div>' +
						'<jsp:include page="/view/templates/javascripts.jsp"></jsp:include>' +
						'<script type="text/javascript">' +
						'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");' +
						'document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));' +
						'</script>' +
						'<script type="text/javascript">' +
						'try {' +
						'var pageTracker = _gat._getTracker("UA-7692542-4");' +
						'pageTracker._trackPageview();' +
						'} catch(err) {}</script>' +
						'</body>' +
						'</html>';
						
						var magnification = window.open('', 'magnification', config);
						magnification.document.write(html);
						magnification.document.close();
						return false;
					});
				});
		});
		
		//adding x to close my-sport warning
		$('#my-sport-warning').each(function() {
			var $this = $(this);
			$this.append('<a href="#" class="close">Zamknij</a>');
			$this.find('a.close').click(function() {
				Cookie.create('nomysportwarning', '1', 365);
				$this.remove();
				return false;
			});
		});
		
		//adding to team my-sports
		$('#my-teams').each(function() {
			var $select = $(this);
			var $button = $('#add-player');
			var href = $button.attr('href');
			
			//$button.attr('href', href + $select.val() + '/jointeam');
			
			if ($select.find('option').length > 1) {
				$select.prepend('<option value="-1" selected="selected">Wybierz drużynę</option>');
				$button.click(function() {
					$select.show().change(function() {
						var id = $select.val();
						var url = $button.attr('href').split('/');
						var link = '/' + url[1] + '/' + url[2] + '/' + url[3] + '/' + id + '/jointeam';
						location.href = link;
						//console.log(link);
					});
					$button.unbind('click').click(function() {
						return false;
					});
					return false;
				});
			}
		});
		
		//position del-elemnt button
		$('.elements-list').each(function() {
			var $list = $(this);
			if ($list.find('.del-element').length > 0) {
				$list.find('> li').each(function() {
					var $li = $(this);
					$li.find('.del-element').css('top', ($li.find('.pic img:first')[0].offsetTop - 6) + 'px').css('left', ($li.find('.pic img:first')[0].offsetLeft - 6) + 'px');
				});
			}
		});
		
		//cite message
		$('#quote-msg').click(function() {
			var textBody = $('#new-message')[0];
			var $textBody = $(textBody);
			
			var val = '[cytat ' + $('#msg-from').text() + ']' + $('#body').find('input[type="hidden"]').val() + '[koniec]';
			var len = val.length;
			if (document.selection && $.browser.msie) {
				textBody.focus();
				sel = document.selection.createRange();
				var stored_range = sel.duplicate();
				stored_range.moveToElementText( textBody );
				stored_range.setEndPoint( 'EndToEnd', sel );
				selectionStart = stored_range.text.length - sel.text.length;
				selectionEnd = selectionStart + sel.text.length;
			}
			else {
				textBody.focus();
				selectionStart = textBody.selectionStart;
				selectionEnd = textBody.selectionEnd;
			}
			var cursor_pos = selectionStart;
			var text_start = $textBody.val().substring(0, cursor_pos);
			var text_end = $textBody.val().substring(cursor_pos);
			var new_text = text_start + val + text_end;
			$textBody.val(new_text);
			
			if (document.selection && $.browser.msie) {
				var back = text_end.length;
				var oSel = document.selection.createRange();
				oSel.moveStart ('character', -(selectionStart + len));
				oSel.moveStart ('character', selectionStart + len);
				oSel.moveEnd ('character', -back);
				oSel.select();
			}
			else {
				textBody.setSelectionRange(selectionStart + len, selectionStart + len);
			}
			return false;
		});
		
		//switch my-sport forms
		$('#add-mysport-forms').each(function() {
			var $forms = $(this);
			var $simple = $('#new-mysport-form');
			var $adv = $('#new-mysport-form2');
			
			function showSimple() {
				$simple.hide();
				$adv.show();
				$('#show-simple').find('a').hide().end().find('span').show().end().addClass('selected');
				$('#show-adv').find('a').show().end().find('span').hide().end().removeClass('selected');
			}
			function showAdv() {
				$simple.show();
				$adv.hide();
				$('#show-simple').find('a').show().end().find('span').hide().end().removeClass('selected');
				$('#show-adv').find('a').hide().end().find('span').show().end().addClass('selected');
			}
			
			var adv_shown = false;
			$('#show-simple a').click(function() {
				showSimple();
				return false;
			});
			$('#show-adv a').click(function() {
				showAdv();
				if (!adv_shown) {
					$('#search-town').suggest_ext('/action?get=towns', {
						minchars: 3
					});
					adv_shown = true;
				}
				return false;
			});
			$('#show-simple2').click(function() {
				showSimple();
			});
			$('#show-adv2').click(function() {
				showAdv();
				if (!adv_shown) {
					$('#search-town').suggest_ext('/action?get=towns', {
						minchars: 3
					});
					adv_shown = true;
				}
			});
			
			function copyInfo($els) {
				$els.each(function() {
					var $el = $(this);
					if ($el.attr('type') == 'hidden') {
						$el.change(function() {
							$els.val($el.val());
						});
					}
					else {
						$el.blur(function() {
							$els.val($el.val());
						});
					}
				});
			}
			
			copyInfo($forms.find('input[name="title"]'));
			copyInfo($forms.find('textarea[name="description"]'));
			copyInfo($forms.find('input[name="discipline"]'));
			copyInfo($forms.find('input[name="maxcompetitors"]'));
			copyInfo($forms.find('input[name="city"]'));
			copyInfo($forms.find('select[name="province"]'));
			copyInfo($forms.find('input[name="unlogged_email"]'));
		});
		
		$('#add-mysport-forms input[name="unlogged_email"]').each(function() {
			var $this = $(this);
			$this.blur(function() {
				if ($this.val() !== '') {
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: '/check',
						data: 'email='+$this.val() + '&ax',
						success: function(data) {
							if (data) {
								$('.additional-pass').show().find('input').removeClass('nr');
							}
							else {
								if (!$('.additional-pass').find('input').hasClass('nr')) {
									$('.additional-pass').hide().find('input').addClass('nr');
								}
							}
						}
					});
				}
			});
		});
		
		//show-hide advanced my-sport search
		$('#show-adv-search').click(function() {
			if ($.browser.msie && (/MSIE 6.0/.test(navigator.userAgent) || /MSIE 7.0/.test(navigator.userAgent))) {
				$('.advanced-search').css('display', 'block');
			}
			else {
				$('.advanced-search').css('display', 'table-cell');
			}
			$('#form-shown').val(1);
			$(this).remove();
			return false;
		});
		
		//event-details setup
		$('#events-details').each(function() {
			var $fields = $(this);
			var $check = $('#preferences-events');
			var check = $check[0];
			if (check.checked == 1) {
				$fields.show();
			}
			$check.click(function() {
				if (check.checked == 1) {
					$fields.show();
				}
				else {
					$fields.hide();
				}
			});
			
			function setDelListener($li) {
				$li.find('a.del').click(function() {
					var $a = $(this);
					$a.unbind('click');
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: $a.attr('href'),
						data: 'ax',
						success: function(data) {
							if (data[0]) {
								$li.remove();
							}
							else {
								alert('Wystapił błąd, nie udało się usunąć dyscypliny. Jeżeli błąd będzie się powtarzał skontaktuj się z administratorem.');
							}
						}
					});
					return false;
				});
			}
			function addDiscipline() {
				if ($fields.find('.discipline-list').val() == '') {
					alert('Wybierz dyscyplinę!');
				}
				else {
					$('#add-notif-discipline').after('<img src="http://static.my-sport.pl/static/loaders/form-loader.gif" alt="" id="disc-loader" />').hide();
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: '/putnotificationdiscipline',
						data: 'discipline='+$fields.find('.discipline-list').val(),
						success: function(data) {
							$('#disc-loader').remove();
							$('#add-notif-discipline').show();
							if (data[0]) {
								if (data[0] == 'onlist') {
									alert('Już wybrałeś/aś tą dyscyplinę!');
								}
								else {
									$fields.find('.notify-disciplines').append('<li><img src="' + data[0] + '" alt="' + $fields.find('.discipline-list').val() + '" /><a class="del" href="/removenotificationdiscipline?discipline=' + $fields.find('.discipline-list').val() + '" title="Nie powiadamiaj o My-Sportach z tej dyscypliny">Nie powiadamiaj o My-Sportach z tej dyscypliny</a></li>');
									setDelListener($fields.find('.notify-disciplines').find('li:last'));
									setTimeout(function() {
										$fields.find('.discipline-list').val('');
									}, 200)
								}
							}
							else {
								$fields.find('.discipline-list').val('').focus();
							}
						}
					});
				}
			}
			$('#add-notif-discipline').click(function() {
				addDiscipline();
				return false;
			});
			$fields.find('.discipline-list').keypress(function(e) {
				if ($('.ac_results').css('display') == 'none') {
					if (/^13$/.test(e.keyCode)) {
						addDiscipline();
						return false;
					}
				}
			});
			$fields.find('.notify-disciplines li').each(function() {
				setDelListener($(this));
			});
		});
		
		//set frozen-overlay size
		$('#frozen-overlay').each(function() {
			var $this = $(this);
			$this.width($('html:first').width());
			$this.height($('#site').height() + 40);
		});
		
		//program functionality
		$('.show-modal').each(function() {
			var $this = $(this);
			if ($this.hasClass('ico-details')) {
				$this.click(function() {
					$.ajax({
						type: 'GET',
						dataType: 'html',
						url: '/myprofitaction?get=detail&id='+$this.attr('rel'),
						success: function(data) {
							if (data) {
								Modal.open($this.parent().find('.icon').attr('alt'), data);
								$('#modal').addClass('ico-details');
							}
						}
					});
					return false;
				})
			}
			else if ($this.hasClass('exchange')) {
				function funcExchange() {
					$this.click(function() {
						$this.unbind('click');
						$this.click(function() {
							return false;
						});
						$.ajax({
							type: 'GET',
							dataType: 'html',
							url: '/myprofitaction?get=exchange&id='+$this.attr('rel'),
							success: function(data) {
								if (data) {
									Modal.open('Wymień', data);
									setTimeout(function() {
										function funcAcc() {
											$('#modal-accept').click(function() {
												$('#modal-accept').unbind('click');
												$('#modal-accept').click(function() {
													return false;
												});
												var $btn = $(this);
												$.ajax({
													type: 'GET',
													dataType: 'json',
													url: $btn.attr('href'),
													data: 'ax',
													success: function(data) {
														if (data[0]) {
															var html = '<p class="center">' + data[0] + '</p>' +
																		'<div class="buttons single-button"><a id="modal-close" href="#" class="butt ok">OK</a></div>';
															$('#program .quant').text(data[1]);
															$('#prizes-table tbody tr').each(function() {
																var $row = $(this);
																if (parseInt($row.find('.price').text(), 10) > parseInt(data[1], 10)) {
																	$row.find('.exchange').after('<span class="exchange non-activ">Wymień</span>').remove();
																	$row.find('.gift').after('<span class="gift non-activ">Podaruj</span>').remove();
																}
															});
															Modal.close();
															Modal.open('Informacja', html);
															setTimeout(function() {
																$('#modal-close').click(function() {
																	Modal.close();
																	return false;
																});
															}, 100);
														}
														else {
															alert('Operacja nie powiodła się. Jeśli błąd będzie się powtarzał, skontaktuj się z Administratoirem.');
														}
														funcAcc();
													}
												});
												return false;
											});
										}
										funcAcc();
										$('#modal-cancel').click(function() {
											Modal.close();
											return false;
										});
										funcExchange();
									}, 100);
								}
							}
						});
						return false;
					});
				}
				funcExchange();
			}
			else if ($this.hasClass('gift')) {
				function funcGift() {
					$this.click(function() {
						$this.unbind('click');
						$this.click(function() {
							return false;
						});
						$.ajax({
							type: 'GET',
							dataType: 'html',
							url: '/myprofitaction?get=gift&id='+$this.attr('rel'),
							success: function(data) {
								if (data) {
									Modal.open('Podaruj', data);
									setTimeout(function() {
										function funcAccGift() {
											$('#modal-accept').click(function() {
												$('#modal-accept').unbind('click');
												$('#modal-accept').click(function() {
													return false;
												});
												var $btn = $(this);
												$.ajax({
													type: 'GET',
													dataType: 'json',
													url: $btn.attr('href'),
													data: 'login=' + $('#privilage-login').val() + '&ax',
													success: function(data) {
														if (data[0]) {
															var html = '<p class="center">' + data[0] + '</p>' +
																		'<div class="buttons single-button"><a id="modal-close" href="#" class="butt ok">OK</a></div>';
															$('#program .quant').text(data[1]);
															$('#prizes-table tbody tr').each(function() {
																var $row = $(this);
																if (parseInt($row.find('.price').text(), 10) > parseInt(data[1], 10)) {
																	$row.find('.exchange').after('<span class="exchange non-activ">Wymień</span>').remove();
																	$row.find('.gift').after('<span class="gift non-activ">Podaruj</span>').remove();
																}
															});
															Modal.close();
															Modal.open('Informacja', html);
															setTimeout(function() {
																$('#modal-close').click(function() {
																	Modal.close();
																	return false;
																});
															}, 100);
														}
														else {
															alert('Operacja nie powiodła się. Jeśli błąd będzie się powtarzał, skontaktuj się z Administratoirem.');
														}
														funcAccGift();
													}
												});
												return false;
											});
										}
										funcAccGift();
										$('#privilage-login').keypress(function(e) {
											if (/^13$/.test(e.keyCode)) {
												setTimeout(function() {
													$('#modal-accept').click();
												}, 100)
												return false;
											}
										});
										$('#modal-cancel').click(function() {
											Modal.close();
											return false;
										});
										funcGift();
									}, 100);
								}
							}
						});
						return false;
					});
				}
				funcGift();
			}
			else if ($this.hasClass('my-stats')) {
				var points = $('#gained-points').text();
				// var html = '<div id="stats-window">' +
								// '<div class="years"><span class="caption">Rok:</span><span class="year selected">2010</span></div>' +
								// '<div class="table-wrapper">' +
									// '<div class="table-inner-wrapper">' +
										// '<table>' + 
											// '<colgroup>' +
												// '<col class="size50" />' +
												// '<col class="size50" />' +
											// '</colgroup>' +
											// '<thead>' +
												// '<tr>' +
													// '<th scope="col">Miesiąc</th>' +
													// '<th scope="col">Punkty</th>' +
												// '</tr>' +
											// '</thead>' +
											// '<tbody>' +
												// '<tr>' +
													// '<td>styczeń</td>' +
													// '<td>10</td>' +
												// '</tr>' +
												// '<tr>' +
													// '<td>luty</td>' +
													// '<td>20</td>' +
												// '</tr>' +
											// '</tbody>' +
										// '</table>' +
									// '</div>' +
								// '</div>' +
							// '</div>';
				function funcStats() {
					$this.click(function() {
						$this.unbind('click');
						$this.click(function() {
							return false;
						});
						$.ajax({
							type: 'GET',
							dataType: 'html',
							url: '/myprofitaction?get=user_stats',
							success: function(data) {
								if (data) {
									Modal.open('Zdobyte punkty: ' + points, data);
									$('#modal').addClass('stats');
									$('a.stats-details').click(function() {
																				
										Modal.close();
										var html = '<div id="stats-window" class="details-window">' +
														'<div class="years"><span class="caption">Rok:</span><span class="year selected">2010</span></div>' +
														'<div class="table-wrapper">' +
															'<div class="table-inner-wrapper">' +
																'<table>' + 
																	'<colgroup>' +
																		'<col class="size60" />' +
																		'<col class="size20" />' +
																		'<col class="size20" />' +
																	'</colgroup>' +
																	'<thead>' +
																		'<tr>' +
																			'<th scope="col">Działanie</th>' +
																			'<th scope="col" class="small">Ilość</th>' +
																			'<th scope="col" class="small">Punkty</th>' +
																		'</tr>' +
																	'</thead>' +
																	'<tbody>' +
																		'<tr>' +
																			'<td>dodanie newsa</td>' +
																			'<td>5</td>' +
																			'<td>10</td>' +
																		'</tr>' +
																		'<tr>' +
																			'<td>dodanie imprezy</td>' +
																			'<td>10</td>' +
																			'<td>20</td>' +
																		'</tr>' +
																	'</tbody>' +
																'</table>' +
															'</div>' +
														'</div>' +
													'</div>';
										Modal.open('Zdobyte punkty', html);
										$('#modal').addClass('stats-details');
										return false;
									});
								}
								funcStats();
							}
						});
						return false;
					});
				}
				funcStats();
				// $this.click(function() {
					// Modal.open('Zdobyte punkty: ' + points, html);
					// $('#modal').addClass('stats');
					// return false;
				// });
			}
		});
		
		//loyalty program
		$('#program .choose-date').each(function() {
			var $this = $(this);
			$this.find('select').change(function() {
				var url = window.location.href;
				url = url.split('?')[0];
				window.location.href = url + '?month=' + $this.find('.month').val() + '&year=' + $this.find('.year').val();
			});
		});

		//select all messages in table
		$('.sel-all').click(function() {
			var $this = $(this);
			var $checks = $this.parents().find('table:first tbody input:checkbox');
			if (this.checked) {
				$checks.each(function() {
					this.checked = 1;
				});
			}
			else {
				$checks.each(function() {
					this.checked = 0;
				});
			}
		});
		
		//rating my-sports
		var copyBtnAdded = false;
		var rows = $('.comments-tbl tbody tr').length;
		if (rows > 1) {
			$('.comments-tbl').each(function() {
				var comm1 = false;
				var $tbl = $(this);
				$tbl.find('tbody tr').each(function() {
					var $tr = $(this);
					$tr.find('input:checkbox').click(function() {
						if (this.checked == 1) {
							$tr.addClass('show');
							if ($tbl.find('tbody input:checkbox:not(:checked)').length == 0) {
								$tbl.find('.sel-all-ms:first')[0].checked = 1;
							}
						}
						else {
							$tr.removeClass('show');
							$tbl.find('.sel-all-ms:first')[0].checked = 0;
						}
					});
					$tr.find('input:checkbox').each(function() {
						if (this.checked == 1) {
							$tr.addClass('show');
						}
						else {
							$tr.removeClass('show');
						}
					});
				});
				
				$tbl.find('.sel-all-ms').each(function() {
					var $this = $(this);
					$this.click(function() {
						var $checks = $this.parent().parent().parent().parent().find('tbody input:checkbox');
						if (this.checked) {
							$checks.each(function() {
								this.checked = 1;
								$(this).parent().parent().addClass('show');
							});
						}
						else {
							$checks.each(function() {
								this.checked = 0;
								$(this).parent().parent().removeClass('show');
							});
						}
					});
				});
				
				
				$('input.comment').focus(function() {
					$('.copy-comment').remove();
					$('.infotip.left-tip').remove();
					var html = '<a href="" class="button copy-comment"><span class="btn-inner">Kopiuj</span></a>' +
								'<img src="http://static.my-sport.pl/static/info.gif" alt="Informacja" class="infotip left-tip" />' +
								'<span class="tip-content">Wystaw taki sam komentarz wszystkim zaznaczonym użytkownikom</span>';
					$(this).parent().after(html);
					$('.copier').removeClass('copier');
					$(this).parent().parent().parent().addClass('copier');
					copyListener();
					Mysport.addTooltips();
				});
				
				function copyListener() {
					$('.copy-comment').click(function() {
						var comment = $('tbody tr.copier .comment').val();
						var mark = $('tbody tr.copier label input:radio:checked').parent()[0].className;
						$('tr.show').each(function() {
							var $tr = $(this);
							$tr.find('label.' + mark + ' input:radio').click();
							$tr.find('.comment').val(comment);
						});
						return false;
					});
				}
			});
		}
		
		//change captcha at reset password
		$('#reset-pass-change-capcha').each(function() {
			var $this = $(this);
			var src = $('#reset-pass-captcha').attr('src');
			$this.click(function() {
				var date = new Date();
				$('#reset-pass-captcha').attr('src', src+'?t='+date.getTime());
				return false;
			});
		});
		
		$('.reset-pass-change-capcha').each(function() {
			var $this = $(this);
			var src = $('.reset-pass-captcha').attr('src');
			$this.click(function() {
				var date = new Date();
				$('.reset-pass-captcha').attr('src', src+'?t='+date.getTime());
				return false;
			});
		});
		
	},
	
	disableButton: function($button) {
		$button.after('<span class="button disabled-btn"><span class="btn-inner">' + $button.text() + '</span></span>');
		$button.next().css('margin-left', '-' + $button.width() + 'px');
	},
	
	enableButton: function($button) {
		if ($button.next().hasClass('disabled-btn'))
		$button.next().remove();
	},
	
	albumFunctions: function() {
		function setDelAlbumListener($cont, type) {
			$cont.find('a.del-folder').click(function() {
				if (window.confirm('Czy na pewno chcesz usunąć ' + type + ' z folderu: ' + $cont.find('a.folder').text())) {
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: $(this).attr('href'),
						data: 'ax',
						success: function(data) {
							if (data) {
								if ($cont.next().hasClass('separator')) {
									$cont.next().remove();
								}
								if ($cont.parent().find('.folder-container').length == 2) {
									$cont.parent().find('.folder-container .del-folder').hide();
								}
								$cont.remove();
							}
							else {
								alert('Wystąpił błąd.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
							}
						}
					});
				}
				return false;
			});
		}
		$('#profile-photos .folders').each(function() {
			var $folders = $(this);
			$folders.find('.folder-container').each(function() {
				var $cont = $(this);
				setDelAlbumListener($cont, 'zdjęcie');
			});
			$('#profile-photos #assign-album-form').submit(function() {
				var $this = $(this);
				var data = $this.serialize();
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: $this.attr('action'),
					data: data + '&ax',
					success: function(data) {
						if (data) {
							var html = '<div class="folder-container">' +
											'<a class="folder" href="/dzikun/photos/list/album/' + data[0].id + '/0">' + data[0].title + '</a>' +
											'<a class="del-folder" href="/removefromalbum?albumid=' + data[0].id +'&photoid=' + $this.find('input[name="photoid"]').val() + '&redirect=/dzikun/photos/' + $this.find('input[name="photoid"]').val() + '/">Usuń zdjęcie z albumu</a>' +
										'</div>' +
										'<span class="separator">|</span>';
							$('#assign-album').before(html);
							setDelAlbumListener($folders.find('.folder-container:last'));
							$this.hide();
							$('#assign-album').show();
							$folders.find('.folder-container .del-folder').show();
						}
						else {
							alert('Wystąpił błąd, zdjęcie nie zostało dodane do albumu.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
						}
					}
				});
				return false;
			});
		});
		$('#profile-movies .folders').each(function() {
			var $folders = $(this);
			$folders.find('.folder-container').each(function() {
				var $cont = $(this);
				setDelAlbumListener($cont, 'filmik');
			});
			$('#profile-movies #assign-album-form').submit(function() {
				var $this = $(this);
				var data = $this.serialize();
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: $this.attr('action'),
					data: data + '&ax',
					success: function(data) {
						if (data) {
							var html = '<div class="folder-container">' +
											'<a class="folder" href="/dzikun/video/list/album/' + data[0].id + '/0">' + data[0].title + '</a>' +
											'<a class="del-folder" href="/removefromalbum?albumid=' + data[0].id +'&videoid=' + $this.find('input[name="videoid"]').val() + '&redirect=/dzikun/video/' + $this.find('input[name="videoid"]').val() + '/">Usuń filmik z albumu</a>' +
										'</div>' +
										'<span class="separator">|</span>';
							$('#assign-album').before(html);
							setDelAlbumListener($folders.find('.folder-container:last'));
							$this.hide();
							$('#assign-album').show();
							$folders.find('.folder-container .del-folder').show();
						}
						else {
							alert('Wystąpił błąd, filmik nie został dodany do albumu.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
						}
					}
				});
				return false;
			});
		});
		
		function setListenersToElList($list, caption) {
			$list.find('li').each(function() {
				var $li = $(this);
				var $a = $li.find('a.del-element:first');
				$a.click(function() {
					if (window.confirm('Czy na pewno chcesz usunąć '+ caption +': ' + $li.find('.title').text() + ' z albumu?')) {
						$.ajax({
							type: 'GET',
							dataType: 'json',
							url: $a.attr('href'),
							data: 'ax',
							success: function(data) {
								if (data) {
									$li.remove();
								}
								else {
									alert('Wystąpił błąd.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
								}
							}
						});
					}
					return false;
				});
			});
		}
		if (document.getElementById('profile-photos')) {
			setListenersToElList($('#profile-photos .elements-list'), 'zdjęcie');
		}
		else if (document.getElementById('profile-movies')) {
			setListenersToElList($('#profile-movies .elements-list'), 'filmik');
		}
	},
	
	addRating: function() {
		$('.rate-box').each(function() {
			var $ratebox = $(this);
			$ratebox.find('.rating').each(function(){
				var $rating_field = $(this);
				var $stars = $rating_field.find('.voting a');
				var $number = $rating_field.find('.number');
				$stars.each(function(i) {
					$(this).hover(function() {
						$this = $(this);
						$this.addClass('active');
						$this.prevAll().addClass('active');
						$number.text('(' + (i+1) + ')');
					}, function() {
						$stars.each(function() {
							$(this).removeClass('active');
						});
						$number.text('');
					});

					$(this).click(function() {
						if (moduleid && itemid) {
							if ($ratebox.hasClass('not-logged')) {
								return true;
							}
							else {
								$.ajax({
									type: 'GET',
									dataType: 'json',
									url: '/rate',
									data: 'moduleid='+moduleid+'&itemid='+itemid+'&rate='+(i+1)+'&ax',
									success: function(data) {
										if (data) {
											var your_rate = Math.round((i+1) * 20);
											var new_rating = 	'<div class="stars">' +
																	'<div class="stars-rate size'+ your_rate + '"></div>' +
																'</div>';
											$rating_field.html(new_rating);
											$rating_field.prev().text('Twoja ocena:');
											
											var overall_rate = Math.round((data) * 20);
											var new_overall_rate = '<div class="stars">' +
																		'<div class="stars-rate size'+ overall_rate + '"></div>' +
																	'</div>';
											$ratebox.find('.overall-rate .rating').html(new_overall_rate);
										}
									}
								});
								return false;
							}
						}
					});
				})
			});
		});
		
		

		$('.shoutbox li:not(.answer)').each(function() {
			var $comm = $(this);
			
			if ($comm.hasClass('blocked')) {
				$comm.find('a.show-blocked').click(function() {
					$(this).remove();
					$comm.removeClass('blocked');
					return false;
				});
			}
			
			var commid = $comm.attr('id').replace('comment_', '');
			$comm.find('.shout-vote a').click(function() {
				var $a = $(this);
				if ($a.attr('rel') != 'lo') {
					if (this.className == 'vote-yes') {
						var addon = 1;
					}
					else if (this.className == 'vote-no') {
						var addon = -1;
					}


					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: $a.attr('href'),
						data: 'ax',
						success: function(data) {
							if (data) {
								$comm.find('.shout-vote').remove();
								$comm.find('.score').text(parseInt($comm.find('.score').text(), 10) + addon);
							}
						}
					});
					return false;
				}
				else {
					return true;
				}
			});
		});
	},
	
	addConfirmations: function() {
		function addConfirmation($el, msg) {
			$el.click(function() {
				return window.confirm(msg);
			});
		}
		addConfirmation($('#profile-friends .del-user'), 'Czy na pewno chcesz usunąć tego użytkownika ze znajomych?');
		addConfirmation($('#group-members .del-user'), 'Czy na pewno chcesz usunąć tego użytkownika z grupy?');
		addConfirmation($('#leave-team'), 'Czy na pewno chcesz opuścić tą drużynę?');
		addConfirmation($('#leave-group'), 'Czy na pewno chcesz opuścić tą grupę?');
		addConfirmation($('#profile-friends .users-list .del-user'), 'Czy na pewno chcesz usunąć tego użytkownika ze znajomych?');
		addConfirmation($('.shoutbox li .del'), 'Czy na pewno chcesz usunąć ten komentarz?');
		addConfirmation($('#admin-del-el'), 'Czy na pewno chcesz usunąć ten element?');
		addConfirmation($('.element-features a.del-element'), 'Czy na pewno chcesz usunąć ten element?');
	},
	
	addWysiwyg: function() {
		$('textarea.wysiwyg').wysiwyg();
	},
	
	addSuggestions: function() {
		function removeListener($el) {
			$el.unbind('keypress').unbind('keydown');
		}
		
		//disciplines
		if ($('.discipline-list').length) {
			discipline_list = [];
			$.ajax({
				type: 'GET',
				dataType: 'json',
				url: '/action?get=disciplines',
				data: 'ax',
				success: function(data) {
					if (data) {
						for (i = 0; i < data.length; i++) {
							discipline_list[i] = data[i].name;
						}
						
						$('input.discipline-list').each(function() {
							var $this = $(this);
							$this.suggest(discipline_list);
							function discChosen() {
								if ($this.val() != '') {
									setTimeout(function() {
										var hit  = -1;
										for (i = 0; i < discipline_list.length; i++) {
											if ($this.val().toLowerCase() == discipline_list[i].toLowerCase()) {
												hit = i;
											}
										}
										if (hit != -1) {
											if ($this.next().hasClass('discipline-id')) {
												$this.next().val(data[hit].id);
											}
											else {
												$this.after('<input class="discipline-id" type="hidden" name="" value="' + data[hit].id + '" />');
											}
										}
										else {
											alert('nie ma takiej dyscypliny');
											$this.val('').focus();
										}
									}, 300);
								}
								else {
									if ($this.next().hasClass('discipline-id')) {
										$this.next().remove();
									}
								}
							}
							$this.blur(function() {
								discChosen();
							});
							// $this.keypress(function(e) {
								// if ($('.ac_results').css('display') == 'none') {
									// if (/^13$/.test(e.keyCode)) {
										// discChosen();
										// return false;
									// }
								// }
							// });
						});
					}
				}
			});
		}
		
		//cities
		if (document.getElementById('search-town2')) {
			$('#search-town2').suggest_ext('/action?get=towns', {
				minchars: 3
			});
		}
	},
	
	startCalendar: function() {
		$('.calendar').each(function() {
			var $cal = $(this);
			
			var myDate = new Date();
			actualDay = myDate.getDate();
			actualMonth = myDate.getMonth() + 1;
			if (!$.browser.msie) {
				actualYear = myDate.getYear() + 1900;
			}
			else {
				actualYear = myDate.getYear();
			}
			cal_month = actualMonth;
			cal_year = actualYear;
			
			var startMonth = 0;
			var endMonth = 0;
			var startDay = 0;
			var endDay = 0;
			var startYear = 0;
			var endYear = 0;
			
			function unifyUnit(val) {
				val = parseInt(val, 10);
				var new_val = val;
				if (val < 10) {
					new_val = '0' + '' + val;
				}
				return new_val;
			}
			
			daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];
			monthNames=['Stycze\u0144','Luty','Marzec','Kwiecie\u0144','Maj','Czerwiec','Lipiec','Sierpie\u0144','Wrzesie\u0144','Pa\u017Adziernik','Listopad','Grudzie\u0144'];
			function getDaysInMonth(month,year){
				month--;
				if ((month == 1 )&& (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
					return 29;
				}
				else {
					return daysInMonth[month];
				}
			}
			function getFirstDay(month,year) {
				month--;
				var firstDayDate = new Date(year,month,1);
				var firstDay = firstDayDate.getDay();
				var return_day = firstDay - 1;
				if (return_day == -1) {
					return 6;
				}
				else {
					return return_day;
				}
			}
			
			$cal.find('td').each(function(i) {
				this.className = '';
				$(this).text('');
				if (++i % 7 == 0) {
					$(this).addClass('sun');
				}
			});
			
			
			function drawCalendar() {
				var start = getFirstDay(cal_month, cal_year);
				var all = getDaysInMonth(cal_month, cal_year);
				var today_day = actualDay;
				var count = 1;
				var other_count = 1;
				$cal.find('.cal-h-inner > span').text(monthNames[cal_month-1] + ' ' + cal_year);
				$cal.find('td').each(function(i) {
					var $this = $(this);
					if ($this.hasClass('today')) {
						$this.removeClass('today');
					}
					if ($this.hasClass('start')) {
						$this.removeClass('start');
					}
					if ($this.hasClass('end')) {
						$this.removeClass('end');
					}
					if ($this.hasClass('other')) {
						$this.removeClass('other');
					}
					if (i < start) {
						var daysMonthOther = getDaysInMonth(cal_month-1, cal_year);
						var other_day = daysMonthOther - (start - i - 1);
						if ($cal.hasClass('big-calendar')) {
							$this.html('<div class="top"><span class="day">' + other_day + '</span></div><div class="list"></div>');
							$this.addClass('other');
							$this.removeAttr('id');
						}
						else {
							$this.html('');
							$this.removeAttr('id');
						}
					}
					else if (i >= start && count <= all) {
						if ($cal.hasClass('big-calendar')) {
							$this.html('<div class="top"><span class="day">' + count++ + '</span></div><div class="td-wrapper"></div><div class="list"></div>');
						}
						else {
							if (document.getElementById('my-sport-list')) {
								$this.html('<a href="#">' + count++ + '</a>');
							}
							else {
								$this.html('<span>' + count++ + '</span>');
							}
						}
						$this.attr('id', 'day_' + (count-1));
						if (cal_month == actualMonth && today_day == count-1 && cal_year == actualYear) {
							$this.addClass('today');
						}
						if (cal_month == startMonth && startDay == count-1 && cal_year == startYear) {
							$this.addClass('start');
						}
						if (cal_month == endMonth && endDay == count-1 && cal_year == endYear) {
							$this.addClass('end');
						}
					}
					else {
						var daysMonthOther = getDaysInMonth(cal_month+1, cal_year);
						$this.removeAttr('id');
						if ($cal.hasClass('big-calendar')) {
							if (cal_month == 8){
								// console.log($this);
								// console.log(count);
								// console.log(i);
								// console.log('------');
							}
							if ((i >= 35 && (start + count > 36)) || (i < 35)) {
								if ($cal.hasClass('big-calendar')) {
									$this.html('<div class="top"><span class="day">' + other_count++ + '</span></div><div class="list"></div>');
									$this.addClass('other');
								}
							}
							else {
								$this.html('');
							}
						}
						else {
							$this.html('');
						}
					}
					// else {
						// if ($this.hasClass('sun')) {
							// $this.removeClass('sun');
						// }
						// $this.removeAttr('id');
						// $this.html('');
					// }
				});
				if (document.getElementById('my-sport-list')) {
					if ($cal.parent().attr('id') == "search-mysport-calendar") {
						var type = true;
						setListeners(type);
					}
					if ($cal.parent().attr('id') == "search-mysport-calendar2") {
						var type = false;
						setListeners(type);
					}
				}
				else if (document.getElementById('profile-blog')) {
					setBlogListeners();
				}
				else if (document.getElementById('user-calendar')) {
					showItems();
				}
			}
			
			function nextMonth() {
				cal_month++;
				if (cal_month > 12) {
					cal_month = 1;
					cal_year++;
				}
				drawCalendar();
			}
			
			function prevMonth() {
				cal_month--;
				if (cal_month < 1) {
					cal_month = 12;
					cal_year--;
				}
				drawCalendar();
			}
			
			$cal.find('.next-month').click(function() {
				nextMonth();
				return false;
			});
			
			$cal.find('.prev-month').click(function() {
				prevMonth();
				return false;
			});
			
			function showItems() {
				if (!document.getElementById('cal-loader')) {
					$cal.find('.cal-h-inner').append('<img src="http://static.my-sport.pl/static/loaders/form-loader.gif" alt="" id="cal-loader" />');
				}
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: '/action?get=calendaritems',
					data: 'login='+login+'&yearmonth='+cal_year+'-'+unifyUnit(cal_month) + '&ax',
					success: function(data) {
						$('#cal-loader').remove();
						if (data && data.length) {
							for (i = 0; i < data.length; i++) {
								var $day = $('#day_'+parseInt(data[i].day, 10));
								$day.find('.list').append('<ul class="events"></ul>');
								for (j = 0; j < data[i].items.length; j++) {
									$day.find('.events').append('<li class="' + data[i].items[j].type + '"><a href="' + data[i].items[j].link + '">' + data[i].items[j].title + '</a></li>');
								}
								if (data[i].items.length > 4) {
									$day.find('.top').prepend('<div class="extend"><a href="#">rozwiń</a></div>');
									$day.find('.td-wrapper').append('<div class="extended-box">' + $day.find('.list').html() + '<a href="#" class="close-cal-details" title="Schowaj szczegóły">Schowaj szczegóły</a></div>');
									if ($day.prevAll().length < 2) {
										$day.find('.extended-box').addClass('to-right');
									}
									else {
										$day.find('.extended-box').addClass('to-left');
									}
									$day.find('.extend a').click(function() {
										var $td = $(this).parent().parent().parent();
										if ($td.hasClass('extended')) {
											$td.removeClass('extended');
											$td.find('extended-box').hide();
											$(this).text('rozwiń');
											
										}
										else {
											$td.addClass('extended');
											$td.find('extended-box').show();
											$(this).text('zwiń');
										}
										return false;
									});
									$day.find('.close-cal-details').click(function() {
										var $td = $(this).parent().parent().parent();
										$td.removeClass('extended');
										$td.find('.extend a').text('rozwiń');
										return false;
									});
								}
							}
							
						}
					}
				});
			}
			
			function setBlogListeners() {
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: '/entrydayslist',
					data: 'userid='+userid+'&year='+cal_year+'&month='+cal_month + '&ax',
					success: function(data) {
						if (data) {
							for (i = 0; i < data.length; i++) {
								var $day = $('#day_'+parseInt(data[i].day, 10));
								$day.addClass('entry').html('<a href="' + data[i].link + '">' + $day.text() + '</a>');
							}
						}
					}
				});
			}
			
			function setListeners(start) {
				$cal.find('td a').unbind('click');
				$cal.find('td a').click(function() {
					var $this = $(this);
					if (start) {
						startDay = unifyUnit($this.parent().attr('id').replace('day_', ''));
						startMonth = unifyUnit(cal_month);
						startYear = unifyUnit(cal_year);
						$cal.find('td').removeClass('start');
						$this.parent().addClass('start');
						//$cal.find('.from .date span').text(startDay+'-'+startMonth+'-'+startYear);
						//$cal.find('.from').show();
						//type = false;
						//setListeners(type);
						$('#search-from .date').text(startDay+'-'+startMonth+'-'+startYear);
					}
					else {
						endDay = unifyUnit($this.parent().attr('id').replace('day_', ''));
						endMonth = unifyUnit(cal_month);
						endYear = unifyUnit(cal_year);
						$cal.find('td').removeClass('end');
						$this.parent().addClass('end');
						//$cal.find('.to .date span').text(endDay+'-'+endMonth+'-'+endYear);
						//$cal.find('.to').show();
						//type = true;
						//setListeners(type);
						//$('#search-to').show();
						$('#search-to .date').text(endDay+'-'+endMonth+'-'+endYear);
					}
					
					return false;
				});
			}
			
			function submitCal() {
				var filter  = /^0\-0\-0/;
				if ($cal.parent().attr('id') == "search-mysport-calendar") {
					var datefrom = startYear+'-'+startMonth+'-'+startDay+' '+unifyUnit($('#cal-start-hour').val())+':'+unifyUnit($('#cal-start-minute').val());
					if (filter.test(datefrom)) {
						$('#cal-datefrom').val('');
					}
					else {
						$('#cal-datefrom').val(datefrom);
					}
				}
				if ($cal.parent().attr('id') == "search-mysport-calendar2") {
					var dateto = endYear+'-'+endMonth+'-'+endDay+' '+unifyUnit($('#cal-end-hour').val())+':'+unifyUnit($('#cal-end-minute').val());
					if (filter.test(dateto)) {
						$('#cal-dateto').val('');
					}
					else {
						$('#cal-dateto').val(dateto);
					}
				}
			}
			
			if (document.getElementById('my-sport-list')) {
				if ($cal.parent().attr('id') == "search-mysport-calendar") {
					var type = true;
					setListeners(type);
				}
				if ($cal.parent().attr('id') == "search-mysport-calendar2") {
					var type = false;
					setListeners(type);
				}
			}
			
			$('#my-sport-search .submit-timing').click(function() {
				$cal.hide();
				submitCal();
				return false;
			});
			
			$('#search-timing').click(function() {
				if ($cal.css('display')  == 'none') {
					$cal.show();
					$('body').click(function(e) {
						if ($(e.target).parents('#search-mysport-calendar').length == 0) {
							submitCal();
							$cal.hide();
							$('body').unbind('click');
						}
					})
				}
				else {
					$cal.hide();
					submitCal();
					$('body').unbind('click');
				}
				return false;
			});
			
			if ($cal.parent().attr('id') == "search-mysport-calendar") {
				$('.from-cal').click(function() {
					if ($cal.css('display')  == 'none') {
						$('#search-mysport-calendar2 .calendar').hide();
						$cal.show();
						$('body').click(function(e) {
							if ($(e.target).parents('#search-mysport-calendar').length == 0) {
								submitCal();
								$cal.hide();
								$('body').unbind('click');
							}
						})
					}
					else {
						$cal.hide();
						submitCal();
						$('body').unbind('click');
					}
					return false;
				});
			}
			if ($cal.parent().attr('id') == "search-mysport-calendar2") {
				$('.to-cal').click(function() {
					if ($cal.css('display')  == 'none') {
						$('#search-mysport-calendar .calendar').hide();
						$cal.show();
						$('body').click(function(e) {
							if ($(e.target).parents('#search-mysport-calendar2').length == 0) {
								submitCal();
								$cal.hide();
								$('body').unbind('click');
							}
						})
					}
					else {
						$cal.hide();
						submitCal();
						$('body').unbind('click');
					}
					return false;
				});
			}
	
			if (document.getElementById('profile-blog')) {
				var blog_month = (blog_date).split('-')[0];
				var blog_year = (blog_date).split('-')[1];
				cal_month = blog_month;
				cal_year = blog_year;
			}
			
			drawCalendar();
		});
	},
	
	addTooltips:function() {
		function showTip($el) {
			$el.bt({
				// showTip: function(box){
					// $(box).fadeIn(500);
				// },
				// hideTip: function(box, callback){
					// $(box).animate({opacity: 0}, 500, callback);
				// },
				contentSelector: '$(this).next().html()',
				shrinkToFit: true,
				hoverIntentOpts: {
					interval: 0,
					timeout: 0
				},
				fill: '#374455',
				strokeWidth: 2,
				strokeStyle: '#fff',
				cssStyles: {color: 'white', fontWeight: 'bold', fontSize: '11px'},
				shrinkToFit: true,
				padding: 10,
				cornerRadius: 5,
				spikeLength: 15,
				spikeGirth: 15,
				positions: ['right', 'left', 'bottom']
			});
		}
		//showTip($('#id_forteam_yes'));
		$('.infotip').each(function() {
			var $this = $(this);
			if ($this.hasClass('left-tip')) {
				$this.bt({
					contentSelector: '$(this).next().html()',
					shrinkToFit: true,
					hoverIntentOpts: {
						interval: 0,
						timeout: 0
					},
					fill: '#374455',
					strokeWidth: 2,
					strokeStyle: '#fff',
					cssStyles: {color: 'white', fontWeight: 'bold', fontSize: '11px'},
					shrinkToFit: true,
					padding: 10,
					cornerRadius: 5,
					spikeLength: 15,
					spikeGirth: 15,
					positions: ['left']
				});
			}
			else {
				showTip($this);
			}
		});
	},
	
	showMap: function() {
		var map_container = document.getElementById('map');
		function mapsLoaded() {
			
			if (google.maps.BrowserIsCompatible()) {
				Mysport.stopMapLoader();
				var map = new google.maps.Map2(map_container);
				var geocoder = new google.maps.ClientGeocoder();
				var redIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/user_red.png');
				var orangeIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/mysport_orange.png');
				if (document.getElementById('team')) {
					var icon = orangeIcon;
				} 
				else {
					var icon = redIcon;
				}
				if (user_lat != '' && user_lng != '') {
					var point = new GLatLng(user_lat, user_lng);
					map.setCenter(point, 12);
					var marker = new GMarker(point, icon);
					map.addOverlay(marker);
					map.setMapType(G_NORMAL_MAP);
					map.addControl(new google.maps.SmallMapControl());
				}
				else {
					google.maps.Unload();
					if (is_owner) {
						$('#map').html('<a class="location-not-set" href="/settings/data#map-location">Ustaw swoją lokalizację!</a>');
					}
					else {
						$(map_container).parents('.section:first').remove();
					}
				}
				/*
				else {
					var $address = $('address.mapped');
					var address = '';
					if ($address.find('.street').text() != '') {
						address += $address.find('.street').text() + ', ';
					}
					if ($address.find('.city').text() != '') {
						address += $address.find('.city').text() + ', ';
					}
					if (address != '') { 
						address += 'Polska';
					}
					geocoder.getLatLng(
						address,
						function(point) {
						  if (!point) {
							google.maps.Unload();
							$(map_container).parents('.section:first').remove();
						  } else {
							map.setCenter(point, 12);
							var marker = new GMarker(point, icon);
							map.addOverlay(marker);
						  }
						}
					  );
				}
				*/
			}
		}
		
		function loadMaps() {
			google.load("maps", "2", {"callback" : mapsLoaded});
		}
		
		loadMaps();
	},
	
	showMysportMap: function() {
		var map_container = document.getElementById('mysport-map');
		function mapsLoaded() {
			if (google.maps.BrowserIsCompatible()) {
				function execute(hostMarker) {
					map.addOverlay(hostMarker);
					var options_html = '<ul class="map-options">' +
											'<li id="show-path">' +
												'<a href="#">Pokaż trasę dojazdu</a>' +
											'</li>' +
											'<li id="show-participants">' +
												'<a href="#">Pokaż uczestników</a>' +
											'</li>' +
											'<li id="other-mysports">' +
												'<a href="#">My-Sport w okolicy</a>' +
											'</li>' +
										'</ul>';
					$('#mysport-map').after(options_html);
					var $options = $('#my-sport .map-options');
					$options.find('li').each(function() {
						var $li = $(this);
						$li.find('a').click(function() { 					// get directions clicked
							$options.find('.selected').removeClass('selected');
							$li.addClass('selected');
							function execute(point) {
								$('#mysport-map').before('<div id="map-directions"><a id="close-directions" href="">Zamknij</a><div id="directions-instructions"></div></div><div id="map-address"><p class="title">Zmień miejsce startu</p><label>Podaj nowy adres poniżej:</label><div class="columns"><p class="caption">Ulica</p><div class="field"><input type="text" id="new-street" /></div></div><div class="columns"><p class="caption">Miejscowość</p><div class="field"><input type="text" id="new-town" /></div><a id="show-new-directions" class="button" href=""><span class="btn-inner">Pokaż</span></a> </div><div>');
								var directions = new GDirections(map, document.getElementById('directions-instructions'));
								var waypoints = new Array(point, hostMarker.getLatLng());
								map.clearOverlays();
								directions.loadFromWaypoints(waypoints);
								$('#close-directions').click(function() {
									resetMap();
									$('#map-directions').remove();
									$('#map-address').remove();
									return false;
								});
								$('#show-new-directions').click(function() {
									geocoder.getLatLng(
										$('#new-street').val() + ', ' + $('#new-town').val() + ', Polska',
										function(point) {
										  if (!point) {
											alert('Nie znaleziono tej lokalizacji');
										  } else {
											map.clearOverlays();
											var waypoints = new Array(point, hostMarker.getLatLng());
											directions.loadFromWaypoints(waypoints);
										  }
										}
									  );
									return false;
								});
							}
							if ($li.attr('id') == 'show-path') {
								if (user_lat == '' || user_lng == '') {
									var address = '';
									if (user_street != '') {
										address += ' ' + user_street;
									}
									if (user_house != '') {
										address += ' ' + user_house;
									}
									if (user_city != '') {
										address += ', ' + user_city;
									}
									if (user_code != '') {
										address += ' ' + user_code;
									}
									address += ', Polska';  			 	// Hard coded Poland for the time being :)
									geocoder.getLatLng(
										address,
										function(point) {
										  if (point) {
											execute(point);
										  }
										  else {
											$li.removeClass('selected');
											alert('Opcja niedostępna. Nie masz ustawionego adresu lub/i lokalizacji na swoim profilu.\nMożesz to zrobić w ustawieniach.');
											}
										 }
									  );
								}
								else {
									execute(new GLatLng(user_lat, user_lng));
								}
								
							}
							else if ($li.attr('id') == 'other-mysports') {					// get other my-sports clicked
								var originLat = hostMarker.getLatLng().y;
								var originLng = hostMarker.getLatLng().x;
								$.ajax({
									type: 'GET',
									dataType: 'json',
									url: '/action',
									data: 'get=mysports&lat='+originLat+'&lng='+originLng+'&radius='+50 + '&ax',
									success: function(data) {
										if (data) {
											resetMap();
											for (i = 0; i < data.length; i++) {
												var mrkr = new GMarker(new GLatLng(data[i].lat, data[i].lng), yellowIcon);
												map.addOverlay(mrkr);
												addInfo(mrkr, data[i].id, data[i].title);
												$li.addClass('selected');
											}
											map.setCenter(hostMarker.getLatLng(), 12);
										}
									}
								});
								function addInfo(marker, id, title) {
									var html = '<div class="map-bubble">' +
													'<p class="title"><a href="/mysport/' + id + '">' + title + '</a></p>' +
												'</div>';
									marker.bindInfoWindowHtml(html);
								}
							}
							else if ($li.attr('id') == 'show-participants') {	
								$.ajax({
									type: 'GET',
									dataType: 'json',
									url: '/action',
									data: 'get=mysportparticipants&mysportid='+mysportid + '&ax',
									success: function(data) {
										if (data) {
											resetMap();
											for (i = 0; i < data.length; i++) {
												var mrkr = new GMarker(new GLatLng(data[i].lat, data[i].lng), blueIcon);
												map.addOverlay(mrkr);
												addInfo(mrkr, data[i].avatar, data[i].login)
											}
											map.setCenter(hostMarker.getLatLng(), 12);
											$li.addClass('selected');
										}
									}
								});
								function addInfo(marker, avatar_url, login) {
									var html = '<div class="map-bubble">' +
													'<div class="bubble-pic"><a href="/' + login + '"><img src="' + avatar_url + '" alt="' + login + '" /></a></div>' +
														'<div class="bubble-content">' +
															'<p class="title"><a href="/' + login + '">' + login + '</a></p>' +
															'<div class="disciplines">' +
														'</div>' +
													'</div>' +
												'</div>';
									marker.bindInfoWindowHtml(html);
								}
							}
							return false;
						});
					});
					
					function resetMap() {
						map.clearOverlays();
						map.addOverlay(hostMarker);
						map.setCenter(hostMarker.getLatLng(), 13);
						$options.find('.selected').removeClass('selected');
						$('#map-directions').remove();
						$('#map-address').remove();
					}
				}
				Mysport.stopMapLoader();
				var map = new google.maps.Map2(map_container);
				var geocoder = new google.maps.ClientGeocoder();
				map.setMapType(G_NORMAL_MAP);
				map.addControl(new google.maps.LargeMapControl());
				var redIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/user_red.png');
				var blueIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/user_blue.png');
				var orangeIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/mysport_orange.png');
				var yellowIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/mysport_yellow.png');
				if (lat == '' || lng == '') {
					var $address= $('address.mapped');
					var address = $address.find('.street').text() + ', ' +$address.find('.code-city').text();
					geocoder.getLatLng(
						address,
						function(point) {
						  if (!point) {
							google.maps.Unload();
							$(map_container).remove();
						  } else {
							map.setCenter(point, 13);
							var marker = new GMarker(point, orangeIcon);
							execute(marker);
						  }
						}
					  );
				}
				else {
					var point = new GLatLng(lat, lng);
					map.setCenter(point, 13);
					var marker = new GMarker(point, orangeIcon);
					map.addOverlay(marker);
					execute(marker);
				}
				
				
				
			}
		}
		
		function loadMaps() {
			google.load("maps", "2", {"callback" : mapsLoaded});
		}
		
		loadMaps();
	},
	
	geolocShowMap: function() {
		$('#set-geolocation').click(function() {
			var $set_link = $(this);
			var $cont = $('#map-location');
			
			function mapsLoaded() {
				$set_link.after('<a href="#" class="button"><span class="btn-inner">Aktualizuj mapę</span></a>');
				var $update_link = $set_link.next();
				$set_link.remove();
				
				if (google.maps.BrowserIsCompatible()) {
					Mysport.stopMapLoader();
					var map = new google.maps.Map2(map_container);
					var geocoder = new google.maps.ClientGeocoder();
					var redIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/user_red.png');
					if ($('#lat').val() == '' || $('#lat').val() == null || $('#lng').val() == '' || $('#lng').val() == null) {
						geocoder.getLatLng(
							getAddress(),
							function(point) {
							  if (!point) {
								//google.maps.Unload();
								//$(map_container).remove();
								alert('Nie znaleziono podanego adresu. Wpisz poprawny adres i zaktualizuj mapę');
							  } else {
								saveLatLng(point.y, point.x);
								map.setCenter(point, 15);
								var marker = new GMarker(point, {draggable: true});
								map.addOverlay(marker);
								GEvent.addListener(marker, "dragend", function() {
									y = marker.getPoint().lat();
									x = marker.getPoint().lng();
									saveLatLng(y, x);
									map.panTo(new GLatLng(y, x));
								});
							  }
							  $update_link.click(function() {
								$geomap_wrapper.show();
								geocoder.getLatLng(getAddress(), function(new_point) {
									if (!new_point) {
										alert('Nie znaleziono szukanej lokalizacji.');
									}
									else {
										if (!marker) {
											geocoder.getLatLng(
												getAddress(),
												function(point) {
												  if (!point) {
													alert('Nie znaleziono podanego adresu. Wpisz poprawny adres i zaktualizuj mapę');
												  } else {
													marker = new GMarker(point, {draggable: true});
													map.addOverlay(marker);
													map.setCenter(point, 15);
													GEvent.addListener(marker, "dragend", function() {
														y = marker.getPoint().lat();
														x = marker.getPoint().lng();
														saveLatLng(y, x);
														map.panTo(new GLatLng(y, x));
													});
												  }
												}
											  );
										}
										else {
											marker.setPoint(new_point, redIcon);
											map.panTo(new_point);
											saveLatLng(new_point.y, new_point.x);
										}
									}
								});
								return false;
							});
							}
						  );
					}
					else {
						var point = new GLatLng($('#lat').val(),  $('#lng').val());
						map.setCenter(point, 15);
						var marker = new GMarker(point, {draggable: true, icon: redIcon});
						map.addOverlay(marker);
						GEvent.addListener(marker, "dragend", function() {
							y = marker.getPoint().lat();
							x = marker.getPoint().lng();
							saveLatLng(y, x);
							map.panTo(new GLatLng(y, x));
						});
						$update_link.click(function() {
							geocoder.getLatLng(getAddress(), function(new_point) {
								if (!new_point) {
									alert('Nie znaleziono szukanej lokalizacji.');
								}
								else {
									marker.setPoint(new_point);
									map.panTo(new_point);
									saveLatLng(new_point.y, new_point.x);
								}
							});
							return false;
						});
					}
					
					
					map.setMapType(G_NORMAL_MAP);
					map.addControl(new google.maps.SmallMapControl());
				}
			}
			function getAddress() {
				var address = '';
				if ($('#map-street').val() != '' && $('#map-street').val() != null) {
					address = $cont.find('#map-street').val() + ' ';
				}
				if ($('#map-housenumber').val() != '' && $('#map-housenumber').val() != null) {
					address += $('#map-housenumber').val();
				}
				if ($('#map-code1').val() != '' && $('#map-code1').val() != null && $('#map-code2').val() != '' && $('#map-code2').val() != null) {
					address += ', ' + $('#map-code1').val() + '-' + $('#map-code2').val();
				}
				address += ', ' + $cont.find('#search-town').val();
				if ($('#map-province').val() != -1) {
					address += ', ' + $cont.find('#map-province option:selected').text();
				}
				address += ', Polska'; 								// Hard coded Poland for the time being :)
				return address;
			}
			function saveLatLng(lat, lng) {
				$('#lat').val(lat);
				$('#lng').val(lng);
				if (!document.getElementById('locationSet')) {
					$('#map-location').append('<input type="hidden" name="locationSet" id="locationSet" value="1" />');
				}
			}
			
			function loadMaps() {
				google.load("maps", "2", {"callback" : mapsLoaded});
			}
			
			
			if ($cont.find('#search-town').val() == '' || $cont.find('#search-town').val() == null) {
				Mysport.displayLightError($('#set-geolocation').parents('.cell:first'), 'Aby ustawić lokalizację na mapie, musisz wpisać przynajmniej miejscowość.');
			}
			else {
				$cont.append('<div id="geomap-wrapper"><div id="geomap" class="gmap"></div><div class="map-caption">Przeciągnij wskaźnik na mapie myszką, aby ustalić dokładną lokalizację.</div><a id="hide-geomap" href="#" title="Schowaj mapę">Ukryj mapę</a></div>');
				var $geomap_wrapper = $cont.find('#geomap-wrapper');
				var $geomap = $cont.find('#geomap');
				$geomap_wrapper.height($cont.height()-72);
				$geomap.height($cont.height()-96);
				
				var map_container = document.getElementById('geomap');
				$set_link.unbind('click').click(function(){return false;});
				Mysport.startMapLoader();
				loadMaps();
				
				$('#hide-geomap').click(function() {
					$geomap_wrapper.hide();
					return false;
				});
			}
			
			return false;
		});
		
	},
	
	geolocShowMap2: function() {
		$('#set-geolocation2').click(function() {
			var $set_link = $(this);
			var $cont = $('#map-location2');
			
			function mapsLoaded() {
				$set_link.after('<a href="#" class="button"><span class="btn-inner">Aktualizuj mapę</span></a>');
				var $update_link = $set_link.next();
				$set_link.remove();
				
				if (google.maps.BrowserIsCompatible()) {
					Mysport.stopMapLoader();
					var map = new google.maps.Map2(map_container);
					var geocoder = new google.maps.ClientGeocoder();
					var redIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/user_red.png');
					if ($('#lat').val() == '' || $('#lat').val() == null || $('#lng').val() == '' || $('#lng').val() == null) {
						geocoder.getLatLng(
							getAddress(),
							function(point) {
							  if (!point) {
								//google.maps.Unload();
								//$(map_container).remove();
								alert('Nie znaleziono podanego adresu. Wpisz poprawny adres i zaktualizuj mapę');
							  } else {
								saveLatLng(point.y, point.x);
								map.setCenter(point, 15);
								var marker = new GMarker(point, {draggable: true});
								map.addOverlay(marker);
								GEvent.addListener(marker, "dragend", function() {
									y = marker.getPoint().lat();
									x = marker.getPoint().lng();
									saveLatLng(y, x);
									map.panTo(new GLatLng(y, x));
								});
							  }
							  $update_link.click(function() {
								$geomap_wrapper.show();
								geocoder.getLatLng(getAddress(), function(new_point) {
									if (!new_point) {
										alert('Nie znaleziono szukanej lokalizacji.');
									}
									else {
										if (!marker) {
											geocoder.getLatLng(
												getAddress(),
												function(point) {
												  if (!point) {
													alert('Nie znaleziono podanego adresu. Wpisz poprawny adres i zaktualizuj mapę');
												  } else {
													marker = new GMarker(point, {draggable: true});
													map.addOverlay(marker);
													map.setCenter(point, 15);
													GEvent.addListener(marker, "dragend", function() {
														y = marker.getPoint().lat();
														x = marker.getPoint().lng();
														saveLatLng(y, x);
														map.panTo(new GLatLng(y, x));
													});
												  }
												}
											  );
										}
										else {
											marker.setPoint(new_point, redIcon);
											map.panTo(new_point);
											saveLatLng(new_point.y, new_point.x);
										}
									}
								});
								return false;
							});
							}
						  );
					}
					else {
						var point = new GLatLng($('#lat').val(),  $('#lng').val());
						map.setCenter(point, 15);
						var marker = new GMarker(point, {draggable: true, icon: redIcon});
						map.addOverlay(marker);
						GEvent.addListener(marker, "dragend", function() {
							y = marker.getPoint().lat();
							x = marker.getPoint().lng();
							saveLatLng(y, x);
							map.panTo(new GLatLng(y, x));
						});
						$update_link.click(function() {
							geocoder.getLatLng(getAddress(), function(new_point) {
								if (!new_point) {
									alert('Nie znaleziono szukanej lokalizacji.');
								}
								else {
									marker.setPoint(new_point);
									map.panTo(new_point);
									saveLatLng(new_point.y, new_point.x);
								}
							});
							return false;
						});
					}
					
					
					map.setMapType(G_NORMAL_MAP);
					map.addControl(new google.maps.SmallMapControl());
				}
			}
			function getAddress() {
				var address = '';
				if ($('#map-street2').val() != '' && $('#map-street2').val() != null) {
					address = $cont.find('#map-street2').val() + ' ';
				}
				if ($('#map-housenumber2').val() != '' && $('#map-housenumber2').val() != null) {
					address += $('#map-housenumber2').val();
				}
				if ($('#map-code12').val() != '' && $('#map-code12').val() != null && $('#map-code22').val() != '' && $('#map-code22').val() != null) {
					address += ', ' + $('#map-code12').val() + '-' + $('#map-code22').val();
				}
				address += ', ' + $cont.find('#search-town2').val();
				if ($('#map-province2').val() != -1) {
					address += ', ' + $cont.find('#map-province2 option:selected').text();
				}
				address += ', Polska'; 								// Hard coded Poland for the time being :)
				return address;
			}
			function saveLatLng(lat, lng) {
				$('#lat2').val(lat);
				$('#lng2').val(lng);
				if (!document.getElementById('locationSet2')) {
					$('#map-location2').append('<input type="hidden" name="locationSet" id="locationSet2" value="1" />');
				}
			}
			
			function loadMaps() {
				google.load("maps", "2", {"callback" : mapsLoaded});
			}
			
			
			if ($cont.find('#search-town2').val() == '' || $cont.find('#search-town2').val() == null) {
				Mysport.displayLightError($('#set-geolocation2').parents('.cell:first'), 'Aby ustawić lokalizację na mapie, musisz wpisać przynajmniej miejscowość.');
			}
			else {
				$cont.append('<div id="geomap-wrapper2"><div id="geomap2" class="gmap"></div><div class="map-caption">Przeciągnij wskaźnik na mapie myszką, aby ustalić dokładną lokalizację.</div><a id="hide-geomap" href="#" title="Schowaj mapę">Ukryj mapę</a></div>');
				var $geomap_wrapper = $cont.find('#geomap-wrapper2');
				var $geomap = $cont.find('#geomap2');
				$geomap_wrapper.height(250);
				$geomap.height($geomap_wrapper.height()-24);
				
				var map_container = document.getElementById('geomap2');
				$set_link.unbind('click').click(function(){return false;});
				Mysport.startMapLoader();
				loadMaps();
				
				$('#hide-geomap').click(function() {
					$geomap_wrapper.hide();
					return false;
				});
			}
			
			return false;
		});
		
	},
	
	neightShowMap: function() {
		startLoader();
		var map_container = document.getElementById('map-neighbours');
		function mapsLoaded() {
			var redIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/user_red.png');
			var blueIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/user_blue.png');
			var orangeIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/mysport_orange.png');
			var yellowIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/mysport_yellow.png');
			GMarker.prototype.hide = function () {
				if (this.getPoint().lat() < 90) try { this.savePoint = this.getPoint(); 
					this.setPoint(new GLatLng(90, 0)); 
				} catch(e) {} 
			} 
			GMarker.prototype.show = function () {
				if (this.getPoint().lat() == 90) 
					if (this.savePoint) try { 
						this.setPoint(this.savePoint); 
						this.savePoint = null; 
					} catch(e) {
				}
			}			
			if (google.maps.BrowserIsCompatible()) {
				Mysport.stopMapLoader();
				var map = new google.maps.Map2(map_container);
				var geocoder = new google.maps.ClientGeocoder();
				map.setMapType(G_NORMAL_MAP);
				map.addControl(new google.maps.LargeMapControl());
				
				
				function execute(map) {
					var mgr = null;
					var markers = [];
					function initGMarkerManager() {
						mgr = new GMarkerManager(map);
				    }
					function resetManager() {
						 if (markers != null  &&  markers.length > 0 ){
							map.clearOverlays();
							for (i = 0; i < markers.length; i++) {
								markers[i].hide();
							}
							markers = [];
							initGMarkerManager();
						 } 
					}
					initGMarkerManager();
					var basic_radius = 10;
					$('#neighbours-search-form .radius-field').val(basic_radius);
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: '/action',
						data: 'get=neighbours&lat='+neighbours_lat+'&lng='+neighbours_lng+'&radius='+basic_radius + '&ax',
						success: function(data) {
							if (data) {
								buildList(data);
								for (i = 0; i < data.length; i++) {
									var mrkr = new GMarker(new GLatLng(data[i].lat, data[i].lng), blueIcon);
									markers.push(mrkr);
									mgr.addMarker(mrkr, 10);
									addInfo(mrkr, data[i].login, data[i].avatar, data[i].disciplines);
									setNeighbourListener(mrkr, data[i].login, data[i].lat, data[i].lng, data[i].avatar, data[i].disciplines);
								}
								mgr.refresh();
								
								$('#neighbours-search-form form').submit(function() {
									var $form = $(this);
									var query = 'radius=' + $form.find('input[name="radius"]').val();
									$form.find('.cell:not(.with-radius)').each(function() {
										var $cell = $(this);
										if ($cell.hasClass('discplines')) {
											query += '&discipline=' + $cell.find('input[name="discipline-caption"]').val();
										}
										else if ($cell.hasClass('sex')) {
											query += '&sex=' + $cell.find(':radio[checked]').val();
										}
										else if ($cell.hasClass('age')) {
											query += '&minage=' + $cell.find('select[name="minage"]').val() + '&maxage=' + $cell.find('select[name="maxage"]').val();
										}
									});
									startLoader();
									$.ajax({
										type: 'GET',
										dataType: 'json',
										url: '/action',
										data: 'get=neighbours&lat='+neighbours_lat+'&lng='+neighbours_lng+'&'+query + '&ax',
										success: function(data) {
											if (data) {
												resetManager();
												map.addOverlay(hostMarker);
												buildList(data);
												for (i = 0; i < data.length; i++) {
													var mrkr = new GMarker(new GLatLng(data[i].lat, data[i].lng), blueIcon);
													markers.push(mrkr);
													mgr.addMarker(mrkr, 10);
													addInfo(mrkr, data[i].login, data[i].avatar, data[i].disciplines);
													setNeighbourListener(mrkr, data[i].login, data[i].lat, data[i].lng, data[i].avatar, data[i].disciplines);
												}
												mgr.refresh();
											}
										}
									});
									return false;
								});
							}
						}
					});
				}
				function setNeighbourListener(marker, login, lat, lng, avatar_url, disciplines) {
					$('#n_'+login).find('.show-on-map').click(function() {
						map.panTo(new GLatLng(lat, lng));
						marker.openInfoWindowHtml(getBubbleHtml(login, avatar_url, disciplines));
					});
				}
				function addInfo(marker, login, avatar_url, disciplines) {
					marker.bindInfoWindowHtml(getBubbleHtml(login, avatar_url, disciplines));
				}
				function getBubbleHtml(login, avatar_url, disciplines) {
					var html = '<div class="map-bubble">' +
									'<div class="bubble-pic"><a href="/' + login + '"><img src="' + avatar_url + '" alt="' + login + '" /></a></div>' +
									'<div class="bubble-content">' +
										'<p class="title"><a href="/' + login + '">' + login + '</a></p>' +
										'<div class="disciplines">';
					// for (i = 0; i < disciplines.length; i++) {
						// html += 			'<img src="' + disciplines[i].src + '" alt="' + disciplines[i].name + '" title="' + disciplines[i].name + '" /> ';
					// }
					html +=				'</div>' +
									'</div>' +
								'</div>';
					return html;
				}
				function buildList(els) {
					function setPage(x) {
						$('.users-list').hide();
						$('#page_' + x).show();
					}
					
					var  per_page = 20;
					var page = 1;
					var html = '<ul id="page_' + page + '" class="users-list">';
					for (i = 0; i < els.length; i++) {
						html += '<li id="n_' + els[i].login + '"><div class="avatar"><a href="/' + els[i].login + '"><img src="' + els[i].avatar + '" alt="' + els[i].login + '"/></a></div><div class="name"><a href="/' + els[i].login + '">' + els[i].login + '</a></div><a title="Pokaż na mapie" class="show-on-map" href="#profile-neighbours">Pokaż na mapie</a></li>';
						if ((i+1)%20 == 0 && i+1 < els.length) {
							page++;
							html += '</ul><ul id="page_' + page + '" class="users-list">';
						}
					}
					html += '</ul>';
					if (page > 1) {
						html += '<div class="pager"><ul id="pages_pager">';
						for (i = 1; i <= page; i++) {
							if (i == 1) {
								html += '<li class="selected"><a href="#neighbours-list">' + i + '</a></li>';
							}
							else {
								html += '<li><a href="#neighbours-list">' + i + '</a></li>';
							}
						}
						html += '</ul></div>';
					}
					$('#neighbours-list .section-inner').html(html);
					$('.pager li').each(function(k) {
						var $li = $(this);
						$li.find('a').click(function() {
							$('.pager .selected').removeClass('selected');
							$li.addClass('selected');
							setPage(k+1);
						});
					});
					setPage(1);
				}
				if (neighbours_lat && neighbours_lng) {
					var point = new GLatLng(neighbours_lat, neighbours_lng);
					map.setCenter(point, 15);
					hostMarker = new GMarker(point, redIcon);
					map.addOverlay(hostMarker);
					execute(map);
				}
				else {
					google.maps.Unload();
					$('#neighbours-list').remove();
					$('#neighbours-search-form').remove();
					if (is_owner) {
						$(map_container).html('<a class="location-not-set" href="/settings/data#map-location">Ustaw swoją lokalizację!</a>');
					}
					else {
						$(map_container).html('<div class="neigh-location-not-set">Użytkownik nie ma ustawionej lub nie udostępnia swojej lokalizacji!</div>');
					}
					/*
					var address = neighbours_street;
					if (neighbours_house) {
						address += ' ' + neighbours_house;
					}
					if (neighbours_code) {
						address += ', ' + neighbours_code;
					}
					if (neighbours_city) {
						address += ', ' + neighbours_city;
					}
					address += ', Polska';  			 	// Hard coded Poland for the time being :)
					geocoder.getLatLng(address, function(point) {
						if (!point) {
							alert('Nie znaleziono lokalizacji.');
						}
						else {
							map.setCenter(point, 15);
							hostMarker = new GMarker(point, redIcon);
							map.addOverlay(hostMarker);
							neighbours_lat = point.y;
							neighbours_lng = point.x;
							execute(map);
						}
					});
					*/
				}
			}
		}
		
		function loadMaps() {
			google.load("maps", "2", {"callback" : mapsLoaded});
		}
		function startLoader() {
			$('#neighbours-list .section-inner').html('<div id="n_loader"><img src="http://static.my-sport.pl/static/loaders/section-loader.gif" alt="" /> Wczytuję sąsiadów...</div>');
		}
		function stopLoader() {
			$('#n_loader').remove();
		}

		loadMaps();
	},
	
	showMainPageMap: function() {
		var map_container = document.getElementById('main-page-map');
		function mapsLoaded() {
			if (google.maps.BrowserIsCompatible()) {
				Mysport.stopMapLoader();
				var map = new google.maps.Map2(map_container);
				var geocoder = new google.maps.ClientGeocoder();
				map.setMapType(G_NORMAL_MAP);
				map.addControl(new google.maps.SmallMapControl());
				var redIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/user_red.png');
				var orangeIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/mysport_orange.png');
				var yellowIcon = new GIcon(G_DEFAULT_ICON, 'http://static.my-sport.pl/static/markers/mysport_yellow.png');
				
				function execute(map) {
					var mgr = null;
					var markers = [];
					function initGMarkerManager() {
						mgr = new GMarkerManager(map);
					}
					function resetManager() {
						 if (markers != null  &&  markers.length > 0 ){
							map.clearOverlays();
							for (i = 0; i < markers.length; i++) {
								markers[i].hide();
							}
							markers = [];
							initGMarkerManager();
						 } 
					}
					initGMarkerManager();
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: '/action',
						data: 'get=mysports&lat='+user_lat+'&lng='+user_lng+'&radius='+50 + '&ax',
						success: function(data) {
							if (data) {
								for (i = 0; i < data.length; i++) {
									var mrkr = new GMarker(new GLatLng(data[i].lat, data[i].lng), yellowIcon);
									markers.push(mrkr);
									mgr.addMarker(mrkr, 10);
									addInfo(mrkr, data[i].id, data[i].title);
								}
								mgr.refresh();
							}
						}
					});
				}
				function addInfo(marker, id, title) {
					var html = '<div class="map-bubble">' +
									'<p class="title"><a href="/mysport/' + id + '">' + title + '</a></p>' +
								'</div>';
					marker.bindInfoWindowHtml(html);
				}
				if (user_lat != '' && user_lng != '') {
					var point = new GLatLng(user_lat, user_lng);
					map.setCenter(point, 12);
					hostMarker = new GMarker(point, redIcon);
					map.addOverlay(hostMarker);
					execute(map);
				}
				else {
					google.maps.Unload();
					$(map_container).addClass('nomap-available').html('<a id="set-location" href="/settings/data/#map-location">Ustaw swoją lokalizację</a>');
					
				}
			}
		}
		function loadMaps() {
			google.load("maps", "2", {"callback" : mapsLoaded});
		}

		loadMaps();
	},
	
	initMap: function() {
		function initLoader(fn) {
			if (location.href.split('/')[2] == 'www.my-sport.pl') {
				var key = 'ABQIAAAAmpUSQ0sk3U1W4MfaQUxY1xReDVc_NJ8AIYD0bw_MRWHqRSxW4xR-PuzSD32AhyaQSxFXe-K_thtZuA';
			}
			else {
				var key = 'ABQIAAAAmpUSQ0sk3U1W4MfaQUxY1xR6rPZByAjpwMPKYDp_JLCE-uPrSBRBT1q84I65bcdreH7wtP_Xq09t3w';
			}
			Mysport.startMapLoader();
			var script = document.createElement("script");
			script.src = 'http://www.google.com/jsapi?key=' + key + '&callback=Mysport.' + fn;
			script.type = "text/javascript";
			document.getElementsByTagName("head")[0].appendChild(script);
		}
		$('#map').each(function() {
			initLoader('showMap');
		});
		$('#map-location').each(function() {
			initLoader('geolocShowMap');
		});
		$('#map-location2').each(function() {
			initLoader('geolocShowMap2');
		});
		$('#profile-neighbours').each(function() {
			initLoader('neightShowMap');
		});
		$('#main-page-map').each(function() {
			initLoader('showMainPageMap');
		});
		$('#mysport-map').each(function() {
			initLoader('showMysportMap');
		});
	},
	
	startMapLoader: function() {
		$('.gmap').append('<div id="gmap-loader"><img src="http://static.my-sport.pl/static/loaders/form-loader.gif" alt="" /> Wczytuję mape...</div>');
	},
	
	stopMapLoader: function() {
		$('#gmap-loader').remove();
	},
	
	addingToObserved: function() {
		function add($a) {
			$a.click(function(e) {
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: $a.attr('href'),
					data: 'ax',
					success: function(data) {
						 if (data) {
							if (data[0]) {
								Mysport.displayPageMsg(e, 'Poprawnie dodano do obserwowanych');
								$a.remove();
							}
							else {
								alert('Wystąpił błąd.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
							}
						}
						else {
							alert('Wystąpił błąd.\nJeśli problem będzie się powtarzał skontaktuj się z administratorem.');
						}
					}
				});
				return false;
			});
		}
		add($('.add-to-fav'));
		add($('.observe-eye'));
	},
	
	countChars: function() {
		$('.count-chars').each(function() {
			function eval() {
				var new_q = $field.val().length;
				q_left = max - new_q;
				if (new_q >= max) {
					$field.val($field.val().slice(0,max));
					q_left = 0;
					$info.removeClass('ok').addClass('err');
				}
				else if ($info.hasClass('err')) {
					$info.removeClass('err').addClass('ok');
				}
				$q.text(q_left);
			}
			var $field = $(this);
			var max = $field.attr('rel');
			var q_left = max - $field.val().length;
			$field.after(' <span class="extra-info ok">Pozostało <span class="chars">' + q_left + '</span> znaków.</span>');
			var $info = $field.next();
			var $q = $info.find('.chars');
			$field.keyup(function() {
				eval();
			});
			eval();
		});
	},
	
	socialButtons: function() {
		$('.social-buttons').each(function() {
			var $this = $(this);
			var site_url = window.location.href;
			var page_title = document.title;
			var fb_url = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(site_url) + '&t=' + encodeURIComponent(page_title) + '&src=sp';
			var wykop_url = 'http://www.wykop.pl/dodaj?url=' + site_url + '&desc=' + page_title;
			
			var img_width = 650;
			var img_height = 400;
			var left = screen.width/2 - img_width/2;
			var top = screen.height/2 - img_height/2;
			var config = 'left=' + left + ',top=' + top + ', height=' + img_height + ', width=' + img_width + ',innerheight=' + img_height + ',innerwidth=' + img_width + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no';
			
			function openWin(url) {
				window.open(url, 'socialWindow', config);
			}
			
			$this.append('<a target="_blank" class="fb-button" href="' + fb_url + '" title="Dodaj do Facebooka!">Dodaj do Facebooka!</a>');
			$this.append('<a target="_blank" class="wykop-button" href="' + wykop_url + '" title="Wykop to!">Wykop to!</a>');
			
			$this.find('.fb-button').click(function() {
				openWin(fb_url);
				return false;
			});
		});
	},
	
	startNotifications: function() {
		$('#bubble').each(function() {
			var $this = $(this);
			$this.find('.close-bubble').click(function() {
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: '/action?action=deletenotifications',
					data: 'ax',
					success: function(data) {
					}
				});
				$this.remove();
				return false;
			});
		});
		$('#bubble2').each(function() {
			var $this = $(this);
			$this.find('.close-bubble').click(function() {
				$this.remove();
				return false;
			});
		});
	},
	
	loadPilot: function() {
		$('#pilot-panels .scr').addClass('screen');
		$('#main-page-guide').show();
	},
	
	initFlashes: function(n) {
		var flashvars = {
			clickTag: 'http://www.my-sport.pl/mysport-add'
		};
		var params = {
			wmode: 'transparent'
		};
		var attributes = {};
		
		if (document.getElementById('joinmysport')) {
			$('#joinmysport').wrap('<div id="joinmysport-wrapper"></div>');
			
			var number = Math.ceil(Math.random() * n);
			
			swfobject.embedSWF("http://www.my-sport.pl/banners/umowsie" + number + ".swf?v=3", "joinmysport", "303", "40", "8.0.0", "/display/swf/expressInstall.swf", flashvars, params, attributes);
		}
	},
	
	initBanners: function() {
		var flashvars = {};
		var params = {
			wmode: 'transparent'
		};
		var attributes = {};

		//$('#main-right-banner').html('<div id="reklama-na-start200x200"></div>');
		if (document.getElementById('reklama-na-start200x200')) {
			swfobject.embedSWF("/banners/reklama_na_start_200x200.swf", "reklama-na-start200x200", "200", "200", "8.0.0", "/display/swf/expressInstall.swf", flashvars, params, attributes);
		}
		
		var flashvars2 = {
			clickTAG: 'http://www.my-sport.pl/programs/myprofit/about',
			targetWindow: '_self'
		};
		
		if (document.getElementById('my-profit-banner')) {
			swfobject.embedSWF("/banners/my_profit.swf", "my-profit-banner", "200", "200", "8.0.0", "/display/swf/expressInstall.swf", flashvars2, params, attributes);
		}
	},
	
	addValidation: function() {
		$('form.validate').each(function() {
			var $form = $(this);
			$form.find('.cell').each(function() {
				var $cell = $(this);
				$cell.find('input:not(:submit):not(type[file])').each(function() {
					var $input = $(this);
					$input.focus(function() {
						$cell.find('.error').remove();
					});
					$input.blur(function() {
						var ok = true;
						if ($input.hasClass('login')) {
							ok = isLongEnough($(this).val(), 4);
							errorMsg = 'Za krótka nazwa użytkownika';
							if (ok) {
								ok = isLogin($(this).val());
								errorMsg = 'Nazwa użytkownika zawiera nieprawidłowe znaki';
							}
						}
						if ($input.hasClass('sex')) {
							ok = isGroupChecked($input.attr('name'));
							errorMsg = 'Wybierz płeć';
						}
						if ($input.hasClass('group')) {
							ok = isGroupChecked($input.attr('name'));
							errorMsg = 'Musisz dokonać wyboru';
						}
						if ($input.hasClass('reg')) {
							ok = isChecked($input);
							errorMsg = 'Aby korzystać z serwisu musisz wyrazić zgodę';
						}
						if ($input.hasClass('email') || $input.hasClass('email2')) {
							ok = isMail($(this).val());
							errorMsg = 'Nieprawidłowy adres e-mail';
							if (ok) {
								if ($input.hasClass('email') && ($form.find('input.email2').val() != null && $form.find('input.email2').val() != '')) {
									ok = isPassEqual($form.find('input.email2').val(), $input.val());
									errorMsg = 'Podane adresy e-mail nie są jednakowe';
								}
								if ($input.hasClass('email2')) {
									ok = isPassEqual($form.find('input.email').val(), $input.val());
									errorMsg = 'Podane adresy e-mail nie są jednakowe';
								}
							}
						}
						if ($input.hasClass('tel')) {
							ok = isPhoneNo($input.val());
							errorMsg = 'Nieprawidłowy numer telefonu';
						}
						if ($input.hasClass('pass') || $input.hasClass('pass2')) {
							ok = isLongEnough($(this).attr('value'), 6);
							errorMsg = 'Hasło powinno mieć conajmniej 6 znaków';
							if (ok) {
								if ($input.hasClass('pass') && ($form.find('input.pass2').val() != null && $form.find('input.pass2').val() != '')) {
									ok = isPassEqual($form.find('input.pass2').val(), $input.val());
									errorMsg = 'Podane hasła nie są jednakowe';
								}
								if ($input.hasClass('pass2')) {
									ok = isPassEqual($form.find('input.pass').val(), $input.val());
									errorMsg = 'Podane hasła nie są jednakowe';
								}
							}
						}
						if ($input.hasClass('number')) {
							ok = isNumber($input.val());
							errorMsg = 'Nieprawidłowy numer';
						}
						if ($input.hasClass('alphanumeric')) {
							ok = isAlphanumeric($input.val());
							errorMsg = 'Pole może posiadać tylko litery i liczby';
						}
						if ($input.hasClass('house-number')) {
							ok = isHouseNumber($input.val());
							errorMsg = 'Nieprawidłowy numer domu';
						}
						if (!isNotBlank($input.val())) {
							ok = false;
							errorMsg = 'To pole jest wymagane';
						}
						
						if (!$input.hasClass('nr') || isNotBlank($input.val())) {
							if (ok) {
								$cell.find('.error').remove();
							}
							else {
								if (!$cell.find('.error').length) {
									Mysport.displayError($cell, errorMsg);
								}
							}
						}
					});
				});
				$cell.find('select:not(.nr)').each(function() {
					var $select = $(this);
					$select.focus(function() {
						$cell.find('.error').remove();
					});
					$select.blur(function() {
						if ($(this).val() == -1) {
							if (!$cell.find('.error').length) {
								Mysport.displayError($cell, 'Musisz dokonać wyboru');
							}
						}
					});
				});
				$cell.find('textarea').each(function() {
					var $textarea = $(this);
					$textarea.focus(function() {
						$cell.find('.error').remove();
					});
					$textarea.blur(function() {
						if (!$textarea.hasClass('nr') && !isNotBlank($textarea.val())) {
							if (!$cell.find('.error').length) {
								Mysport.displayError($cell, 'To pole jest wymagane');
							}
						}
					});
				});
			});

			$form.submit(function() {
				if ($form.find('.error').length <= 0) {
					$form.find('input:not(:submit):not(type[file]):not(.nr)').blur();
					$form.find('select').blur();
					$form.find('textarea').blur();
					if ($form.find('.error').length > 0) {
						gotoErr();
						return false;
					}
					else return true;
				}
				else {
					gotoErr();
					return false;
				}
			});
			
			function gotoErr() {
				if (!$form.hasClass('small-form')) {
					if (!document.getElementById('register-page')) {
						$('#first-error').removeAttr('id');
						$form.find('.error:first').parents('.cell:first').attr('id', 'first-error');
						var url = location.href.split('#');
						if (url.length > 1) {
							location.href = url[0] + '#first-error';
						}
						else {
							location.href = location.href + '#first-error';
						}
					}
				}
			}
		});
		
		$('#blog-subscribe').submit(function() {
			var $form = $(this);
			if (!isMail($form.find('.fields input').val())) {
				Mysport.displayError($form.find('fieldset'), 'Nieprawidłowy adres e-mail');
				return false;
			}
			else {
				return true;
			}
		});
		
		function isChosen(val) {
			if (val != -1) return true;
			else return false;
		}
		function isNotBlank(val) {
			if (val != null && val != '') return true;
			else return false;
		}
		function isLongEnough(val, n) {
			if ((val != null && val != '') && val.length >= n) return true;
			else return false;
		}
		function getErrorMsg(msg) {
			var message = 	'<div class="error">' + msg + '</div>';
			return message;
		}
		function isMail(val) {
			var filter  = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			if (filter.test(val)) return true;
			else return false;
		}
		function isPhoneNo(val) {
			var filter  = /^([0-9\-\+/ /])+$/;
			if (filter.test(val)) return true;
			else return false;
		}
		function isPassEqual(pass, pass2) {
			if (pass == pass2 && pass != null) return true;
			else return false;
		}
		function isNumber(val) {
			var filter  = /^([0-9])+$/;
			if (filter.test(val)) return true;
			else return false;
		}
		function isPostCode(val) {
			var filter  = /^[0-9][0-9]-[0-9][0-9][0-9]$/;
			if (filter.test(val)) return true;
			else return false;
		}
		function isLogin(val) {
			if (isLongEnough(val, 4)) {
				var filter  = /^([a-zA-Z0-9])+$/;
				if (filter.test(val)) return true;
				else return false;
			}
			else return false;
		}
		function isAlphanumeric(val) {
			var filter  = /^([a-zA-Z0-9])+$/;
			if (filter.test(val)) return true;
			else return false;
		}
		function isHouseNumber(val) {
			var filter  = /^([a-zA-Z0-9\/ ])+$/;
			if (filter.test(val)) return true;
			else return false;
		}
		function isPriceAmount(val) {
			var filter  = /^(([0-9])+)?([0-9][.,][0-9])?(([0-9])+)?$/;
			if (filter.test(val)) return true;
			else return false;
		}
		function isChecked($el) {
			if ($el[0].checked) {
				return true;
			}
			else return false;
		}
		function isGroupChecked(name) {
			var i = 0;
			$(':radio:checked').each(function() {
				if ($(this).attr('name') == name) {
					i++;
				}
			})
				
			if (i > 0) {
				return true;
			}
			else return false;
		}
	},
	
	displayError: function($cell, message) {
		if ($cell.find('.error').length == 0) {
			$cell.append('<div class="error">' + message + '</div>');
			$cell.find('.error').fadeIn(1000);
		}
	},
	
	displayLightError: function($cell, message) {
		if ($cell.find('.light-error').length == 0) {
			$cell.append('<div class="light-error">' + message + '</div>');
			$cell.find('.light-error').fadeIn(1000);
		}
	},
	
	displayPageMsg: function(e, msg) {
		$('body').append('<div class="page-msg"><div class="inner">' + msg + '</div></div>');
		var $msg = $('body > .page-msg:last');
		$msg.css({
				'top':  e.pageY+'px',
				'left': (e.pageX+20)+'px'
			});
		if (!$.browser.msie) {
			$msg.fadeIn(500, function() {
				setTimeout(function() {
					$msg.fadeOut(500, function() {
						$msg.remove();
					});
				}, 2000);
			});
		}
		else {
			$msg.show();
			setTimeout(function() {
				$msg.remove();
			}, 2500);
		}
	},
	
	preloadImages: function() {
		// $.imgpreload([ //preload loaders
			// 'http://static.my-sport.pl/static/loaders/form-loader.gif',
			// 'http://static.my-sport.pl/static/loaders/box-loader.gif',
			// 'http://static.my-sport.pl/static/loaders/section-loader.gif'
		// ], '');
		if (document.getElementById('disciplines')) {
			$('#discipline-list').before('<div id="loader"><img src="http://static.my-sport.pl/static/loaders/box-loader.gif" alt="" /> Wczytuję dyscypliny</div>')
			$.imgpreload([
				'http://static.my-sport.pl/static/disciplines/l/aeroplane.png',
				'http://static.my-sport.pl/static/disciplines/l/aikido.png',
				'http://static.my-sport.pl/static/disciplines/l/american_football.png',
				'http://static.my-sport.pl/static/disciplines/l/archering.png',
				'http://static.my-sport.pl/static/disciplines/l/armwrestling.png',
				'http://static.my-sport.pl/static/disciplines/l/artistic_gymnastics.png',
				'http://static.my-sport.pl/static/disciplines/l/asg.png',
				'http://static.my-sport.pl/static/disciplines/l/badminton.png',
				'http://static.my-sport.pl/static/disciplines/l/base_jumping.png',
				'http://static.my-sport.pl/static/disciplines/l/baseball.png',
				'http://static.my-sport.pl/static/disciplines/l/basketball.png',
				'http://static.my-sport.pl/static/disciplines/l/beach.png',
				'http://static.my-sport.pl/static/disciplines/l/biathlon.png',
				'http://static.my-sport.pl/static/disciplines/l/billiards.png',
				'http://static.my-sport.pl/static/disciplines/l/body_builder.png',
				'http://static.my-sport.pl/static/disciplines/l/boules.png',
				'http://static.my-sport.pl/static/disciplines/l/bowling.png',
				'http://static.my-sport.pl/static/disciplines/l/boxing.png',
				'http://static.my-sport.pl/static/disciplines/l/breakdance.png',
				'http://static.my-sport.pl/static/disciplines/l/bridge.png',
				'http://static.my-sport.pl/static/disciplines/l/bungee.png',
				'http://static.my-sport.pl/static/disciplines/l/canoeing.png',
				'http://static.my-sport.pl/static/disciplines/l/capoeira.png',
				'http://static.my-sport.pl/static/disciplines/l/cars.png',
				'http://static.my-sport.pl/static/disciplines/l/chess.png',
				'http://static.my-sport.pl/static/disciplines/l/conferences.png',
				'http://static.my-sport.pl/static/disciplines/l/cricket.png',
				'http://static.my-sport.pl/static/disciplines/l/curling.png',
				'http://static.my-sport.pl/static/disciplines/l/cycling.png',
				'http://static.my-sport.pl/static/disciplines/l/dance.png',
				'http://static.my-sport.pl/static/disciplines/l/darts.png',
				'http://static.my-sport.pl/static/disciplines/l/diving.png',
				'http://static.my-sport.pl/static/disciplines/l/e-sport.png',
				'http://static.my-sport.pl/static/disciplines/l/extreme_climbing.png',
				'http://static.my-sport.pl/static/disciplines/l/field_hockey.png',
				'http://static.my-sport.pl/static/disciplines/l/fishing.png',
				'http://static.my-sport.pl/static/disciplines/l/fitness.png',
				'http://static.my-sport.pl/static/disciplines/l/footbag.png',
				'http://static.my-sport.pl/static/disciplines/l/football.png',
				'http://static.my-sport.pl/static/disciplines/l/freestyle_bmx.png',
				'http://static.my-sport.pl/static/disciplines/l/freestyle_flying.png',
				'http://static.my-sport.pl/static/disciplines/l/freestyle_football.png',
				'http://static.my-sport.pl/static/disciplines/l/freestyle_skiing.png',
				'http://static.my-sport.pl/static/disciplines/l/frisbee.png',
				'http://static.my-sport.pl/static/disciplines/l/golf.png',
				'http://static.my-sport.pl/static/disciplines/l/gymnastics_ribbon.png',
				'http://static.my-sport.pl/static/disciplines/l/gymnastics_sprinboard.png',
				'http://static.my-sport.pl/static/disciplines/l/hang_gliding.png',
				'http://static.my-sport.pl/static/disciplines/l/high_jump.png',
				'http://static.my-sport.pl/static/disciplines/l/horse_riding.png',
				'http://static.my-sport.pl/static/disciplines/l/hummer_throwing.png',
				'http://static.my-sport.pl/static/disciplines/l/hunting.png',
				'http://static.my-sport.pl/static/disciplines/l/hurdles.png',
				'http://static.my-sport.pl/static/disciplines/l/ice_hockey.png',
				'http://static.my-sport.pl/static/disciplines/l/javelin_throw.png',
				'http://static.my-sport.pl/static/disciplines/l/judo.png',
				'http://static.my-sport.pl/static/disciplines/l/karate.png',
				'http://static.my-sport.pl/static/disciplines/l/kendo.png',
				'http://static.my-sport.pl/static/disciplines/l/kick_volleyball.png',
				'http://static.my-sport.pl/static/disciplines/l/kickboxing.png',
				'http://static.my-sport.pl/static/disciplines/l/kitesurfing.png',
				'http://static.my-sport.pl/static/disciplines/l/krav-maga.png',
				'http://static.my-sport.pl/static/disciplines/l/lacrosse.png',
				'http://static.my-sport.pl/static/disciplines/l/life-saving.png',
				'http://static.my-sport.pl/static/disciplines/l/lugeing.png',
				'http://static.my-sport.pl/static/disciplines/l/lugeing_group.png',
				'http://static.my-sport.pl/static/disciplines/l/mma.png',
				'http://static.my-sport.pl/static/disciplines/l/mountain_boarding.png',
				'http://static.my-sport.pl/static/disciplines/l/mountain tourism.png',
				'http://static.my-sport.pl/static/disciplines/l/mountaineering.png',
				'http://static.my-sport.pl/static/disciplines/l/mua-thai.png',
				'http://static.my-sport.pl/static/disciplines/l/nordic_walking.png',
				'http://static.my-sport.pl/static/disciplines/l/paintball.png',
				'http://static.my-sport.pl/static/disciplines/l/parachuting.png',
				'http://static.my-sport.pl/static/disciplines/l/paragliding.png',
				'http://static.my-sport.pl/static/disciplines/l/parkoure.png',
				'http://static.my-sport.pl/static/disciplines/l/poker.png',
				'http://static.my-sport.pl/static/disciplines/l/relay_race.png',
				'http://static.my-sport.pl/static/disciplines/l/rollerskating.png',
				'http://static.my-sport.pl/static/disciplines/l/rounders.png',
				'http://static.my-sport.pl/static/disciplines/l/rowing.png',
				'http://static.my-sport.pl/static/disciplines/l/rugby.png',
				'http://static.my-sport.pl/static/disciplines/l/running.png',
				'http://static.my-sport.pl/static/disciplines/l/sailing.png',
				'http://static.my-sport.pl/static/disciplines/l/shooting_sport.png',
				'http://static.my-sport.pl/static/disciplines/l/shopping.png',
				'http://static.my-sport.pl/static/disciplines/l/shot_put.png',
				'http://static.my-sport.pl/static/disciplines/l/skateboarding.png',
				'http://static.my-sport.pl/static/disciplines/l/skating.png',
				'http://static.my-sport.pl/static/disciplines/l/ski_jumping.png',
				'http://static.my-sport.pl/static/disciplines/l/skiing.png',
				'http://static.my-sport.pl/static/disciplines/l/skimboarding.png',
				'http://static.my-sport.pl/static/disciplines/l/slackline.png',
				'http://static.my-sport.pl/static/disciplines/l/snoorkeling.png',
				'http://static.my-sport.pl/static/disciplines/l/snowboard.png',
				'http://static.my-sport.pl/static/disciplines/l/snowboard_freestyle.png',
				'http://static.my-sport.pl/static/disciplines/l/sport_gymnastics.png',
				'http://static.my-sport.pl/static/disciplines/l/sport_gymnastics_hours.png',
				'http://static.my-sport.pl/static/disciplines/l/sport_gymnastics_shaft.png',
				'http://static.my-sport.pl/static/disciplines/l/sport_gymnastics_still_rings.png',
				'http://static.my-sport.pl/static/disciplines/l/sprint.png',
				'http://static.my-sport.pl/static/disciplines/l/squash.png',
				'http://static.my-sport.pl/static/disciplines/l/surfing.png',
				'http://static.my-sport.pl/static/disciplines/l/survival.png',
				'http://static.my-sport.pl/static/disciplines/l/swimming.png',
				'http://static.my-sport.pl/static/disciplines/l/swordsmanship.png',
				'http://static.my-sport.pl/static/disciplines/l/table_soccer.png',
				'http://static.my-sport.pl/static/disciplines/l/table_tennis.png',
				'http://static.my-sport.pl/static/disciplines/l/taekwondo.png',
				'http://static.my-sport.pl/static/disciplines/l/taijiquan.png',
				'http://static.my-sport.pl/static/disciplines/l/tennis.png',
				'http://static.my-sport.pl/static/disciplines/l/tower_running.png',
				'http://static.my-sport.pl/static/disciplines/l/tug_of_war.png',
				'http://static.my-sport.pl/static/disciplines/l/voleyball.png',
				'http://static.my-sport.pl/static/disciplines/l/wakeboarding.png',
				'http://static.my-sport.pl/static/disciplines/l/water_polo.png',
				'http://static.my-sport.pl/static/disciplines/l/water_skiing.png',
				'http://static.my-sport.pl/static/disciplines/l/weightlifting.png',
				'http://static.my-sport.pl/static/disciplines/l/windsurfing.png',
				'http://static.my-sport.pl/static/disciplines/l/wrestling.png',
				'http://static.my-sport.pl/static/disciplines/l/yoga.png'
			],function() {
				$('#loader').remove();
				$('#discipline-list').show();
			});
		}
	}
	
}

function imgpreload(imgs,settings)
{
	// settings = { each:Function, all:Function }
	if (settings instanceof Function) { settings = {all:settings}; }

	// use of typeof required
	// https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Instanceof_Operator#Description
	if (typeof imgs == "string") { imgs = [imgs]; }

	var loaded = [];
	var t = imgs.length;
	var i = 0;
	if ($.browser.msie) {
		setTimeout(function() {
			for (i; i<t; i++)
			{
				var img = new Image();
				img.onload = function()
				{
					loaded.push(this);
					if (settings.each instanceof Function) { settings.each.call(this); }
					if (loaded.length>=t && settings.all instanceof Function) { settings.all.call(loaded); }
				};
				img.src = imgs[i];
			}
		}, 1000);
	}
	else {
		for (i; i<t; i++)
		{
			var img = new Image();
			img.onload = function()
			{
				loaded.push(this);
				if (settings.each instanceof Function) { settings.each.call(this); }
				if (loaded.length>=t && settings.all instanceof Function) { settings.all.call(loaded); }
			};
			img.src = imgs[i];
		}
	}
}

if (typeof jQuery != "undefined")
{
	(function($){
		$.imgpreload = imgpreload;

		// public
		$.fn.imgpreload = function(settings)
		{
			settings = $.extend({},$.fn.imgpreload.defaults,(settings instanceof Function)?{all:settings}:settings);

			this.each(function()
			{
				var elem = this;

				imgpreload($(this).attr('src'),function()
				{
					if (settings.each instanceof Function) { settings.each.call(elem); }
				});
			});

			// declare urls and loop here (loop a second time) to prevent
			// pollution of above closure with unnecessary variables

			var urls = [];

			this.each(function()
			{
				urls.push($(this).attr('src'));
			});
			var selection = this;

			imgpreload(urls,function()
			{
				if (settings.all instanceof Function) { settings.all.call(selection); }
			});

			return this;
		};

		// public
		$.fn.imgpreload.defaults =
		{
			each: null, // callback invoked when each image in a group loads
			all: null // callback invoked when when the entire group of images has loaded
		};

	})(jQuery);
}

var Modal = {
	open: function(title, msg) {
		Modal.screenHeight = $('#wrapper').height();
		var html = '<div id="modal-bg" style="height:' + Modal.screenHeight + 'px"></div>';
		html += '<div id="modal" class="pre"><div class="columns"><div class="header">' + title + '</div><a class="close" href="#">zamknij</a></div><div class="inner">' + msg + '</div></div>';
		// '<p class="imp">Szczegóły:</p>' +
		// '<div class="columns">' +
			// '<img class="ico" src="http://www.kkuliczkowski.dev.sportmediagroup.pl/view/static/icons/xl/superman.png" alt="Superman"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>' +
		// '</div>' +
		// '<p><span class="imp">Kategoria:</span> Ikonka</p>' +
		// '<p><span class="imp">Cena:</span> 150</p>' +
		
		$('body').append(html);
		Modal.box = $('#modal');
		Modal.height = Modal.box.height();
		Modal.box.height(Modal.height);
		Modal.box.css('margin-top', -Modal.height/2 + 'px');
		Modal.box.removeClass('pre');
		Modal.box.find('.close').click(function() {
			Modal.close();
			return false;
		});
	},
	
	close: function() {
		Modal.box.remove();
		$('#modal-bg').remove();
	}
}

// var Modal = {

	// open: function() {
		// var height = $('#wrapper').height();
		// var $body = $('body');
		// $body.append('<div class="modal-overlay"></div>');
		// $body.find('.modal-overlay').height(height);
		
		
	// }
	
// }

var Cookie = {
   
    create: function(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    },

    read: function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    },
	
    erase: function(name) {
        createCookie(name,"",-1);
    }
} 

$(function() {
	Mysport.start();
});