$(document).ready(function() {
	$('.colorbox').colorbox();
	
	$('.rating').rating({
		callback: function(value, link) {
			var video_id = $(this).attr('name').split('-');
			video_id = video_id[1];
			
			$('input[name=' + $(this).attr('name') +']').rating('disable');
			
			$.ajax({
				type: 'post',
				url: 'ajax.php',
				dataType: 'json',
				data: {
					action: 'rating',
					value: value,
					video_id: video_id
				},
				success: function(data, textStatus) {
					$('#tooltips').html(data.message);

					$.fn.colorbox({
						inline: true,
						href: '#tooltips',
						open: true
					});
				}
			});
		}
	});
	
	checkLogin();
});

function checkLogin() {
	$.ajax({
		type: 'post',
		url: 'ajax.php',
		dataType: 'json',
		data: {
			action: 'check_login'
		},
		success: function(data, textStatus) {
			if (data.safe == 1) {
				$('.rating').rating('enable');
			} else {
				$('.rating').rating('disable');
			}
		}
	});
}

function registred() {
	$.ajax({
		type: 'post',
		url: 'ajax.php',
		dataType: 'json',
		data: {
			action: 'registred',
			email: $('#registred_email').val(),
			password: $('#registred_password').val(),
			password_2: $('#registred_password_2').val(),
			pseudo: $('#pseudo').val()
		},
		success: function(data, textStatus) {
			if (data.safe == 1) {
				$('#tooltips').html(data.message);

				$.fn.colorbox({
					inline: true,
					href: '#tooltips',
					open: true
				});
				
				$('.rating').rating('enable');
				
				$('.header-text').html('Bonjour, <a href="#1" onclick="logout();">cliquez-ici</a> pour vous d&eacute;connecter');
			} else {
				alert(data.message);
			}
		}
	});
}

function login() {
	$.ajax({
		type: 'post',
		url: 'ajax.php',
		dataType: 'json',
		data: {
			action: 'login',
			email: $('#login_email').val(),
			password: $('#login_password').val()
		},
		success: function(data, textStatus) {			
			if (data.safe == 1) {
				$('#tooltips').html(data.message);

				$.fn.colorbox({
					inline: true,
					href: '#tooltips',
					open: true
				});
				
				$('.rating').rating('enable');
				
				$('.header-text').html('Bonjour, <a href="#1" onclick="logout();">cliquez-ici</a> pour vous d&eacute;connecter');
				
				$().bind('cbox_close', function() {
					window.location = window.location;	
				});
			} else {
				alert(data.message);
			}
		}
	});
}

function logout() {
	$.ajax({
		type: 'post',
		url: 'ajax.php',
		dataType: 'json',
		data: {
			action: 'logout'
		},
		success: function(data, textStatus) {			
			$('#tooltips').html(data.message);

			$.fn.colorbox({
				inline: true,
				href: '#tooltips',
				open: true
			});
			
			$('.rating').rating('disable');
			
			$('.header-text').html('Bonjour, <a href="registred.php" class="colorbox">identifiez-vous</a> pour voter pour votre Bande-annonce pr&eacute;f&eacute;r&eacute;e');
			
			$('.colorbox').colorbox();
		}
	});
}
