﻿var Shooters = {
	preferences: {
		
	},

	start: function() {
		this.startMyServers();
		this.startAmxConf();
		this.tweakLayout();
		this.mailFix();
		this.transformButtons();
		// imageRotate(number_of_images, interval_in_sec);
		//this.imageRotate(6, 10);
		this.startTabs();
		this.changeServersName();
		this.initializePopups();
		this.startValidation();
		this.colorTable();
		// startGallery(width_with_margin, number_of_elements_on_screen);
		this.startGallery(115, 4);
		this.startServersChoice();
		this.startMoreSlots();
		this.startMoreMonths();
		this.serverReinstallWarning();
		this.serverStatsClipboard();
		this.startCountdown();
		this.startCommandBoxes();
		this.startToolTips();
		this.confirmations();
	},
	
	
	tweakLayout: function() {
		$('html').addClass('js');
		var global = this;
		$('input[alt]').each(function() {
			var width = this.alt;
			var s = width.split('.');
			if (s.length == 2) {
				$(this).css({
					'width': s[0] + '%',
					'margin-right': s[1] + '%'
				})
			}
		});
		//$('form div > label').wrapInner('<span></span>');
		
		// Fixing navigation for IE 6
		/*
		if ($.browser.msie) {
			$('#nav').find('li.selected a').each(function() {
				$('<span class="ienav"></span>').insertBefore($(this))}).end()
					.find('li.current span').each(function() {
				$('<span class="ienav"></span>').insertBefore($(this))});
		};
		
		// Fixing partners and friends last A margin
		$('#partners > div.partners-list > .banner:last').addClass('last');
		$('#friends > div.friends-list > .banner:last').addClass('last');
		*/
		
		// Round #nav corners
		$('#nav').append('<div class="crn-l-t"></div><div class="crn-r-t"></div><div class="crn-l-b"></div><div class="crn-r-b"></div>');
		
		// Tweaking FAQ
		$('#help li').each(function() {
			var global = this;
			$(this).find('div.answer').hide();
			var question = $(this).find('p.question').text();
			$(this).find('p.question').remove();
			$(this).prepend('<a href="#" class="question">' + question +' <span>(zobacz odpowiedź)</span></a>');
			$(this).find('a.question').toggle(function() {
				$(global).find('div.answer').slideDown();
				return false;
			}, function() {
				$(global).find('div.answer').slideUp();
				return false;
			});
		});
		
		//Tweaking wallet top-up
		
		$('#wallet form.top-up-validate').each(function() {
			var form = this;
			$(this).find('li').each(function(){
				var li = this;
				var logo = $(this).find('label.logo').html();
				$(this).find('label.logo').remove();
				$(this).prepend('<a href="#" class="logo">' + logo + '</a>');
				$(this).find('label').hide();
				$(form).find('div.btn').hide();
				$(this).find('a.logo').click(function() {
					$(li).find(':radio:first').attr('checked', 'checked');
					$(form).submit();
					return false;
				});
			});
		});
		
		//Tweaking buttons for Opera
		if ($.browser.opera || ($.browser.msie && /MSIE 8.0/.test(navigator.userAgent))) {
			$('a.button').addClass('opera');
		}
		
		//Fix linked servers
		$('.list li.linked li:last a .top').css('background-image', 'none');
		
		//Tweaking free-servers
		$('#free-servers > table > tbody > tr').each(function() {
			var $tr = $(this);
			var ip = $tr.find('.ip').text();
			
			//var players = $tr.find('.players').text();
			
			//$tr.hide();
			
			$header = $tr.find('td > .header:first');
			$header.find('p.title-info').append('| <a class="details close" href="">Szczegółowe statystyki</a>');
			
			var id = parseInt($header.find('h3:first').attr('id').replace('serv-id_', ''));
			
			var header = $header.html();
			
			//$header.find('p.title-info a.close').append(' (schowaj)');
			/*
			var insert = '<tr class="shrinked">' +
							'<td>' +
								'<div class="header">' +
									header +
								'</div>' +
							'</td>' +
							'<td>' + ip + '</td>' +
							'<td class="players-amount">' + players + '</td>' +
						'</tr>';
			*/
			
			/*
			
			*/
			
			
			$tr.find('a.details').click(function() {
				var $a = $(this);
				$a.addClass('loading');
				$a.unbind('click');
				$a.click(function() {
					return false;
				});
				var insert = '';
				$.ajax({
				type: 'POST',
			    dataType: 'json',
			    url: 'moje-serwery/' + id + '/statystyki',
			    data: '',
			    success: function(data) {
					$a.removeClass('loading');
					$a.attr('href', '');
					if (!data) {
						var insert = '<div class="favoured">' +
									'<div>'
										'<p>Server offline</p>' +
									'</div>' +
								'</div>';
						var insert = '<tr class="full">' +
									'<td colspan="2">' +
										'<div class="header">' +
											header +
										'</div>' +
										'<div class="columns">' +
											'<div class="stats">' +
												'<div class="favoured">' +
													'<div>' +
														'<p>Server offline</p>' +
													'</div>' +
												'</div>' +
											'</div>' +
											'<div class="overall-stats">' +
												'<table>' +
													'<colgroup>' +
														'<col class="size35" />' +
														'<col class="size65" />' +
													'</colgroup>' +
													'<thead>' +
														'<tr>' +
															'<th scope="col">Tytuł</th>' +
															'<th scope="col">Wartość</th>' +
														'</tr>' +
													'</thead>' +
													'<tbody>' +
														'<tr>' +
															'<td>IP</td>' +
															'<td><span class="ip-address">' + ip + '</span></td>' +
														'</tr>' +
														'<tr>' +
															'<td>GRACZY</td>' +
															'<td><span class="players">0</span></td>' +
														'</tr>' +
													'</tbody>' +
												'</table>' +
											'</div>' +
										'</div>' +
									'</td>' +
								'</tr>';
						$tr.hide();
						$tr.after(insert);
						var $newTr = $tr.next();
						$newTr.find('p.title-info a.close').append(' (schowaj)');
						
						$newTr.find('p.title-info a.close').click(function() {
							$newTr.hide();
							$tr.show();
							return false;
						});
						
						$tr.find('p.title-info a.details').click(function() {
							$tr.hide();
							$newTr.show();
							return false;
						});
					}
					else {
						var current_server_slots = data.players.length;
						var max_server_slots = data.max_players;
						
						var insert = '<tr class="full">' +
										'<td colspan="2">' +
											'<div class="header">' +
												header +
											'</div>' +
											'<div class="columns">' +
												'<div class="stats">' + 
												'<p class="name">GRACZY</p>' +
												'<p class="value">' + current_server_slots + '/ ' + max_server_slots + '</p>' +
												'<table class="data">' +
													'<colgroup>' +
														'<col class="size15" />' +
														'<col class="size65" />' +
														'<col class="size20" />' +
													'</colgroup>' +
													'<thead>' +
														'<tr>' +
															'<th scope="col">RANK</th>' +
															'<th scope="col">NAME</th>' +
															'<th scope="col">POINTS</th>' +
														'</tr>' +
													'</thead>' +
													'<tbody>';
														for (i = 0; i < data.players.length; i++) {
															if (i % 2 != 0) {
															insert += '<tr class="even">';
															}
															else {
															insert += '<tr>';
															}
															insert +=
															'<td>' + (i + 1) + '</td>' +
															'<td>' + data.players[i].name + '</td>' +
															'<td>' + data.players[i].score + '</td>' +
														'</tr>';
														}
													insert +=
													'</tbody>' +
												'</table>' +
												'<p class="name">Aktualizacja:</p>' +
												'<p class="value">' + data.date + '</p>' +
												'</div>' +
												'<div class="overall-stats">' +
													'<table>' +
														'<colgroup>' +
															'<col class="size35" />' +
															'<col class="size65" />' +
														'</colgroup>' +
														'<thead>' +
															'<tr>' +
																'<th scope="col">Tytuł</th>' +
																'<th scope="col">Wartość</th>' +
															'</tr>' +
														'</thead>' +
														'<tbody>' +
															'<tr>' +
																'<td>IP</td>' +
																'<td><span class="ip-address">' + ip + '</span></td>' +
															'</tr>' +
															'<tr>' +
																'<td>GRACZY</td>' +
																'<td><span class="players">' + current_server_slots + '</span></td>' +
															'</tr>' +
														'</tbody>' +
													'</table>' +
												'</div>' +
											'</div>' +
										'</td>' +
									'</tr>';
						$tr.hide();
						$tr.after(insert);
						var $newTr = $tr.next();
						$newTr.find('p.title-info a.close').append(' (schowaj)');
						
						$newTr.find('p.title-info a.close').click(function() {
							$newTr.hide();
							$tr.show();
							return false;
						});
						
						$tr.find('p.title-info a.details').click(function() {
							$tr.hide();
							$newTr.show();
							return false;
						});
					}
				}
				});
				return false;
			});
		});
		
		// Vertical center payment-images for IE
		if ($.browser.msie && /MSIE 6.0/.test(navigator.userAgent) && $('.payment-operators .logo').length) {
			$('.payment-operators .logo img').each(function() {
				var $img = $(this);
				var width = Math.round($(this).width()/2);
				var height = Math.round($(this).height()/2);
				$img.css('position', 'absolute');
				$img.css('left', '50%');
				$img.css('top', '50%');
				$img.css('margin', '-' + height + 'px auto auto -' + width + 'px');
			});
		}
		
		// 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');
					$('#top').append('<a href="' + href + '" id="logo-fix"></a>');
				}
			}
			
		}
		
	},
	
	imageRotate: function(n, delay) {

		
		tweakMasthead();

		delay *= 1000;
		
		$('#masthead-rotator').cycle({ 
			fx:     'fade', 
			speed:   4000, 
			timeout: delay
		});
		
		function tweakMasthead() {
			$('#masthead').addClass('rotator');
			var content = '<div id="masthead-rotator">';
			for (i = 0; i < n; i++) {
				content += '<img src="http://beta.shooters.pl/css/i/bg/masthead-bg' + (i+1) + '.jpg" alt="" />'
			}
			content += '</div>';
			$('#masthead').append(content);
		}
	},

	transformButtons: function() {
		$('a.button').each(function() {
			var $this = $(this);
			var classes = this.className;
			var id = $this.attr('id');
			var href = $this.attr('href');
			var text = $this.text();
			$this.after('<a href="' + href + '" class="' + classes + '"><span class="btn-l"></span><span class="btn-c">' + text + '</span><span class="btn-r"></span></a>');
			var $new_link = $this.next();
			if (id != 'undefined') {
				$new_link.attr('id', id);
			}
			$this.remove();
		});
		$('input.button').each(function() {
			var $submit = $(this);
			var classes = this.className;
			var val = $submit.attr('value');
			$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();
				return false;
			});
			$submit.hide();
		});
	},
	
	faux_hover: function($element, cascade, className) {
		$(document).bind('mouseover', function(e) {
			if($(e.target).parents('li#dash-language').length) {
				$element.find(cascade).show();
				$element.addClass(className);
			} else {
				$element.find(cascade).hide();
				$element.removeClass(className);
			}
		});
		
	},
	
	startTabs: function() {
		function createCookie(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=/";
		}
		function readCookie(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;
		}

		if ($('ul.tabs').length) {
			$('ul.tabs').each(function() {
				$(this).show();
				var parent = this.parentNode;
				$(parent).find('.tab').each(function() {
					$(this).addClass('inactive');
					$(this).find('.header:first').remove();
				});
				var currentTab = readCookie('currentTab');
				$('#' + currentTab).addClass('selected');
				if ($(this).find('li.selected').length == 0) {
					$(this).find('li:first').addClass('selected');
				}
				var a = this;
				$(this).find('li > a').click(function() {
					$(a).find('li.selected').removeClass('selected');
					$(this.parentNode).addClass('selected');
					createCookie('currentTab', $(this.parentNode).attr('id'));
					
					var tabName = $(this.parentNode).attr('id').replace('t-', '');
					$(parent).find('.tab').each(function() {
						if (!$(this).hasClass('inactive')) {
							$(this).addClass('inactive');
						}
						$(parent).find('#tab-' + tabName).removeClass('inactive');
					});
					return false;
				});
				$(this).find('li.selected > a').click();
			});
		}
		
		$('#change-ftp-pswd').click(function() {
			$('#tab-informacje').addClass('inactive');
			$('#tab-kontoftp').removeClass('inactive');
			$('#t-informacje').removeClass('selected');
			$('#t-kontoftp').addClass('selected');
			createCookie('currentTab', 't-kontoftp');
			return false;
		});
		$('#change-slot-quant').click(function() {
			$('#tab-informacje').addClass('inactive');
			$('#tab-konfiguracja').removeClass('inactive');
			$('#t-informacje').removeClass('selected');
			$('#t-konfiguracja').addClass('selected');
			createCookie('currentTab', 't-konfiguracja');
			return false;
		});
		
		// Delete tab cookie while ordering new server
		$('form.order').submit(function() {
			createCookie('currentTab', '', -1);
		});
	},
	
	changeServersName: function() {
		$('#your-servers .ip').hide();
		if ($('#your-servers li > span.inner .ip').text() != ''){
			$('#your-servers li > a').hover(function() {
				$(this).find('.server-name').toggle().end()
					.find('.ip').toggle();
			}, function() {
				$(this).find('.server-name').toggle().end()
					.find('.ip').toggle();
			});
			$('#your-servers li > span.inner').hover(function() {
				$(this).find('.server-name').toggle().end()
					.find('.ip').toggle();
			}, function() {
				$(this).find('.server-name').toggle().end()
					.find('.ip').toggle();
			});
		}
	},
	
	startValidation: function() {
		$('div.validate').each(function() {
			
			$(this).find('input').focus(function() {
				var global = this.parentNode;
				if ($(global).hasClass('error')) {
					$(global).removeClass('error');
					$(global).find('.form-error').remove().end()
						.find('.sign').remove();
				}
				else if ($(global).hasClass('ok')) {
					$(global).removeClass('ok');
					$(global).find('.sign').remove();
				}
			});
			$(this).find('input').blur(function() {
				var global = this.parentNode;
				var ok = true;
				var errorMsg = '';
				if ($(global).hasClass('email')) {
					ok = isMail($(this).attr('value'));
					errorMsg = 'Nieprawidłowy adres e-mail';
				}
				if ($(global).hasClass('tel')) {
					ok = isPhoneNo($(this).attr('value'));
					errorMsg = 'Nieprawidłowy numer telefonu';
				}
				if ($(global).hasClass('pass') || $(global).hasClass('pass2')) {
					/*
					ok = isLongEnough($(this).attr('value'), 6);
					errorMsg = 'Hasło powinno mieć conajmniej 6 znaki';
					if (ok) {
						if ($(global).hasClass('pass') && $(global.parentNode).find('div.pass2 input').attr('value') != null) {
							ok = isPassEqual($(global.parentNode).find('div.pass2 input').attr('value'), $(this).attr('value'));
							errorMsg = 'Podane hasła nie są jednakowe';
						}
						if ($(global).hasClass('pass2')) {
							ok = isPassEqual($(global.parentNode).find('div.pass input').attr('value'), $(this).attr('value'));
							errorMsg = 'Podane hasła nie są jednakowe';
						}
					}
					*/
					if ($(global).hasClass('pass') && $(global.parentNode).find('div.pass2 input').attr('value') != null) {
						ok = isPassEqual($(global.parentNode).find('div.pass2 input').attr('value'), $(this).attr('value'));
						errorMsg = 'Podane hasła nie są jednakowe';
					}
					if ($(global).hasClass('pass2')) {
						ok = isPassEqual($(global.parentNode).find('div.pass input').attr('value'), $(this).attr('value'));
						errorMsg = 'Podane hasła nie są jednakowe';
					}
				}
				if ($(global).hasClass('number')) {
					ok = isNumber($(this).attr('value'));
					errorMsg = 'Nieprawidłowy numer';
				}
				if ($(global).hasClass('post-code')) {
					ok = isPostCode($(this).attr('value'));
					errorMsg = 'Nieprawidłowy kod pocztowy';
				}
				if ($(global).hasClass('alphanumeric')) {
					ok = isAlphanumeric($(this).attr('value'));
					errorMsg = 'Pole może posiadać tylko litery i liczby';
				}
				if ($(global).hasClass('house-number')) {
					ok = isHouseNumber($(this).attr('value'));
					errorMsg = 'Nieprawidłowy 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).addClass('ok');
						$(global).find('.form-error').remove();
					}
					else {
						$(global).addClass('error');
						if (!$(global).find('.form-error').length) {
							$(global).append(getErrorMsg(errorMsg));
							$(global).find('.form-error').fadeIn(1000);
						}
					}
					$(this).after('<span class="sign"></span>');
					$(global).find('.sign').css('left', ($(this).width() + 15 + 'px'));
				}
			});
		});
		
		function isNotBlank(val) {
			if (val != null) return true;
			else return false;
		}
		function isLongEnough(val, n) {
			if (val != null && val.length >= n) return true;
			else return false;
		}
		function getErrorMsg(msg) {
			var message = 	'<div class="form-error">' +
								'<p><span>Błąd</span> ' + msg + '</p>' +
							'</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.comment-validate').submit(function() {
			$(this.parentNode).find('.error-msg').remove();
			
			var isError = false;
			var msg = '<div class="error-msg">' +
							'<div>' +
								'<div class="inner">' +
									'<p class="msg">Wystąpiły błędy w formularzu</p>';
			if ($('#commenterName').length) {
				if (!isNotBlank($('#commenterName').attr('value'))) {
					msg += 			'<p>- Podpis jest wymagany</p>';
					isError = true;
				}
				if (!isNotBlank($('#commenterEmail').attr('value'))) {
					msg += 			'<p>- Email jest wymagany</p>';
					isError = true;
				}
				else if (!isMail($('#commenterEmail').attr('value'))) {
					msg += 			'<p>- Nieprawidłowy adres e-mail</p>';
					isError = true;
				}
			}
			if (!isNotBlank($('#commentBody').attr('value'))) {
				msg += 			'<p>- Komentarz jest wymagany</p>';
				isError = true;
			}
			
			msg += 				'</div>' +
							'</div>' +
						'</div>';
						
			if (isError) {
				$(this).before(msg);
				return false;
			}
			else {
				return true;
			}
		});
		
		//console.log($('form.contact-validate'));
		$('form.contact-validate').each(function() {
			var $this = $(this);
			$(this.parentNode).find('.error-msg').remove();
			$(this).find('a.button').unbind('click').click(function() {
				$this.parent().find('.error-msg').remove();
				var isError = false;
				var msg = '<div class="error-msg">' +
								'<div>' +
									'<div class="inner">' +
										'<p class="msg">Wystąpiły błędy w formularzu</p>';
				if (document.getElementById('contactName') && !isNotBlank($('#contactName').attr('value'))) {
					msg += 			'<p>- Podpis jest wymagany</p>';
					isError = true;
				}
				if (document.getElementById('contactEmail')) {
					if (!isNotBlank($('#contactEmail').attr('value'))) {
						msg += 			'<p>- Email jest wymagany</p>';
						isError = true;
					}
					else if (!isMail($('#contactEmail').attr('value'))) {
						msg += 			'<p>- Nieprawidłowy adres e-mail</p>';
						isError = true;
					}
				}
				if (!isNotBlank($('#contactBody').attr('value'))) {
					msg += 			'<p>- Teść jest wymagana</p>';
					isError = true;
				}
				
				msg += 				'</div>' +
								'</div>' +
							'</div>';
							
				if (isError) {
					$this.before(msg);
				}
				else {
					$(this).prev().click();
				}
				return false;
			});
		});
		
		$('form.login-validate').submit(function() {
			$(this.parentNode).find('.error-msg').remove();
			
			var isError = false;
			var msg = '<div class="error-msg">' +
							'<div>' +
								'<div class="inner">' +
									'<p class="msg">Wystąpiły błędy w formularzu</p>';

			if (!isNotBlank($('#login').attr('value'))) {
				msg += 			'<p>- Login jest wymagany</p>';
				isError = true;
			}
			if (!isNotBlank($('#password').attr('value'))) {
				msg += 			'<p>- Hasło jest wymagane</p>';
				isError = true;
			}
		
			msg += 				'</div>' +
							'</div>' +
						'</div>';
						
			if (isError) {
				$(this).before(msg);
				return false;
			}
			else {
				return true;
			}
		});
		
		$('form.register-validate').submit(function() {
			$(this.parentNode).find('.error-msg').remove();
			
			var isError = false;
			var msg = '<div class="error-msg">' +
							'<div>' +
								'<div class="inner">' +
									'<p class="msg">Wystąpiły błędy w formularzu</p>';

			if (!isLogin($('#login').attr('value'))) {
				msg += 			'<p>- Proszę wprowadzić prawidłowy login (przynajmniej 4 znaki alfanumeryczne)</p>';
				isError = true;
			}
			if (!isLongEnough($('#password-register').attr('value'), 6)) {
				msg += 			'<p>- Proszę wprowadzić prawidłowe hasło (przynajmniej 6 znaków)</p>';
				isError = true;
			}
			if ($('#password-register').attr('value') != $('#passwordConfirm').attr('value')) {
				msg += 			'<p>- Hasła muszą być identyczne</p>';
				isError = true;
			}
			if (!isMail($('#email').attr('value'))) {
				msg += 			'<p>- Proszę wprowadzić prawidłowy adres e-mail</p>';
				isError = true;
			}
			if (!isLongEnough($('#nick').attr('value'), 2)) {
				msg += 			'<p>- Nick musi składać sie z przynajmniej 2 znaków</p>';
				isError = true;
			}
			if (!isChecked('byelaw')) {
				msg += 			'<p>- Musisz wyrazić zgodę</p>';
				isError = true;
			}
		
			msg += 				'</div>' +
							'</div>' +
						'</div>';
						
			if (isError) {
				$(this).before(msg);
				return false;
			}
			else {
				return true;
			}
		});
		
		$('form.new-subject-validate').submit(function() {
			$(this.parentNode).find('.error-msg').remove();
			
			var isError = false;
			var msg = '<div class="error-msg">' +
							'<div>' +
								'<div class="inner">' +
									'<p class="msg">Wystąpiły błędy w formularzu</p>';

			if (!isNotBlank($('#commentTitle').attr('value'))) {
				msg += 			'<p>- Temat jest wymagany</p>';
				isError = true;
			}
			if (!isNotBlank($('#commentBody').attr('value'))) {
				msg += 			'<p>- Komentarz jest wymagany</p>';
				isError = true;
			}
		
			msg += 				'</div>' +
							'</div>' +
						'</div>';
						
			if (isError) {
				$(this).before(msg);
				return false;
			}
			else {
				return true;
			}
		});
		
		$('form.order-payment-validate').submit(function() {
			$(this.parentNode).find('.error-msg').remove();
			
			var isError = false;
			var msg = '<div class="error-msg">' +
							'<div>' +
								'<div class="inner">' +
									'<p class="msg">Wystąpiły błędy w formularzu</p>';
			
			if (!isNotBlank($('#paymentAmount').attr('value'))) {
				msg += 			'<p>- Kwota jest wymagana</p>';
				isError = true;
			}
			else if (!isPriceAmount($('#paymentAmount').attr('value'))) {
				msg += 			'<p>- Kwota musi być liczbą</p>';
				isError = true;
			}
			if (!isNotBlank($('#paymentId').attr('value'))) {
				msg += 			'<p>- Numer zamówienia jest wymagany</p>';
				isError = true;
			}
			else if (!isNumber($('#paymentId').attr('value'))) {
				msg += 			'<p>- Numer zamówienia musi być liczbą</p>';
				isError = true;
			}
		
			msg += 				'</div>' +
							'</div>' +
						'</div>';
						
			if (isError) {
				$(this).before(msg);
				return false;
			}
			else {
				return window.confirm('Czy na pewno chcesz doładować zamówienie #' + $('#paymentId').attr('value') + ' kwotą: ' + $('#paymentAmount').attr('value') + 'zł ?');
			
				//return true;
			}
		});
		
		$('form.top-up-validate').submit(function() {
			$(this.parentNode).find('.error-msg').remove();
			
			var isError = false;
			var msg = '<div class="error-msg">' +
							'<div>' +
								'<div class="inner">' +
									'<p class="msg">Wystąpiły błędy w formularzu</p>';
			
			if (!isGroupChecked('paymentOperator')) {
				msg += 			'<p>- Proszę wybrać operatora</p>';
				isError = true;
			}
		
			msg += 				'</div>' +
							'</div>' +
						'</div>';
						
			if (isError) {
				$(this).before(msg);
				return false;
			}
			else {
				return true;
			}
		});
		
		$('form.choose-operator-validate').submit(function() {
			$(this.parentNode).find('.error-msg').remove();
			
			var isError = false;
			var msg = '<div class="error-msg">' +
							'<div>' +
								'<div class="inner">' +
									'<p class="msg">Wystąpiły błędy w formularzu</p>';
			
			if (!isPriceAmount($('#paymentAmount').attr('value'))) {
				msg += 			'<p>- Kwota musi być liczbą</p>';
				isError = true;
			}
			if (!isGroupChecked('pay_type')) {
				msg += 			'<p>- Proszę wybrać operatora</p>';
				isError = true;
			}
		
			msg += 				'</div>' +
							'</div>' +
						'</div>';
						
			if (isError) {
				$(this).before(msg);
				return false;
			}
			else {
				return true;
			}
		});
		
		$('form.validate').each(function() {
			$(this).submit(function() {
				$(this).find('div.validate > input').blur();
				if ($(this).find('.error').length > 0) {
					return false;
				}
				else return true;
			});
		});
	},
	
	colorTable: function() {
		$('table.color').each(function() {
			$(this).find('tbody tr').each(function(i) {
				if (i > 0 && i < 5) {
					$(this).addClass('op' + (100 - i * 10));
				}
				else if (i >= 5) {
					$(this).addClass('op50');
				}
			});
		})
	},
	
	startGallery: function(width, elements) {
		if ($('div.image-gallery').length) {
			$('div.image-gallery').each(function() {
				var gallery = $(this).find('ul.gallery:first');
				var title = $(this).find('.title').html();
				$(this).find('.title').remove();
				$(this).find('.inner-gallery:first').prepend('<div class="buttons"><a class="gallery-prev" href="">poprzednie</a><div class="title">' + title + '</div><a class="gallery-next" href="">następne</a></div>');
				$(this).find('.buttons > a.gallery-prev').click(function() {
					scrollBack($(gallery));
					return false;
				}).end()
				.find('.buttons > a.gallery-next').click(function() {
					scrollForward($(gallery));
					return false;
				});
			})
			function scrollForward(el) {
				var q = $(el).find('li').length;
				var max = -((q - q%elements) * width);
				var to = $(el).css('left').replace('px', '') - width*elements;
				if (to < max) to = max;
				move(el, to);
			}
			function scrollBack(el) {
				var max = 0;
				var to = $(el).css('left').replace('px', '') * 1 + width*elements;
				if (to > max) to = max;
				move(el, to);
			}
			function move(el, to) {
				var gallery = $('ul.gallery:first');
				$(gallery.parentNode).find('.buttons > a').unbind('click').click(function() {
					return false;
				});
				$(el).animate({left: to + 'px'}, 1000, function() {
					$(gallery.parentNode).find('.buttons > a.gallery-prev').click(function() {
						scrollBack($(gallery));
						return false;
					}).end()
					.find('.buttons > a.gallery-next').click(function() {
						scrollForward($(gallery));
						return false;
					});
				});
			}
			setupZoom();
		}
	},
	
	startServersChoice: function() {
		$('#promotion_code').attr('disabled', 'disabled');
		$('#game').bind('change', function() {
			var fields = this.parentNode;
			var fieldset = fields.parentNode.parentNode;
			$fields = $(fields);
			$selects = $fields.find('select');
			$selects.attr('disabled', 'disabled');
			$.ajax({
			    type: 'POST',
			    dataType: 'json',
			    url: 'zamowienie-ajax',
			    data: 'id=' + $(this).find('option:selected').attr('value'),
			    success: function(data) {
					if (!data.error) {
						$('#game').find('option:first').remove();
						$('#promotion_code').removeAttr('disabled');
						var priceData = data;
						$fields.find('#server_type').unbind('change');
						$fields.find('#slot_quantity').unbind('change');
						$fields.find('#duration').unbind('change');
						$fields.find('#teamspeak').unbind('change');
						$('#promotion_code').unbind('blur');
						$('#promotion_code').unbind('focus');
						$fields.find('#server_type').each(function() {
							$(this).find('option').remove();
							if (data.game.public) {
								$(this).append('<option value="public">Publiczny</option>')
							}
							if (data.game.private) {
								$(this).append('<option value="private">Prywatny</option>')
							}
							if (this.length > 1) {
								this[1].selected = "1";
							}
						});
						$fields.find('#slot_quantity').each(function() {
							$(this).find('option').remove();
							if (data.game.public && $(fields).find('#server_type option:selected').val() == 'public') {
								var min = parseInt(data.slots.public.min);
								var max = parseInt(data.slots.public.max);
							}
							else {
								var min = parseInt(data.slots.private.min);
								var max = parseInt(data.slots.private.max);
							}
							for (i = min; i <= max; i++) {
								if (i == min) {
									$(this).append('<option value="' + i + '">' + i + '</option>')
								}
								else {
									$(this).append('<option value="' + i + '">' + i + '</option>')
								}
							}
							this[0].selected = "1";
						});
						
						
						
						
						$fields.find('#server_type').bind('change', function() {
							updateSlotQuantityValues(fields, data);
							updatePrice(fieldset, $fields, data);
						});
						$fields.find('#duration').bind('change', function() {
							updatePrice(fieldset, $fields, data);
						});
						$fields.find('#slot_quantity').bind('change', function() {
							updatePrice(fieldset, $fields, data);
						});
						$selects.removeAttr('disabled');
						$fields.find('#teamspeak').bind('change', function() {
							updatePrice(fieldset, $fields, data);
						});
						
						$('#promotion_code').bind('blur', function() {
							var parent = document.getElementById('promotion_code').parentNode;
							$(parent).removeClass('ok');
							if ($(this).attr('value') != null) {
								promo = this;
								$.ajax({
								    type: 'POST',
								    dataType: 'json',
								    url: 'kod-promocyjny-ajax',
								    data: 'promotionCode=' + $(this).attr('value'),
								    success: function(data) {
										if (document.getElementById('discount-rate')) {
											$('#discount-rate').remove();
										}
										if (!data.errorCode) {
											$(parent).addClass('ok');
											$fields.append('<input id="discount-rate" type="hidden" value="' + data.discount + '" />');
											showOk(promo, data.discount);
										}
										else {
											$(parent).addClass('error');
											showError(promo, data.errorCode);
										}
									}
								});
							}
							else {
								if (document.getElementById('discount-rate')) {
									$('#discount-rate').remove();
								}
							}
							setTimeout(function() {
								updatePrice(fieldset, $fields, priceData);
							}, 1000);
						});
						
						$('#promotion_code').bind('focus', function() {
							var el = $(this.parentNode).find('.form-error').each(function() {
								$(this).remove();
							})
							/*
							if ($(el).hasClass('form-error') || $(el).hasClass('discount-ok')) {
								$(el).remove();
							}
							*/
						});
						
						function showError(el, msg) {
							var message = 	'<div class="form-error">' +
												'<p><span>Błąd</span> ' + msg + '</p>' +
											'</div>';
							$(el).after(message);
							$(el).next().fadeIn(1000);
						}
						function showOk(el, discount) {
							var message = 	'<span class="discount-ok">Obniżka o ' + discount + '%</span>';
							$(el).after(message);
							$(el).next().fadeIn(1000);
						}
						
						
						updateSlotQuantityValues(fields, data);
						updatePrice(fieldset, $fields, data);
						
						
						
						if (data.voice == 1){
							$fields.find('#teamspeak').attr('disabled', 'disabled');
							$fields.find('#teamspeak').each(function() {
								this[0].selected = "0";
							});
						}
					}
			    }
			});
		});
		
		
		function updateSlotQuantityValues(fields, data) {
			var slot_quantity = document.getElementById('slot_quantity');
			var $slot_quantity = $(slot_quantity);
			
			$slot_quantity.find('option').remove();
			if (data.game.public && $(fields).find('#server_type option:selected').val() == 'public') {
				var min = parseInt(data.slots.public.min);
				var max = parseInt(data.slots.public.max);
			}
			else {
				var min = parseInt(data.slots.private.min);
				var max = parseInt(data.slots.private.max);
			}
			for (i = min; i <= max; i++) {
				if (i == min) {
					$slot_quantity.append('<option value="' + i + '">' + i + '</option>')
				}
				else {
					$slot_quantity.append('<option value="' + i + '">' + i + '</option>')
				}
			}
			slot_quantity[0].selected = "1";
			
			var duration = $(fields).find('#duration');
			$(duration).find('option').remove();
			if (data.game.private && $(fields).find('#server_type option:selected').val() == 'private') {
				var l = data.game.private.length;
				for (i = 0; i < l; i++) {
					$(duration).append('<option value="'+ data.game.private[i].id + '">' + data.game.private[i].name + '</option>');
				}
			}
			else {
				var l = data.game.public.length;
				for (i = 0; i < l; i++) {
					$(duration).append('<option value="'+ data.game.public[i].id + '">' + data.game.public[i].name + '</option>');
				}
			}
			/*
			for (i = 0; i < l; i++) {
				if (data.game.public && $(fields).find('#server_type option:selected').val() == 'public') {
					$(duration).append('<option value="'+ data.game.public[i].id + '">' + data.game.public[i].name + '</option>');
				}
				else if (data.game.private && $(fields).find('#server_type option:selected').val() == 'private') {
					$(duration).append('<option value="'+ data.game.private[i].id + '">' + data.game.private[i].name + '</option>');
				}

			}
			*/
			document.getElementById('duration')[0].selected = "1";
		}
		function updatePrice(fieldset, $fields, data) {
			if ($fields.find('#server_type option:selected').val() == 'private') {
				var l = data.game.private.length;
				for (i = 0; i < l; i++) {
					if (data.game.private[i].id == parseInt($fields.find('#duration option:selected').val())) {
						var months = parseInt(data.game.private[i].month);
						var days = parseInt(data.game.private[i].days);
						var pricePerSlot = parseFloat(data.game.private[i].price);
					}
					var text = data.game.private[i].name + ' (' + parseFloat(data.game.private[i].price) + ' zł za slot)';
					$fields.find('#duration option:eq(' + i + ')').text(text);
					var slotQuantity = parseInt($fields.find('#slot_quantity option:selected').val());
					if( months != 0 ){
						var price =  pricePerSlot * months * slotQuantity;
					}
					else{
						var price =  pricePerSlot * slotQuantity;// * days/30;
						price = Math.round(price * 100) / 100;
					}
					if (parseInt($fields.find('#teamspeak option:selected').val()) != 0) {
						var addon = months;
						if (addon == 0) {
							addon = 1;
						}
						if ($fields.find('#server_type option:selected').val() == 'public') {
							addon *= 2;
						}
						price += addon * slotQuantity; 
					}
					if (document.getElementById('discount-rate')) {
						price *= (100 - parseFloat($('#discount-rate').attr('value'))) / 100;
					}
					price = Math.round(price * 100) / 100;
				}
			}
			else {
				var l = data.game.public.length;
				for (i = 0; i < l; i++) {
					if (data.game.public[i].id == parseInt($fields.find('#duration option:selected').val())) {
						var months = parseInt(data.game.public[i].month);
						var days = parseInt(data.game.public[i].days);
						var pricePerSlot = parseFloat(data.game.public[i].price);
					}
					
					var text = data.game.public[i].name + ' (' + parseFloat(data.game.public[i].price) + ' zł za slot)';
					$fields.find('#duration option:eq(' + i + ')').text(text);

					var slotQuantity = parseInt($fields.find('#slot_quantity option:selected').val());
					if( months != 0 ){
						var price =  pricePerSlot * months * slotQuantity;
					}
					else{
						var price =  pricePerSlot * slotQuantity;// * days/30;
						price = Math.round(price * 100) / 100;
					}
					if (parseInt($fields.find('#teamspeak option:selected').val()) != 0) {
						var addon = months;
						if (addon == 0) {
							addon = 1;
						}
						if ($fields.find('#server_type option:selected').val() == 'public') {
							addon *= 2;
						}
						price += addon * slotQuantity; 
					}
					if (document.getElementById('discount-rate')) {
						price *= (100 - parseFloat($('#discount-rate').attr('value'))) / 100;
					}
					price = Math.round(price * 100) / 100;
				}
			}
			/*
			for (i = 0; i < l; i++) {
				if ($fields.find('#server_type option:selected').val() == 'public') {
					if (data.game.public[i].id == parseInt($fields.find('#duration option:selected').val())) {
						var months = parseInt(data.game.public[i].month);
						var pricePerSlot = parseFloat(data.game.public[i].price);
					}
					var text = data.game.public[i].name + ' (' + parseInt(data.game.public[i].price) + ' zł za slot)';
					$fields.find('#duration option:eq(' + i + ')').text(text);
				}
				else if  {
					if (data.game.private[i].id == parseInt($fields.find('#duration option:selected').val())) {
						var months = parseInt(data.game.private[i].month);
						var pricePerSlot = parseFloat(data.game.private[i].price);
					}
					var text = data.game.private[i].name + ' (' + parseFloat(data.game.private[i].price) + ' zł za slot)';
					$fields.find('#duration option:eq(' + i + ')').text(text);
				}
				var slotQuantity = parseInt($fields.find('#slot_quantity option:selected').val());
				var price =  pricePerSlot * months * slotQuantity;
				if (parseInt($fields.find('#teamspeak option:selected').val()) != 0) {
					var addon = months;
					if ($fields.find('#server_type option:selected').val() == 'public') {
						addon *= 2;
					}
					price += addon * slotQuantity; 
				}
				if (document.getElementById('discount-rate')) {
					price *= (100 - parseFloat($('#discount-rate').attr('value'))) / 100;
				}
				price = Math.round(price * 100) / 100;
			}
			*/
			$(fieldset).find('.status .amount').text(price + ' zł');
		}
	},
	
	startMoreSlots: function() {
		$('#slot_quantity_buymore').bind('change', function() {
			var fieldset = this.parentNode;
			var urlParts = window.location.href.split('/');
			var serverId = urlParts[urlParts.length-1];
			$.ajax({
			    type: 'POST',
			    dataType: 'json',
			    url: '../cena-slot-ajax',
			    data: 'server_id='+ serverId +'&slot_quantity=' + $(this).find('option:selected').attr('value'),
			    success: function(data) {
					if (!data.error) {
						$('#promotion_code').removeAttr('disabled');
						$(fieldset).find('.status .amount').text(data.price + ' zł');
						var priceData = data;
						$('#promotion_code').bind('blur', function() {
							var parent = document.getElementById('promotion_code').parentNode;
							$(parent).removeClass('ok');
							if ($(this).attr('value') != null) {
								promo = this;
								$.ajax({
								    type: 'POST',
								    dataType: 'json',
								    url: '../kod-promocyjny-ajax',
								    data: 'promotionCode=' + $(this).attr('value'),
								    success: function(data) {
										if (document.getElementById('discount-rate')) {
											$('#discount-rate').remove();
										}
										if (!data.errorCode) {
											$(parent).addClass('ok');
											$(parent).append('<input id="discount-rate" type="hidden" value="' + data.discount + '" />');
											showOk(promo, data.discount);
										}
										else {
											$(parent).addClass('error');
											showError(promo, data.errorCode);
										}
									}
								});
							}
							else {
								if (document.getElementById('discount-rate')) {
									$('#discount-rate').remove();
								}
							}
							setTimeout(function() {
								var price = priceData.price;
								if (document.getElementById('discount-rate')) {
									price *= (100 - parseFloat($('#discount-rate').attr('value'))) / 100;
								}
								price = Math.round(price * 100) / 100;
								$(fieldset).find('.status .amount').text(price + ' zł');
							}, 1000);
						});
						$('#promotion_code').bind('focus', function() {
							var el = $(this).next();
							if ($(el).hasClass('form-error') || $(el).hasClass('discount-ok')) {
								$(el).remove();
							}
						});
						
						function showError(el, msg) {
							var message = 	'<div class="form-error">' +
												'<p><span>Błąd</span> ' + msg + '</p>' +
											'</div>';
							$(el).after(message);
							$(el).next().fadeIn(1000);
						}
						function showOk(el, discount) {
							var message = 	'<span class="discount-ok">Obniżka o ' + discount + '%</span>';
							$(el).after(message);
							$(el).next().fadeIn(1000);
						}
					}
			    }
			});
		});
	},
	
	startMoreMonths: function() {
		$('#slot_quantity_buymore_duration').bind('change', function() {
			var fieldset = this.parentNode;
			var urlParts = window.location.href.split('/');
			var serverId = urlParts[urlParts.length-1];
			var slot_quantity = $('#slot_quantity_buymore_duration').val();
			var duration = $('#duration_buymore').val();
			$.ajax({
			    type: 'POST',
			    dataType: 'json',
			    url: '../cena-server-ajax',
			    data: 'server_id='+ serverId +'&duration=' + duration + '&slot_quantity=' + slot_quantity,
			    success: function(data) {
					if (!data.error) {
						$('#promotion_code').removeAttr('disabled');
						$(fieldset).find('.status .amount').text(data.price + ' zł');
						var priceData = data;
						$('#promotion_code').bind('blur', function() {
							var parent = document.getElementById('promotion_code').parentNode;
							$(parent).removeClass('ok');
							if ($(this).attr('value') != null) {
								promo = this;
								$.ajax({
								    type: 'POST',
								    dataType: 'json',
								    url: '../kod-promocyjny-ajax',
								    data: 'promotionCode=' + $(this).attr('value'),
								    success: function(data) {
										if (document.getElementById('discount-rate')) {
											$('#discount-rate').remove();
										}
										if (!data.errorCode) {
											$(parent).addClass('ok');
											$(parent).append('<input id="discount-rate" type="hidden" value="' + data.discount + '" />');
											showOk(promo, data.discount);
										}
										else {
											$(parent).addClass('error');
											showError(promo, data.errorCode);
										}
									}
								});
							}
							else {
								if (document.getElementById('discount-rate')) {
									$('#discount-rate').remove();
								}
							}
							setTimeout(function() {
								var price = priceData.price;
								if (document.getElementById('discount-rate')) {
									price *= (100 - parseFloat($('#discount-rate').attr('value'))) / 100;
								}
								price = Math.round(price * 100) / 100;
								$(fieldset).find('.status .amount').text(price + ' zł');
							}, 1000);
						});
						$('#promotion_code').bind('focus', function() {
							var el = $(this).next();
							if ($(el).hasClass('form-error') || $(el).hasClass('discount-ok')) {
								$(el).remove();
							}
						});
						
						function showError(el, msg) {
							var message = 	'<div class="form-error">' +
												'<p><span>Błąd</span> ' + msg + '</p>' +
											'</div>';
							$(el).after(message);
							$(el).next().fadeIn(1000);
						}
						function showOk(el, discount) {
							var message = 	'<span class="discount-ok">Obniżka o ' + discount + '%</span>';
							$(el).after(message);
							$(el).next().fadeIn(1000);
						}
					}
			    }
			});
		});		
		
		$('#duration_buymore').bind('change', function() {
			var fieldset = this.parentNode;
			var urlParts = window.location.href.split('/');
			var serverId = urlParts[urlParts.length-1];
			var slot_quantity = $('#slot_quantity_buymore_duration').val();
			$.ajax({
			    type: 'POST',
			    dataType: 'json',
			    url: '../cena-server-ajax',
			    data: 'server_id='+ serverId +'&duration=' + $(this).find('option:selected').attr('value') + '&slot_quantity=' + slot_quantity,
			    success: function(data) {
					if (!data.error) {
						$('#promotion_code').removeAttr('disabled');
						$(fieldset).find('.status .amount').text(data.price + ' zł');
						var priceData = data;
						$('#promotion_code').bind('blur', function() {
							var parent = document.getElementById('promotion_code').parentNode;
							$(parent).removeClass('ok');
							if ($(this).attr('value') != null) {
								promo = this;
								$.ajax({
								    type: 'POST',
								    dataType: 'json',
								    url: '../kod-promocyjny-ajax',
								    data: 'promotionCode=' + $(this).attr('value'),
								    success: function(data) {
										if (document.getElementById('discount-rate')) {
											$('#discount-rate').remove();
										}
										if (!data.errorCode) {
											$(parent).addClass('ok');
											$(parent).append('<input id="discount-rate" type="hidden" value="' + data.discount + '" />');
											showOk(promo, data.discount);
										}
										else {
											$(parent).addClass('error');
											showError(promo, data.errorCode);
										}
									}
								});
							}
							else {
								if (document.getElementById('discount-rate')) {
									$('#discount-rate').remove();
								}
							}
							setTimeout(function() {
								var price = priceData.price;
								if (document.getElementById('discount-rate')) {
									price *= (100 - parseFloat($('#discount-rate').attr('value'))) / 100;
								}
								price = Math.round(price * 100) / 100;
								$(fieldset).find('.status .amount').text(price + ' zł');
							}, 1000);
						});
						$('#promotion_code').bind('focus', function() {
							var el = $(this).next();
							if ($(el).hasClass('form-error') || $(el).hasClass('discount-ok')) {
								$(el).remove();
							}
						});
						
						function showError(el, msg) {
							var message = 	'<div class="form-error">' +
												'<p><span>Błąd</span> ' + msg + '</p>' +
											'</div>';
							$(el).after(message);
							$(el).next().fadeIn(1000);
						}
						function showOk(el, discount) {
							var message = 	'<span class="discount-ok">Obniżka o ' + discount + '%</span>';
							$(el).after(message);
							$(el).next().fadeIn(1000);
						}
					}
			    }
			});
		});
	},
	
	initializePopups: function() {
		
		var top = screen.availHeight/2 - 300;
		var left = screen.availWidth/2 - 400;
		// $('#edit-config-file').submit(function() {
			// var urlParts = window.location.href.split('/');
			// var serverId = urlParts[urlParts.length-1];
			// var file = $(this).find('#configs option:selected').attr('value');
			// var options = 'scrollbars=0, status=0, width=800, height=600, top='+top+', left='+left;
			// window.open(window.location.href + '/edytuj-config/?cfg=' + file, 'edit_config', options);
			// return false;
		// });
		$('#edit-config-file').each(function() {
			var $this = $(this);
			var $butt = $this.find('a.button');
			$butt.unbind('click');
			$butt.click(function() {
				var urlParts = window.location.href.split('/');
				var serverId = urlParts[urlParts.length-1];
				var file = $this.find('#configs option:selected').attr('value');
				var options = 'scrollbars=0, status=0, width=800, height=600, top='+top+', left='+left;
				window.open(window.location.href + '/edytuj-config/?cfg=' + file, 'edit_config', options);
				return false;
			});
		});
		$('#rcon-console').bind('click', function() {
			var url = $(this).attr('href');
			var options = 'scrollbars=0, status=0, width=800, height=600, top='+top+', left='+left;
			window.open(url, 'rcon_console', options);
			return false;
		});
		$('#ftp-help').bind('click', function() {
			var url = $(this).attr('href');
			var options = 'scrollbars=0, status=0, width=800, height=600, top='+top+', left='+left;
			window.open(url, 'ftp_help', options);
			return false;
		});
		
	},
	
	serverReinstallWarning: function() {
		if (document.getElementById('reinstall')) {
			var info = $('#reinstall-info').text();
			var times_left = parseInt(document.getElementById('times-left').innerHTML);
			$('#reinstall').click(function() {
				if (times_left < 1) {
					alert('Wykorzystałeś już dzisiejszy limit reinstalacji!');
					return false;
				}
				else {
					return window.confirm('Czy na pewno chcesz dokonać reinstalacji?\nProces ten przywraca wszystkie pliki serwera do stanu początkowego.\n' + info);
				}
			});
			$('#reinstall-info').remove();
		}
	},
	
	serverStatsClipboard: function() {
		if (document.getElementById('frame')) {
			$('#frame').click(function() {
				select(this);
				return false;
			});
			$('#frame2').click(function() {
				select(this);
				return false;
			});
			$('#frame3').click(function() {
				select(this);
				return false;
			});
		}
		$('.banners .frame').click(function() {
			select(this);
			return false;
		});
		function select(el) {
			if (window.getSelection) { // FF, Safari, Opera
	   			var sel = window.getSelection();
	   			var range = document.createRange();
	   			range.selectNode(el);
	   			sel.removeAllRanges();
	   			sel.addRange(range);
	  		} else { // IE
	   			document.selection.empty();
	   			var range = document.body.createTextRange();
	   			range.moveToElementText(el);
	   			range.select();
	  		}
			if (window.clipboardData) {
				$('#frame').unbind('click');
				var text = el.innerHTML.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
				window.clipboardData.setData('Text', text);
				$(el).before('<div class="favoured"><div><p style="text-align: center;color: #fff;">Skopiowano do schowka</p></div></div>');
				setTimeout(function() {
					$(el).prev().fadeOut(2000, function() {
						$('#frame').click(function() {
							select(this);
						});
					});
				}, 1000);
			}
		}
	},
	
	startCountdown: function() {
		$('.countdown-msg').each(function() {
			var url = document.getElementById('goto').getAttribute('href');
			var left = parseInt(document.getElementById('wait').innerHTML);
			
			var msg = '<div class="extra">'+
						'<p><span id="time-left">' + left + '</span>s</p>' +
					'</div>';
			
			var title = $(this).find('p.msg').text();
			
			var text = '<p class="msg">' + title + '</p>' +
						'<p>Proszę o chwilę cierpliwości, za chwilę zostaniesz przekierowany na stronę serwera.</p>';
			
			$(this).find('.inner').append(msg);
			$(this).find('.message').html(text);
			
			timeLeft = document.getElementById('time-left');
			timeLeft.innerHTML = left;
			var countdownInterval = setInterval(function() {
				left--;
				if (left > 0) {
					timeLeft.innerHTML = left;
				}
				if (left == 0) {
					clearInterval(countdownInterval);
					window.location = url;
				}
				
			}, 1000);
		});
	},
	
	confirmations: function() {
		if (!($.browser.msie && /MSIE 6.0/.test(navigator.userAgent))) {
			$('a.confirm-payment').click(function(){
				var $tr = $(this.parentNode.parentNode);
				var game = $tr.find('.title:first').text().replace(/\n/g, '').replace(/\t/g, '');
				var amount = $tr.find('.amount:first').text().replace(/\n/g, '').replace(/\t/g, '');
				return window.confirm('Czy na pewno chcesz zapłacić ' + amount + '\nza: ' + game + '?');
			});
			
			$('#order a.del').click(function() {
				var game = $(this.parentNode.parentNode).find('.title:first').text().replace(/\n/g, '').replace(/\t/g, '');
				return window.confirm('Czy na pewno chcesz usunąć zamówienie:\n' + game + '?');
			});
			
			$('#my-servers ul li').each(function() {
				var $this = $(this);
				var server = $this.find('h3 a').text().replace('(więcej)', '');
				$this.find('a.stop').click(function() {
					return window.confirm('Czy na pewno chcesz zatrzymać serwer: ' + server + '?');
				});
				$this.find('a.restart').click(function() {
					return window.confirm('Czy na pewno chcesz zrestartować serwer: ' + server + '?');
				});
			});
			$('#stop-all-servers').click(function() {
				return window.confirm('Czy na pewno chcesz zatrzymać wszystkie zaznaczone serwery?');
			});
			$('#restart-all-servers').click(function() {
				return window.confirm('Czy na pewno chcesz zrestartować wszystkie zaznaczone serwery?');
			});
			$('#start-all-servers').click(function() {
				return window.confirm('Czy na pewno chcesz uruchomić wszystkie zaznaczone serwery?');
			});
		}
	},
	
	startCommandBoxes: function() {
		$('#command-options :checkbox').each(function() {
			var $command = $('#command');
			var $box = $(this);
			var $label = $(this.parentNode);
			
			
			if ($command.val().match(new RegExp('.*' + $label.text() + '.*'))) {
				console.log('on');
				$box.attr('checked', 'checked');
			}
			
			$box.click(function() {
				if (this.checked) {
					$command.val($command.val() + $label.text());
				}
				else {
					$command.val($command.val().replace($label.text(), ''));
				}
			});
		});
	},
	
	startToolTips: function() {
		
		// Promo code
		$('#promo-code-help').hide();
		
		if (document.getElementById('promotion_code')) {
			var $label = $(document.getElementById('promotion_code').parentNode).prev();
			
			var _for = $label.attr('for');
			var _text = $label.text();
			
			var html = '<div class="columns">' +
							'<label class="promo-lbl" for="' + _for + '">' + _text + '</label>' +
							'<a class="help" id="tooltip-promo-code" href="" rel="#promo-code-help">?</a>' +
						'</div>';
			
			$label.after(html);
			$label.remove();
		}
		$('#tooltip-promo-code').click(function() {
			return false;
		});
		
		$('#tooltip-promo-code').cluetip({
			local:true,
			cursor: 'pointer',
			width: 550,
			positionBy: 'fixed', 
			showTitle: false, 
			sticky: false, 
			dropShadow: false, 
			arrows: true,
			cluezIndex: 200,
			topOffset: 2,
			fx: {             
				  open:       'fadeIn',
				  openSpeed:  '500'
			}
		});
		// Promo code.end
		
		
		// Amx help
		if (document.getElementById('amx-help')) {
			var $amx_help = $('#amx-help');
			$amx_help.hide();
			
			$btn = $amx_help.prev();
			$btn.addClass('columns');
			$btn.find('a.button').css({float: 'left', marginRight: '5px'});
			
			var html = '<a class="help" id="amx-help-l" href="#" rel="#amx-help">?</a>';
			
			$btn.find('a:first').after(html);
			
			if ($.browser.opera) {
				$btn.find('a:last').css('padding-top', '15px');
			}
		}
		$('#amx-help-l').click(function() {
			return false;
		});
		
		$('#amx-help-l').cluetip({
			local:true,
			cursor: 'pointer',
			width: 550,
			positionBy: 'fixed', 
			showTitle: false, 
			sticky: false, 
			dropShadow: false, 
			arrows: true,
			cluezIndex: 200,
			topOffset: 6,
			fx: {             
				  open:       'fadeIn',
				  openSpeed:  '500'
			}
		});
		// Amx help.end
		
		// Amx configuration help
		if (document.getElementById('amx-configuration')) {
			var $amx_help = $('#amx-configuration-help');
			$amx_help.hide();
			
			$btn = $amx_help.prev().prev();
			
			var html = '<a class="help" id="amx-configuration-help-l" href="#" rel="#amx-configuration-help">?</a>';
			
			$btn.find('a:last').after(html);
			
			if ($.browser.opera) {
				$btn.find('a:last').css('padding-top', '15px');
			}
		}
		$('#amx-configuration-help-l').click(function() {
			return false;
		});
		
		$('#amx-configuration-help-l').cluetip({
			local:true,
			cursor: 'pointer',
			width: 550,
			positionBy: 'fixed', 
			showTitle: false, 
			sticky: false, 
			dropShadow: false, 
			arrows: true,
			cluezIndex: 200,
			topOffset: 6,
			fx: {             
				  open:       'fadeIn',
				  openSpeed:  '500'
			}
		});
		// Amx configuration help.end
		
		// Sms discount
		$('#order .sms-discount').each(function() {
			var classes = this.className;
			var text = this.innerHTML;
			
			$(this).after('<a class="' + classes + '" title="' + text + '" href="">' + text + '</a>');
			var $label = $(this).next();
			$(this).remove();
			$label.click(function() {
				return false;
			});
			$label.cluetip({
				cursor: 'pointer',
				positionBy: 'fixed', 
				showTitle: false, 
				sticky: false, 
				dropShadow: false, 
				arrows: true,
				cluezIndex: 200,
				topOffset: 2,
				fx: {             
					  open:       'fadeIn',
					  openSpeed:  '500'
				}
			});
			
		});
		
		$('#password-help').hide();
		
		if (document.getElementById('password-register')) {
			var $label = $(document.getElementById('password-register').parentNode).prev();
			
			var _for = $label.attr('for');
			var _text = $label.text();
			
			var html = '<div class="columns">' +
							'<label class="promo-lbl" for="' + _for + '">' + _text + '</label>' +
							'<a class="help" id="tooltip-promo-code" href="" rel="#password-help">?</a>' +
						'</div>';
			
			$label.after(html);
			$label.remove();
		}
		$('#tooltip-promo-code').click(function() {
			return false;
		});
		
		$('#tooltip-promo-code').cluetip({
			local:true,
			cursor: 'pointer',
			width: 550,
			positionBy: 'fixed', 
			showTitle: false, 
			sticky: false, 
			dropShadow: false, 
			arrows: true,
			cluezIndex: 200,
			topOffset: 2,
			fx: {             
				  open:       'fadeIn',
				  openSpeed:  '500'
			}
		});
		
	},
	
	startMyServers: function() {
		$('#my-servers ul:first').each(function() {
			$this = $(this);
			$this.before('<div class="btn"><a id="ms-check-all" class="button">Zaznacz wszystkie</a></div>');
			$('#ms-check-all').toggle(function() {
				$this.find(':checkbox').attr('checked', 'checked');
				$(this).find('.inner').text('Odznacz wszystkie');
			}, function() {
				$this.find(':checkbox').attr('checked', '');
				$(this).find('.inner').text('Zaznacz wszystkie');
			});
		});
	},
	
	mailFix: function() {
		$('a.mail-fix').each(function() {
			$this = $(this);
			var name = $this.find('.nazwa').text();
			var domain1 = $this.find('.domena1').text();
			var domain2 = $this.find('.domena2').text();
			$this.attr('href', 'mailto:' + name + '@' + domain1 + '.' + domain2);
			$this.text(name + '@' + domain1 + '.' + domain2);
		});
	},
	
	startAmxConf: function() {
		if (document.getElementById('amx-conf')) {
			var $amx = $('#amx-conf');
			var $lis = $amx.find('li');
			
			$('#new-amx-user').removeClass('conf-li').hide();
			
			var add_new = '<div class="btn"><a class="button" id="amx-add">Nowy użytkownik</a></div>';
			var select = '<label for="">Wybierz użytkownika</label><select id="amx-select"><option value="0">Wybierz użytkownika</option>';
		
			$lis.not('#new-amx-user').each(function(i) {
				var $this = $(this);
				$this.hide();
				$this.removeClass('conf-li');
				$this.attr('id', 'amx_user_' + (i + 1));
				var nick = $this.find('.nick').val();
				
				select += '<option value="' + (i + 1) + '">' + nick + '</option>';
				
			});
			
			select += '</select>';
			$amx.before(add_new);
			$amx.before(select);
			$('#amx-select').change(function() {
				var index = $(this).find('option:selected').attr('value');
				if (index != 0) {
					$lis.hide();
					$('#amx_user_' + index).show();
				}
			});
			
			$('#amx-add').click(function() {
				$lis.hide();
				document.getElementById('amx-select')[0].selected= "1";
				$('#new-amx-user').show();
			});
		}
	}
}

$(function() {
	Shooters.start();
});