var Sportpolis = {

	start: function() {
		this.tweakLayout();
		this.tweakButtons();
		this.addToObserved();
		this.addFunctionalities();
		this.startNotifications();
		this.startValidation();
		this.registrationChecks();
		this.initMyTooltip();
		this.addForumFunctionality();
		this.initDatepicker();
		this.initMap();
		this.addRating();
		this.addConfirmations();
		//this.initBanners();
	},
	
	
	tweakLayout: function() {
		// Sign inputs for IE and other IE BS
		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');
				}
			});
			
			$('ul#nav').each(function() {
				var $nav = $(this);
				var nav_html = $nav.html();
				$nav.remove();
				$('#site').prepend('<ul id="nav">' + nav_html + '</ul>');
			});
		}
		
		// 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');
				});
			}
			
			giveHover($('#community .inner'));
			giveHover($('.group-list > li'));
		}
		
		//set frozen-overlay size
		$('#frozen-overlay').each(function() {
			var $this = $(this);
			$this.width($('body:first').width());
			$this.height($('body:first').height());
		});
		
		//reorganize masthead for IE6
		if ($.browser.msie && /MSIE 6.0/.test(navigator.userAgent)) {
			$('#masthead').each(function() {
				$(this).prepend('<div id="masthead-bg"></div>');
			});
		}
	},
	
	tweakButtons: function() {
		$('input.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 if ($submit.hasClass('login-button')) {
				$submit.after('<a href="#" class="login-button">Zaloguj</a>');
			}
			else {
				$submit.after('<a href="#" class="' + classes + '"><span class="btn-l"></span><span class="btn-c">' + val + '</span><span class="btn-r"></span></a>');
			}
			$submit.next().click(function() {
				//$submit.click();
				$submit.parents().filter('form:first').submit();
				return false;
			});
			$submit.hide();
		});
	},
	
	addToObserved: function() {
		$('a.add-to-observed').click(function(e) {
			var $this = $(this);
			$.ajax({
				type: 'GET',
				dataType: 'json',
				url: $this.attr('href'),
				data: 'ax',
				success: function(data) {
					if (data[0]) {
						var txt = 'Poprawnie dodano do obserwowanych';
						$this.remove();
					}
					else {
						var txt = 'Wystąpił błąd, spróbuj jeszcze raz';
					}
					Sportpolis.displayPageMsg(e, txt);
				}
			});
			return false;
		});
	},
	
	addFunctionalities: function() {
		// show/hide main-topics
		$('#disciplines > li.more').each(function() {
			var $this = $(this);
			var $topics = $this.find('.main-topics');
			if ($this.hasClass('shown')) {
				$this.find('h4 a:first').toggle(function() {
					$topics.slideUp();
					$this.removeClass('open');
					$(this).find('.action').text('rozwiń');
				}, function() {
					$topics.slideDown();
					$this.addClass('open');
					$(this).find('.action').text('zwiń');
				});
			}
			else {
				$this.find('h4 a:first').toggle(function() {
					$topics.slideDown();
					$this.addClass('open');
					$(this).find('.action').text('zwiń');
				}, function() {
					$topics.slideUp();
					$this.removeClass('open');
					$(this).find('.action').text('rozwiń');
				});
			}
		});
		
		//show/hide new-topic form
		$('#add-topic-btn').toggle(function() {
			$('#new-topic').slideDown();
			return false;
		}, function() {
			$('#new-topic').slideUp();
			return false;
		})
		
		//new comment hidden/showed
		$('.comments.hidden').each(function() {
			$this = $(this);
			var form = $this.find('form:first');
			form.hide();
			$this.prepend('<div class="add-comment-link btn"><a href="#" class="button"><span class="btn-l"></span><span class="btn-c">Dodaj komentarz</span><span class="btn-r"></span></a></div>')
			form.prev().find('a:first').click(function() {
				form.prev().remove();
				form.slideDown();
				return false;
			});
		});
		
		//login captions
		$('#login').each(function() {
			function clearPre() {
				$this.find('input[name="login"]').val('').unbind('focus');
				$fake_pass.remove();
				$pass.show();
				$this.removeClass('pre');
			}
			var $this = $(this);
			$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();
			});
		});
		
		//new-topic captions
		$('#new-topic').each(function() {
			function clearPre() {
				$this.find('input[type="text"]').val('').unbind('focus');
				$this.find('textarea').val('').unbind('focus');
				$this.removeClass('pre');
			}
			var $this = $(this);
			$this.addClass('pre');
			$this.find('input[type="text"]').val('temat').focus(function() {
				clearPre();
			});
			$this.find('textarea').val('treść').focus(function() {
				clearPre();
			});
		});
		
		//form submit by eneter 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();
							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;
				});
			}
		});
		
		//adding blank
		$('a.blank').attr('target', '_blank');
		
		//privacy table
		$('#privacy-table').each(function() {
			var $table = $(this);
			$table.find('tr.main').each(function() {
				var $main = $(this);
				var $details = $main.next();
				$main.find('> td').each(function(i) {
					$(this).find(':radio').click(function() {
						$details.find('table tbody tr').each(function() {
							$(this).find('td:eq('+i+') :radio')[0].checked = 1;
						})
					});
				});
				$details.find(':radio').click(function() {
					$main.find(':radio').each(function() {
						this.checked = 0;
					});
				});
				$main.find('a.details').click(function() {
					if (!$main.hasClass('shown')) {
						if ($.browser.msie) {
							$details.css('display', 'block');
						}
						else {
							$details.css('display', 'table-row');
						}
						$main.find('a.details').text('zwiń');
						$main.addClass('shown');
					}
					else {
						$details.hide();
						$main.find('a.details').text('rozwiń');
					$main.removeClass('shown');
					}
					return false;
				});
			});
		});
		
		//show/hide personal_number
		$('#personal_number_choice').each(function() {
			$this = $(this);
			if (this.checked) {
				$('#personal-number').show();
			}
			$this.click(function() {
			if (this.checked) {
					$('#personal-number').show();
				}
				else {
					$('#personal-number').hide();
				}
			});
		});
		
		//right column anchor links functionality
		$('a.anchor').click(function(){
			$('#' + $(this).attr('href').replace('/#', '')).click();
		});
		
		//how-they-see-me functionality
		$('#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;
			});
		});
		
		//temp display page-msg test
		// $('#main-bar .header h3').click(function(e) {
			// Sportpolis.displayPageMsg(e, 'Testowa wiadomość systemowa.')
		// });
		
		//cite posts
		$('#posts li').each(function() {
			var $li = $(this);
			$li.find('.topic-cite').click(function() {
				var textBody = $('#topic-answer')[0];
				var $textBody = $(textBody);
				
				var val = '[cytat ' + $li.find('.nick').text() + ']' + $li.find('.raw-body:first').text() + '[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);
				}
			});
		});
		
		//edit post
		$('#edit-post-link').click(function() {
			$('#edit-post').slideDown();
			$(this).remove();
			return false;
		});
		$('li.edit-post').each(function(){
			var $this = $(this);
			$this.prev().find('a.edit-post-link').click(function() {
				$(this).remove();
				$this.slideDown();
				return false;
			});
		});
		
		//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 {
									Sportpolis.displayError($this.parents('.cell:first'), 'Taki użytkownik nie istnieje!');
								}
							}
						});
					}, 200);
				}
			});
		});
		
		//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;
		});
		
		//hide bubble2
		$('#bubble2').each(function() {
			var $this = $(this);
			setTimeout(function() {
				$this.remove();
			}, 6000);
		});
		
		//sliding main bars
		$('#disciplines').each(function() {
			var $this = $(this);
			var url = window.location.href;
			var filter  = /#/;
			if (filter.test(url)) {
				var id = url.split('#')[1];
				$('#' + id).click();
			}
		});
	},
	
	startValidation: function() {
		$('form.validate').each(function() {
			
			$(this).find('input').focus(function() {
				var global = this.parentNode.parentNode;
				while (!$(global).hasClass('cell')) {
					global = global.parentNode;
				}
				$(global).find('.error').remove();
				$(global).find('.info-ok').remove();
			});
			
			$(this).find('input:not(:submit)').blur(function() {
				var global = this.parentNode.parentNode;
				while (!$(global).hasClass('cell')) {
					global = global.parentNode;
				}
				var ok = true;
				var errorMsg = '';
				if ($(global).hasClass('login')) {
					ok = isLongEnough($(this).attr('value'), 4);
					errorMsg = 'Za kr\u00F3tka nazwa u\u017Cytkownika';
					if (ok) {
						ok = isLogin($(this).attr('value'));
						errorMsg = 'Nazwa użytkownika zawiera nieprawidłowe znaki';
					}
				}
				if ($(global).hasClass('sex')) {
					ok = isGroupChecked($(this).attr('name'));
					errorMsg = 'Wybierz p\u0142e\u0107';
				}
				if ($(global).hasClass('group')) {
					ok = isGroupChecked($(this).attr('name'));
					errorMsg = 'Musisz dokonać wyboru';
				}
				if ($(global).hasClass('reg')) {
					ok = isChecked($(this).attr('id'));
					errorMsg = 'Aby korzysta\u0107 serwisu musisz wyrazi\u0107 zgod\u0119';
				}
				if ($(global).hasClass('email') ||$(global).hasClass('email2')) {
					ok = isMail($(this).attr('value'));
					errorMsg = 'Nieprawid\u0142owy adres e-mail';
					if (ok) {
						if ($(global).hasClass('email') && ($(global.parentNode).find('div.email2 input').attr('value') != null && $(global.parentNode).find('div.email2 input').attr('value') != '')) {
							ok = isPassEqual($(global.parentNode).find('div.email2 input').attr('value'), $(this).attr('value'));
							errorMsg = 'Podane adresy e-mail nie s\u0105 jednakowe';
						}
						if ($(global).hasClass('email2')) {
							ok = isPassEqual($(global.parentNode).find('div.email input').attr('value'), $(this).attr('value'));
							errorMsg = 'Podane adresy e-mail nie s\u0105 jednakowe';
						}
					}
				}
				if ($(global).hasClass('tel')) {
					ok = isPhoneNo($(this).attr('value'));
					errorMsg = 'Nieprawid\u0142owy numer telefonu';
				}
				if ($(global).hasClass('pass') || $(global).hasClass('pass2')) {
					ok = isLongEnough($(this).attr('value'), 6);
					errorMsg = 'Has\u0142o powinno mie\u0107 conajmniej 6 znak\u00F3w';
					if (ok) {
						if ($(global).hasClass('pass') && ($(global.parentNode).find('div.pass2 input').attr('value') != null && $(global.parentNode).find('div.pass2 input').attr('value') != '')) {
							ok = isPassEqual($(global.parentNode).find('div.pass2 input').attr('value'), $(this).attr('value'));
							errorMsg = 'Podane has\u0142a nie s\u0105 jednakowe';
						}
						if ($(global).hasClass('pass2')) {
							ok = isPassEqual($(global.parentNode).find('div.pass input').attr('value'), $(this).attr('value'));
							errorMsg = 'Podane has\u0142a nie s\u0105 jednakowe';
						}
					}
				}
				if ($(global).hasClass('number')) {
					ok = isNumber($(this).attr('value'));
					errorMsg = 'Nieprawid\u0142owy numer';
				}
				if ($(global).hasClass('post-code')) {
					ok = isPostCode($(this).attr('value'));
					errorMsg = 'Nieprawid\u0142owy kod pocztowy';
				}
				if ($(global).hasClass('alphanumeric')) {
					ok = isAlphanumeric($(this).attr('value'));
					errorMsg = 'Pole mo\u017Ce posiada\u0107 tylko litery i liczby';
				}
				if ($(global).hasClass('house-number')) {
					ok = isHouseNumber($(this).attr('value'));
					errorMsg = 'Nieprawid\u0142owy numer domu';
				}
				
				if (!isNotBlank($(this).attr('value'))) {
					ok = false;
					errorMsg = 'To pole jest wymagane';
				}
				
				if (!$(global).hasClass('nr') || isNotBlank($(this).attr('value'))) {
					if (ok) {
						$(global).find('.error').remove();
					}
					else {
						//$(global).addClass('error');
						if (!$(global).find('.error').length) {
							$(global).append(getErrorMsg(errorMsg));
							$(global).find('.error').fadeIn(1000);
						}
					}
				}
			});
			$(this).find('select').blur(function() {
				var global = this.parentNode.parentNode;
				while (!$(global).hasClass('cell')) {
					global = global.parentNode;
				}
				var ok = true;
				var errorMsg = '';
				
				if (!isSelectChosen($(this).attr('value')) && !$(this).hasClass('nr')) {
					ok = false;
					errorMsg = 'To pole jest wymagane';
				}
				
				if (!$(global).hasClass('nr') || isNotBlank($(this).attr('value'))) {
					if (ok) {
						$(global).find('.error').remove();
					}
					else {
						//$(global).addClass('error');
						if (!$(global).find('.error').length) {
							$(global).append(getErrorMsg(errorMsg));
							$(global).find('.error').fadeIn(1000);
						}
					}
				}
			});
			$(this).find('input[name="captcha"]').blur(function() {
				var $field = $(this);
				var global = this.parentNode.parentNode;
				while (!$(global).hasClass('cell')) {
					global = global.parentNode;
				}
				var value = $field.val();
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: '/validatecaptcha',
					data: 'captcha_key='+value,
					success: function(data) {
						if (!data) {
							if ($(global).find('.error').length == 0) {
								$(global).append('<div class="error">Nieprawidłowy kod!</div>');
								$(global).find('.error').fadeIn(1000);
							}
						}
					}
				});
			});
			$(this).find('input[name="groupname"]').blur(function() {
				var $field = $(this);
				var global = this.parentNode.parentNode;
				while (!$(global).hasClass('cell')) {
					global = global.parentNode;
				}
				var value = $field.val();
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: '/checkgroupname',
					data: 'groupname='+value,
					success: function(data) {
						//console.log(data);
						if (data[0]) {
							if ($(global).find('.error').length == 0) {
								$(global).append('<div class="error">Nieprawidłowy kod!</div>');
								$(global).find('.error').fadeIn(1000);
							}
						}
					}
				});
			});
			$(this).find('input[name="personal_number"]').each(function() {
				var $this = $(this);
				var input = this;
				
				function checkAvail() {
					var $field = $this;
					var global = input.parentNode.parentNode;
					while (!$(global).hasClass('cell')) {
						global = global.parentNode;
					}
					var value = $field.val();
					if (isNumber(value)) {
						$(global).find('.error').remove();
						$(global).find('.info-ok').remove();
						$.ajax({
							type: 'GET',
							dataType: 'json',
							url: '/checkpersonalnumber',
							data: 'personal_number='+value,
							success: function(data) {
								//console.log(data);
								if (data[0]) {
									$(global).find('.user-number-options').before('<div class="error">Numerek już zajęty!</div>');
									$(global).find('.error').fadeIn(1000);
								}
								else {
									$(global).find('.user-number-options').before('<div class="info-ok">Numerek dostępny!</div>');
									$(global).find('.info-ok').fadeIn(1000);
								}
							}
						});
					}
					else {
						if ($(global).find('.error').length == 0) {
							$(global).find('.user-number-options').before('<div class="error">Podaj numer złożony tylko z cyfr!</div>');
							$(global).find('.error').fadeIn(1000);
						}
					}
				}
				function generate() {
					var $field = $this;
					var global = input.parentNode.parentNode;
					while (!$(global).hasClass('cell')) {
						global = global.parentNode;
					}
					var value = $field.val();
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: '/getrandnumber',
						data: 'i=' + index++,
						success: function(data) {
							if (data[0]) {
								$this.val(data[0]);
								$(global).find('.error').remove();
								$(global).find('.info-ok').remove();
							}
						}
					});
				}
				
				$this.blur(function() {
					if ($this.val() == '' || $this.val() == null) {
						generate();
					}
					else {
						checkAvail();
					}
				});
				$('#number-avail-check').click(function() {
					checkAvail();
					return false;
				})
				var index = 0;
				$('#generate-number').click(function() {
					generate();
					return false;
				});
				
				$('input[name="password1"]').focus(function() {
					if ($this.val() == '' || $this.val() == null) {
						var $field = $this;
						var global = input.parentNode.parentNode;
						while (!$(global).hasClass('cell')) {
							global = global.parentNode;
						}
						var value = $field.val();
						$.ajax({
							type: 'GET',
							dataType: 'json',
							url: '/getrandnumber',
							data: 'i=' + index++,
							success: function(data) {
								if (data[0]) {
									$this.val(data[0]);
									$(global).find('.error').remove();
									$(global).find('.info-ok').remove();
								}
							}
						});
					}
				});
			});
		});
		function isSelectChosen(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) {
			var parent = document.getElementById(el).parentNode;
			if ($(parent).find('#' + el + ':checked').length) {
				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;
		}
		
		$('form.validate').each(function() {
			$(this).submit(function() {
				if ($(this).find('.error').length <= 0) {
					$(this).find('div.cell:not(.nr)').each(function() {
						$(this).find('input').blur();
						$(this).find('select').blur();
					})
					if ($(this).find('.error').length > 0) {
						return false;
					}
					else return true;
				}
				else {
					return false;
				}
			});
		});

	},
	
	addRating: function() {
		if ($('.rate-box').length || document.getElementById('comments-section')) {
			var rate_id = $('#itemid').attr('title');
			var module_id = $('#moduleid').attr('title');
			
			//rate comments
			if (document.getElementById('comments-section')) {
				$('.comments ul li').each(function() {
					var $comm = $(this);
					
					if ($comm.hasClass('blocked')) {
						$comm.find('a.show-blocked').click(function() {
							$(this).remove();
							$comm.removeClass('blocked');
							return false;
						});
					}
					
					var comm_id = $comm.attr('id').replace('comment_', '');
					$comm.find('.options-bar a').click(function() {
						if (this.className == 'rate-plus') {
							var rate = 'plus';
							var addon = 1;
						}
						else if (this.className == 'rate-minus') {
							var rate = 'minus';
							var addon = -1;
						}
						else {
							return true;
						}
						
						if (rate) {
							$.ajax({
								type: 'GET',
								dataType: 'json',
								url: '/plusminus',
								data: 'moduleid='+module_id+'&itemid='+rate_id+'&id='+comm_id+'&rate='+rate,
								success: function(data) {
									if (data) {
										$comm.find('.rate-plus').remove();
										$comm.find('.rate-minus').remove();
										$comm.find('.rate-total').text('[' + (parseInt($comm.find('.rate-total').text().replace('[', '').replace(']', ''), 10) + addon) + ']');
										//Cookie.create('rc-'+module_id+'-'+rate_id, 'true', 365);
									}
								}
							});
						}
						
						return false;
					});
				});
			}
		}
	},
	
	registrationChecks: function() {
		$('#registration').each(function() {
			$this = $(this);
			$this.find('input[name="register_login"]').blur(function() {
				var $field = $(this);
				var global = this.parentNode.parentNode;
				while (!$(global).hasClass('cell')) {
					global = global.parentNode;
				}
				var value = $field.val();
				if (value != '') {
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: '/checklogin',
						data: 'login='+value,
						success: function(data) {
							if (data[0]) {
								if (data[0] == 'exists') {
									$(global).append('<div class="error">Użytkownik o takiej nazwie już istnieje!</div>');
								}
								else if (data[0] == 'vulgar') {
									$(global).append('<div class="error">Login nie może zawierać niecenzuralnych słów!</div>');
								}
								
								
								$(global).find('.error').fadeIn(1000);
							}
						}
					});
				}
			});
			$this.find('input[name="email1"]').blur(function() {
				var $field = $(this);
				var global = this.parentNode.parentNode;
				while (!$(global).hasClass('cell')) {
					global = global.parentNode;
				}
				var value = $field.val();
				if (value != '') {
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: '/checkemail',
						data: 'email='+value,
						success: function(data) {
							if (data[0]) {
								$(global).append('<div class="error">Podany e-mail jest już użyty przez innego użytkownika!</div>');
								$(global).find('.error').fadeIn(1000);
							}
						}
					});
				}
			});
			
			//real/fictitious account choice
			/*
			var $real = $('#choose-real');
			var $fict = $('#choose-fictitious');
			var $number = $('#personal-number');
			var $real_fields = $('.real_user');
			if ($real[0].checked == 1) {
				$number.show().removeClass('nr');
				$real_fields.show().removeClass('nr');
			}
			if ($fict[0].checked == 1) {
				$number.hide();
				$real_fields.hide();
			}
			$real.click(function() {
				$number.show().removeClass('nr');
				$real_fields.show().removeClass('nr');
			});
			$fict.click(function() {
				$number.hide();
				$real_fields.hide();
				if (!$number.hasClass('nr')) {
					$number.addClass('nr');
					$real_fields.addClass('nr');
				}
			});
			*/
		});
		
	},
	
	initMyTooltip: function() {
		
		function giveTooltip($el, text) {
			var txt = 	'<div id="tooltip">' +
							'<div class="touter">' +
								'<div class="tinner">' +
									'<div class="tinner-top"></div>' +
									'<div class="tinner-right"></div>' +
									'<div class="tvalue">' +
										text +
									'</div>' +
								'</div>' +
							'</div>' +
						'</div>';
			$el.hover(function() {
				if (!document.getElementById('tooltip')) {
					$el.click(function() {
						return false;
					});
					if ($el.css('position') != 'absolute') {
						$el.css('position', 'relative');
					}
					$el.append(txt);
					var $tooltip = $('#tooltip');
					$tooltip.css('left', $el.width() + 1 + 'px');
					if ($.browser.msie && /MSIE 6.0/.test(navigator.userAgent)) {
						$tooltip.css('bottom', $el.height() + 61 + 'px');
					}
					else {
						$tooltip.css('bottom', $el.height() + 1 + 'px');
					}
					$tooltip.show();
					$tooltip.find('.tinner-top').width($tooltip.width() - 5);
					$tooltip.find('.tinner-right').height($tooltip.height() - 13);
				}
			}, function() {
				$('#tooltip').remove();
				$el.unbind('click');
			});
		}
		
		giveTooltip($('#open-group-tip'), 'Każdy może dołączyć do Twojej grupy');
		giveTooltip($('#closed-group-tip'), 'Dołączenie do grupy wymaga Twojej zgody');
		
		$('.give-tooltip').each(function() {
			var $this = $(this);
			giveTooltip($this, $this.next().html());
		});
			
	},
	
	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-l"></span><span class="btn-c">Aktualizuj mapę</span><span class="btn-r"></span></a>');
				var $update_link = $set_link.next();
				$set_link.remove();
				
				if (google.maps.BrowserIsCompatible()) {
					Sportpolis.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) {
								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ść.');
				$('#set-geolocation').parents('.cell:first').append('<div class="error shown">Aby ustawić lokalizację na mapie, musisz wpisać przynajmniej miejscowość.</div>');
			}
			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;});
				Sportpolis.startMapLoader();
				loadMaps();
				
				$('#hide-geomap').click(function() {
					$geomap_wrapper.hide();
					return false;
				});
			}
			
			return false;
		});
		
	},
	
	initMap: function() {
		function initLoader(fn) {
			if (location.href.split('/')[2] == 'www.sportpolis.pl') {
				var key = 'ABQIAAAAmpUSQ0sk3U1W4MfaQUxY1xQEWvsQOFtWu0sxWFPA2kuODMY5qxQCeXFxTYeRNfg3iCF6upbMQ-Uicg';
			}
			else {
				var key = 'ABQIAAAAmpUSQ0sk3U1W4MfaQUxY1xQiDCYn2xY9icMs-4-offAxDWHyRBRY2QJ_sW5QykMAwZMvty0eVjaisQ';
			}
			Sportpolis.startMapLoader();
			var script = document.createElement("script");
			script.src = 'http://www.google.com/jsapi?key=' + key + '&callback=Sportpolis.' + fn;
			script.type = "text/javascript";
			document.getElementsByTagName("head")[0].appendChild(script);
		}
		$('#map-location').each(function() {
			initLoader('geolocShowMap');
		});
	},
	
	startMapLoader: function() {
		$('.gmap').append('<div id="gmap-loader">Wczytuję mape...</div>');
	},
	
	stopMapLoader: function() {
		$('#gmap-loader').remove();
	},
	
	addConfirmations: function() {
		function confirm($el, text) {
			$el.click(function() {
				return window.confirm(text);
			});
		}
		confirm($('#comments-section .comments li .del'), 'Czy na pewno chcesz usunąć komentarz?');
		confirm($('#main.observed a.bin'), 'Czy na pewno chcesz usunąć z obserwowanych?');
	},
	
	initBanners: function() {
		// billboard
		var flashvars = {
			'clickTag': 'http://www.informatorsportowy.pl/programlojalnoscowy/0,0,0.html'
		};
		var params = {
			'wmode': 'transparent'
		};
		var attributes = {};
		
		//temp:
		//$('#banner750').append('<div id="banner-billboard"');
		
		//swfobject.embedSWF("/displaysp/swf/pieczatki2.swf", "banner-billboard", "750", "100", "8.0.0", "/displaysp/swf/expressInstall.swf", flashvars, params, attributes);
		
		/*
		if (document.getElementById('form-banner')) {
			var flashvars = {
				'clickTag': 'http://www.informatorsportowy.pl/programlojalnoscowy/0,0,0.html'
			};
			var params = {
				'wmode': 'transparent'
			};
			var attributes = {};

			swfobject.embedSWF("/display/swf/kubicasky.swf", "form-banner", "160", "600", "8.0.0", "/display/swf/expressInstall.swf", flashvars, params, attributes);
		}
		
		if (document.getElementById('banner-sky')) {
			var flashvars = {
				'clickTag': 'http://www.informatorsportowy.pl/programlojalnoscowy/0,0,0.html'
			};
			var params = {
				'wmode': 'transparent'
			};
			var attributes = {};

			swfobject.embedSWF("/display/swf/pieczatki.swf", "banner-sky", "160", "600", "8.0.0", "/display/swf/expressInstall.swf", flashvars, params, attributes);
		}
		*/
	},
	
	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;
			});
		});
	},
	
	addForumFunctionality: function() {
		$('form.posting-form').each(function() {
			$forum = $(this);
			textBody = $forum.find('textarea')[0];
			$textBody = $(textBody);
			
			$forum.find('#o-bold').click(function() {
				insertSnippet('[b][/b]');
				return false;
			});
			$forum.find('#o-under').click(function() {
				insertSnippet('[u][/u]');
				return false;
			});
			$forum.find('#o-italic').click(function() {
				insertSnippet('[i][/i]');
				return false;
			});
			
			$forum.find('#o-img').click(function() {
				var href = window.prompt('Podaj adres obrazka', 'http://')
				if (href) {
					insertEmot('[img]' + href + '[/img]');
				}
				return false;
			});
			$forum.find('#o-link').click(function() {
				var href = window.prompt('Podaj adres odnosnika', 'http://')
				var caption = window.prompt('Podaj nazwę odnośnika', '')
				if (href && caption) {
					insertEmot('[url href=' + href + ']' + caption + '[/url]');
				}
				return false;
			});
			$forum.find('.toptions li.t-email a').click(function() {
				insertSnippet('[email][/email]');
				return false;
			});
			$forum.find('.toptions li.t-gg a').click(function() {
				insertSnippet('[gg][/gg]');
				return false;
			});
			
			$forum.find('#e-smile').click(function() {
				insertEmot(' :) ');
				return false;
			});
			$forum.find('#e-wink').click(function() {
				insertEmot(' ;) ');
				return false;
			});
			$forum.find('#e-grin').click(function() {
				insertEmot(' :D ');
				return false;
			});
			$forum.find('#e-cool').click(function() {
				insertEmot(' 8) ');
				return false;
			});
			$forum.find('#e-woot').click(function() {
				insertEmot(' :O ');
				return false;
			});
			$forum.find('#e-notcool').click(function() {
				insertEmot(' :/ ');
				return false;
			});
			
			
			function insertSnippet(val, extra) {
				len = val.split('[/')[0].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;
				}
				
				if (selectionStart == 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 + len + 1;
						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);
					}
				}
				else {
					var snippet_parts = val.split('[/');
					var first_insert = snippet_parts[0];
					var second_insert = '[/' + snippet_parts[1];
					
					var text_start = $textBody.val().substring(0, selectionStart);
					var text_middle = $textBody.val().substring(selectionStart, selectionEnd);
					var text_end = $textBody.val().substring(selectionEnd);
					var new_text = text_start + first_insert + text_middle + second_insert + text_end;
					$textBody.val(new_text);
				}
			}
			
			function insertEmot(val) {
				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);
				}
				
			}
			
			// Moove post to functionality
			$('form.move-post').each(function() {
				$form = $(this);
				$select = $form.find('select:first');
				
				$select.bind('change', function() {
					if ($(this).val() != '') {
						var decision = window.confirm('Czy na pewno chcesz przeniesc temat do: ' + $(this).find('option:selected').text());
						if (decision) {
							$form.submit();
						}
					}
				});
			});
			
		});
	},
	
	initDatepicker: function() {
		$('#birthdateDatepicker').each(function() {
			var $cal = $(this);
			var $parent = $cal.parent().parent();
			var $day = $parent.find('select[name="birthdate_day"]');
			var $month = $parent.find('select[name="birthdate_month"]');
			var $year = $parent.find('select[name="birthdate_year"]');
			var starting_year = parseInt($year.find('option:first').text(), 10);
			var ending_year = parseInt($year.find('option:last').text(), 10);
			var range_beg = new Date(starting_year, 1 - 1, 1);
			var range_end = new Date(ending_year, 12 - 1, 31);
			$cal.datepicker({
				monthNamesShort: ['Sty','Lut','Mar','Kwi','Maj','Cze','Lip','Sie','Wrz','Paz','Lis','Gru'],
				dayNamesShort: ['Nie', 'Pon', 'Wt','Śr', 'Czw', 'Pt', 'Sob'],
				dayNamesMin: ['Nie', 'Pon', 'Wt','Śr', 'Czw', 'Pt', 'Sob'],
				firstDay: 1,
				minDate: range_beg,
				maxDate: range_end,
				yearRange: starting_year+':'+ending_year,
				showOn: 'button', 
				buttonImage: 'http://static.sportpolis.pl/static/calendar.gif', 
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true,
				beforeShow: function() {
					 $cal.val($month.val() + '/' + $day.val() + '/' + $year.val());
				},
				onSelect: function() {
					var date = $cal.val();
					$month.val(date.substring(0, 2));  
					$day.val(date.substring(3, 5));  
					$year.val(date.substring(6, 10));
				}
			});
		});
	},
	
	displayError: function($cell, message) {
		if ($cell.find('.error').length == 0) {
			$cell.append('<div class="error">' + message + '</div>');
			$cell.find('.error').fadeIn(1000);
		}
	},
	
	displayPageMsg: function(e, msg) {
		$('body').append('<div class="sp-page-msg"><div class="inner">' + msg + '</div></div>');
		var $msg = $('body > .sp-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);
		}
	}
}

$(function() {
	Sportpolis.start();
});