$(function() {
	$("#form-login").validate({
		rules: {
			entered_login: {
				required: true,
				email: true
			},
			entered_password: "required"
		},
		submitHandler: function(form) {
			var dataString = $(form).serialize();
			$.ajax({
				type: "POST",
				url: "secure-login.php",
				data: dataString,
				success: function(html) {
					$("#div-login").fadeOut("slow", function () {
						if( html=='KO') {
							$.ajax({
								type: "GET",
								url: "includes//page.top.KO.inc.php",
								success: function(html) {
									$("#div-user").html(html);
									$("#logout").bind("click", handler);
									$("#div-user").fadeIn("slow");
								},
								error: function(html){
								}
							});
						} else {
							$.ajax({
								type: "GET",
								url: "includes//page.top.user.inc.php",
								data: "loggedFromAjax=1",
								success: function(html) {
									if (html != "")
									{
										$("#div-user").html(html);
										$("#logout").bind("click", handler);
										$("#div-user").fadeIn("slow");
										$("#div-panier").fadeIn("slow");
									}
									else
									{
										$.ajax({
											type: "GET",
											url: "includes//page.top.KO.inc.php",
											success: function(html) {
												$("#div-user").html(html);
												$("#logout").bind("click", handler);
												$("#div-user").fadeIn("slow");
											},
											error: function(html){
											}
										});
									}
                  window.location.reload();
								},
								error: function(html){
								}
							});
						}
					});
				},
				error: function(html){
				}
			});

			return false;
		}
	});
	
  $("#login").bind("click", function(event) {
    $("#div-login-KO").hide("slow");
    $("#div-login").fadeIn("slow");
  });
	
	function handler(event) {
		$.ajax({
			type: "POST",
			url: "secure-login.php",
			data: "mode=logout",
			success: function(html) {
				$("#div-user").fadeOut("slow", function () {
					$("#div-login").fadeIn("slow");
          window.location.reload();
				});
			},
			error: function(html){
			}
		});
	}

	$("#logout").bind("click", handler);
});
