/* WALIDACJA */

var errorLogin1 = 'Niepoprawne znaki w polu login.';
var errorLogin2 = 'Podany login jest już zajęty.';
var errorLogin3 = 'Login musi składać się z conajmniej 4 znaków.';
var errorPassword1 = 'Niepoprawne znaki w polu hasło.';
var errorPassword2 = 'Hasło musi składać się z conajmniej 6 znaków.';
var errorPassword3 = 'Hasła muszą być takie same.';
var errorEmail1 = 'Niepoprawne znaki w polu email.';
var errorEmail2 = 'Podany email istnieje już w bazie. <a href="/logowanie.html?r=1">Zaloguj</a>.';
var errorLogowanie1 = 'Login lub hasło są błędne.';
var errorAkcept = 'Należy zaakceptować regulamin.';
var error = null;

$(function(){

	emailOk = false;
	loginOk = false;

    $('input[name="login"]').blur(function(){
		sprawdzLogin();
    });

    $('input[name="email"]').blur(function(){
		sprawdzEmail();
    });

    $('input[name="emailPrzypomnij"]').blur(function(){
		sprawdzEmail2();
    });

    $('input[name="password"]').blur(function(){
		sprawdzHaslo();
    });

    $('input[name="password2"]').blur(function(){
		sprawdzHaslo2();
    });

    $('input[name="teraz-w-kinach"]').click(function(){
		if($(this).attr('checked')){
			$('.sortowanie_wg').val('d');
			$('#kierunek-sortowania_m').click();
			$('input[name="wkrótce-w-kinach"]').attr('checked', '');
		}
    });

    $('input[name="wkrótce-w-kinach"]').click(function(){
		if($(this).attr('checked')){
			$('.sortowanie_wg').val('d');
			$('#kierunek-sortowania_r').click();
			$('input[name="teraz-w-kinach"]').attr('checked', '');
		}
    });


	$("#przypomnijForm").submit(function(){
		if(!sprawdzEmail2())
			return false;
		else
			return true;
	});

	$('input[name="formUstawNick"]').click(function(){
		if(!loginOk)
			sprawdzLoginFb();

	})

	$("#ustawNick").submit(function(){
		if(!loginOk)
				return false;
			else
				return true;
	});

	$("#kontaktFormularz").submit(function(){
		$('#kontaktLoginError').html('');
		$('#kontaktMessageError').html('');
		$('#kontaktTematError').html('');
		$('#usernameError').html('');
		
		if(document.getElementById("username")){
			var wynik_dodawania = $('input[name="username"]').val();
			
			if(wynik_dodawania.length == 0){
				$('#usernameError').html('<div class="alert2"><img alt="" src="gfx/alert.png">Wpisz wynik dodawania.</div>');
				return false;
			}
			
			if(wynik_dodawania.match(/^[2-9]$/) == null ){
				$('#usernameError').html('<div class="alert2"><img alt="" src="gfx/alert.png">Źle :)</div>');
				return false;
			}
		}
		
		if(document.getElementById("loginKontakt")){
			var login = $('input[name="login"]').val();
		if(login.length == 0){
			$('#kontaktLoginError').html('<div class="alert2"><img alt="" src="gfx/alert.png">Podaj adres e-mail. Jest to niezbędne żebyśmy mogli odpowiedzieć na wiadomość.</div>');
			return false;
		}
		if(login.match('^[\\w\\.\\-]+@[\\w]+.[a-z A-Z]{2,6}') == null ){
				$('#kontaktLoginError').html('<div class="alert2"><img alt="" src="gfx/alert.png">Nieprawidłowy adres email.</div>');
				return false;
			}
		}

		if($('select[name="tematKontakt"]').val() == ''){
			$('#kontaktTematError').html('<div class="alert2"><img alt="" src="gfx/alert.png">Proszę wybrać temat wiadomości.</div>');
			return false;
		}

		var message = $('textarea[name="message"]').val();

			if(message.length == 0){
				$('#kontaktMessageError').html('<div class="alert2"><img alt="" src="gfx/alert.png">Podaj treść wiadomości.</div>');
				return false;
			}

		return true
	});

    $("#rejestracjaForm").submit(function(){
		wyczysc();
		$('#emailError').html('<p id="oddany_glos_loader"><img src="/gfx/loader.gif" alt=""></p>');
		$('#loginError').html('<p id="oddany_glos_loader"><img src="/gfx/loader.gif" alt=""></p>');
		if(!emailOk)
			sprawdzEmail();
		else
			$('#emailError').html('');
		if(!loginOk)
			sprawdzLogin();
		else
			$('#loginError').html('');

		if(!emailOk || !loginOk || !sprawdzHaslo() || !sprawdzHaslo2() || !akceptacjaRegulamin() )
				return false;
			else
				return true;
    });

function akceptacjaRegulamin(){
	if ( $('input[name="akcept"]').is(':checked') ){
		return true;
	}else{
		$('#akceptError').html(errorAkcept);
		return false;
	}
}

    $("#zmianaHasla").submit(function(){
		if(!sprawdzStareHaslo() || !sprawdzHaslo() || !sprawdzHaslo2())
				return false;
			else
				return true;
	});


    $("#logowanieForm").submit(function(){

	error = false;
	var login = $('input[name="loginLogowanie"]').val();
	var pass = $('input[name="passwordLogowanie"]').val();
	if(login.length < 4){
		$('#logowanieError2').html('<div class="alert2"><img alt="" src="/gfx/alert.png">'+errorLogowanie1+'</div>');
		error = true;
	}else if(login.match('^[\\w\\d\\_\\.@]{4,}$') == null ){
		$('#logowanieError2').html('<div class="alert2"><img alt="" src="/gfx/alert.png">'+errorLogowanie1+'</div>');
		error = true;
	}
	else if(pass.match('^[\\w\\d]{5,}$') == null ){
		$('#logowanieError2').html('<div class="alert2"><img alt="" src="/gfx/alert.png">'+errorLogowanie1+'</div>');
		error = true;
	}

	if(error)
		return false;
	else
		return true;
    });

    $('input[name="recenzjaTytul"]').blur(function(){
		sprawdzTekst('recenzjaTytul', true);
    });

    $('textarea[name="recenzjaTekst"]').blur(function(){
		//sprawdzTekst('recenzjaTekst', false);
    });

	$("#nowaRecenzja").submit(function(){
		if(!sprawdzTekst('recenzjaTytul', true) || !sprawdzTekst('recenzjaTekst', false))
			return false;
	});

	$("#nowaFabula").submit(function(){
		if(!sprawdzTekst('recenzjaTekst', false))
			return false;
	});

});


function sprawdzTekst(pole, input){
	if(input)
		poleVal = $('input[name="'+pole+'"]').val();
	else
		poleVal = $('textarea[name="'+pole+'"]').val();

	poleVal = jQuery.trim(poleVal);

	$('#'+pole+'Error').html('');
	if(poleVal.length < 1){
		$('#'+pole+'Error').html('<div class="alert2"><img alt="" src="/gfx/alert.png">Wpisany tekst jest za krótki</div>');
		return false;
	}
	return true;
}

function sprawdzEmail2(){
	var email = $('input[name="emailPrzypomnij"]').val();

	if(email.match('^[\\w\\.\\-]+@[\\w]+.[a-z A-Z]{2,6}') == null ){
		$('#emailError').html('<div class="alert2"><img alt="" src="gfx/alert.png">'+errorEmail1+'</div>');
		return false;
	}
	return true;
}

function sprawdzStareHaslo(){
	var pass = $('input[name="oldPassword"]').val();

	var ret = false

		if(pass.length < 6){
			$('#oldPasswordError').html(errorPassword2);
			ret = false;
		}else if(pass.match('^[\\w\\d]{6,}$') == null ){
			$('#oldPasswordError').html(errorPassword1);
			ret = false;
		}else{
			$('#oldPasswordError').html('');
			ret = true;
		}
	return ret;
}


function sprawdzHaslo2(){
	var pass = $('input[name="password2"]').val();
	var pass2 = $('input[name="password"]').val();

	if(pass2.length > 1){
		if(pass2 != pass){
			$('#passwordError2').html(errorPassword3);
		}else{
			return true;
		}
	}
	return false;
}

function sprawdzHaslo(){
	var pass = $('input[name="password"]').val();
	var pass2 = $('input[name="password2"]').val();
	var ret = false;

	if(pass2.length > 1 && pass2 != pass){
		$('#passwordError2').html(errorPassword3);
	}else{
		if(pass.length < 6){
			$('#passwordError').html(errorPassword2);
		}else if(pass.match('^[\\w\\d]{6,}$') == null ){
			$('#passwordError').html(errorPassword1);
		}else{
			$('#passwordError').html('');
			ret = true;
		}
	}

	return ret;
}

function sprawdzLogin(){
	var login = $('input[name="login"]').val();

	if(login.length < 4){
		$('#loginError').html(errorLogin3);
		error = true;
		loginOk = false;
	}else if(login.match('^[\\w\\d\\_\\.]{4,}$') == null ){
		$('#loginError').html(errorLogin1);
		error = true;
		loginOk = false;
	}else{
	$(function(){
		$.ajax({
			url: '/rejestracja/checkLogin',
			dataType: 'json',
			type: 'POST',
			data: {
				login: $('input[name="login"]').val()
			},
			success: function(response){
				if(!response.isAvailable){
					$('#loginError').html(errorLogin2);
					loginOk = false;
					error = true;
				}
				else{
					$('#loginError').html('');
					loginOk = true;
			}},

			error: function (XMLHttpRequest, textStatus, errorThrown) {
				//alert(textStatus);
			}
		});
	});
	}
	return error;
}

function sprawdzLoginFb(){
	var login = $('input[name="loginFb"]').val();

	if(login.length < 4){
		$('#loginError').html(errorLogin3);
		error = true;
		loginOk = false;
	}else if(login.match('^[\\w\\d\\_\\.]{4,}$') == null ){
		$('#loginError').html(errorLogin1);
		error = true;
		loginOk = false;
	}else{
		$(function(){
			$.ajax({
				url: '/rejestracja/checkLogin',
				dataType: 'json',
				type: 'POST',
				data: {
					login: $('input[name="loginFb"]').val()
				},
				success: function(response){
					if(!response.isAvailable){
						$('#loginError').html(errorLogin2);
						loginOk = false;
						error = true;
					}
					else{
						loginOk = true;
						wyslij();
					}},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					//alert(textStatus);
				}
			});
		});
	}
	return error;
}

function sprawdzEmail(){
	login = $('input[name="email"]').val();

	if(login.match('^[\\w\\.\\-]+@[\\w]+.[a-z A-Z]{2,6}') == null){
		$('#emailError').html(errorEmail1);
		emailOk = false;
	}else{
	$(function(){
		$.ajax({
			url: '/rejestracja/checkEmail',
			dataType: 'json',
			type: 'POST',
			data: {
				email: $('input[name="email"]').val()
			},
			success: function(response){
				if(!response.isAvailable){
					$('#emailError').html(errorEmail2);
					emailOk = false;
					return false;
				}
				else{
					emailOk = true;
					$('#emailError').html('');
					return true;
				}
			},

			error: function (XMLHttpRequest, textStatus, errorThrown) {
				//alert(textStatus);
				//return false;
			}
		});
	});
	}

}

function wyczysc(){
	$('#emailError').html('');
	$('#loginError').html('');
	$('#passwordError').html('');
	$('#passwordError2').html('');
	$('#akceptError').html('');
}

function wyslij(){
	$('#ustawNick').submit();
}

/* FILMS */

function showRating(i,change){
	var newMarginTop = "-="+i+"px";
	var newHeight = "+="+i+"px";

    if(change){
		var height = $(".oscar_wypelniacz").css('height');
		height = height.substr(0,height.length-2);
		inew = i - height;
		if(inew < 0){
			inew =  height - i;
			newMarginTop = "+="+inew+"px";
			newHeight = "-="+inew+"px";
		}else{
			newMarginTop = "-="+inew+"px";
			newHeight = "+="+inew+"px";
		}
	}

	$(".oscar_wypelniacz").animate({
		marginTop: newMarginTop,
		height: newHeight
	},{queue:false, duration:800});

	return false;
}


$(function(){
	$(".vote_a").click(function(){

	var id = $(".zaglosuj").attr("id").substr(3);
	var rating_ =$(this).attr("href");
	var type = $("#vote-target-type").attr("content");
		$(".zaglosuj").html('<p id="oddany_glos_loader"><img src="/gfx/loader.gif" alt=""></p>');
		$.ajax({
			url: '/'+type+'/vote',
			dataType: 'json',
			type: 'POST',
			data: {
				id: parseInt(id),
				rating: rating_
			},
			success: function(response){
				$(".zaglosuj").html('<p id="oddany_glos">'+response['vote']['glos']+'</p>');
				$("#ocena").html(response['vote']['rating']);
				$("#count").html(response['vote']['count']);
				showRating(response['vote']['oscar'], true);
			},

			error: function (XMLHttpRequest, textStatus, errorThrown) {
				//alert(textStatus);
				return false;
			}
		});

	return false;
	});

	//alert(document.location.hash);


});


/* KOMMENT */

$(document).ready(function(){
	var working = false;
	var type = $('.comment_type').attr('id');

	$('.form').submit(function(e){
		$('.loginError').html('');
		$('.textError').html('');

		if(document.getElementById("loginComment")){
			var login = $(this).children(".komBlock").children(".loginComment").val();

			login = jQuery.trim(login);
			if(login == ''){
				$('.loginError').html('Uzupełnij login');
				return false;
			}else{
				if(login.match('^[\\w\\d\\_\\.@ęóąśłżźćńĘÓĄŚŁŻŹĆŃ]{1,}$') == null ){
					$('.loginError').html('Niedozwolone znaki w loginie');
					return false;
				}
			}
		}

		var text = $(this).children(".komBlock").children(".textComment").val();
		text = jQuery.trim(text);
		if(text.length == 0){
			$('.textError').html('Uzupełnij treść komentarza');
			return false;
		}

		if(text.length > 32768){
			$('.textError').html('Komentarz jest zbyt długi');
			return false;
		}

 		e.preventDefault();
		if(working) return false;

		working = true;
		$('#submit').val('Zapisuję..');
		$('span.error').remove();


		$.post('/komentarz/dodaj',$(this).serialize(),function(msg){

			working = false;
			$('#submit').val('Dodaj »');
			if(msg.isOk){
				$(msg.html).hide().insertAfter('#add_kom').slideDown();
				$('.textComment').val('');
			}
			else {
				$('.formError').html('Wystąpił bład podczas dodawania komentarza. Odśwież stronę i spróbuj ponownie.');
			}
		},'json');
	});

	$(".odp").live('click', function(){
		$('.add_kom_odp').slideUp();
		var id = $(this).attr("href");
		var idElement = $('.movie_id').attr('id').substr(5);

		$.ajax({
			url: '/komentarz/odpowiedzForm',
			dataType: 'json',
			type: 'POST',
			data: {
				idComment: id,
				idElement: idElement,
				type: $('#type').val()
			},
			success: function(response){
				$(response['html']).hide().insertAfter('#kom_id_'+id).slideDown();
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				//alert(errorThrown);
				return false;
			}
		});

		return false;
	});

    $(".formOdp").live('submit', function(e){

		if(document.getElementById("loginCommentOdp")){
			var login = $(this).children(".komBlock").children(".loginComment").val();
			login = jQuery.trim(login);
			$('.loginOdpError').html('');
			if(login == ''){
				$('.loginOdpError').html('Uzupełnij login');
				return false;
			}else{
				if(login.match('^[\\w\\d\\_\\.@ęóąśłżźćńĘÓĄŚŁŻŹĆŃ]{1,}$') == null ){
					$('.loginOdpError').html('Niedozwolone znaki w loginie');
					return false;
				}
			}
		}
		var text = $(this).children(".komBlock").children(".textComment").val();
		text = jQuery.trim(text);
		if(text.length == 0){
			$('.textOdpError').html('Uzupełnij treść komentarza');
			return false;
		}

		if(text.length > 32768){
			$('.textError').html('Komentarz jest zbyt długi');
			return false;
		}

		$('.add_kom_odp').slideUp();
		var id_parent = $(this).children(".komBlock").children(".komentarz_odp_submit").attr('id').substr(7);

 		e.preventDefault();
		if(working) return false;


		working = true;
		$('#submit').val('Zapisuję..');
		$('span.error').remove();

		$.post('/komentarz/dodaj',$(this).serialize(),function(msg){

			working = false;
			$('#submit').val('Dodaj »');
			if(msg.isOk){
				$(msg.html).hide().insertAfter('#kom_id_'+id_parent).slideDown();
				$('.textComment').val('');
			}
			else {
				$('.formOdpError').html('Wystąpił bład podczas dodawania komentarza. Odśwież stronę i spróbuj ponownie.');
			}
		},'json');
		return false;
	});

});


