// Preload Images
img1 = new Image(16, 16);  
img1.src="Scripts/modal_login/images/spinner.gif";

img2 = new Image(220, 19);  
img2.src="Scripts/user_registration/img/ajax-loader.gif";

// When DOM is ready
$(document).ready(function(){		
	
	//disabe onEnter
	/*$("#form-login").bind("keypress", function(e) {
		 if (e.keyCode == 13) {
			e.preventDefault(); 			
			return false;
			
		}
	});*/
	
	// When the form is submitted
	$("#form-envio-pass").submit(function(e){ 					
		e.preventDefault(); 
		
		//Realizo toda la validacion y mando 
		validate_email_remember();
				
	}); // end submit event
	
	
	// When the form is submitted
	$("#form-login").submit(function(e){ 		
			
		e.preventDefault(); 

		if(!validate_login()){
			return false;	
		};
			
		
		hideshow('loading',0);		
	
		// 'this' refers to the current submitted form  
		var str = $(this).serialize(); 
		
		// -- Start AJAX Call --		
		$.ajax({  
			type: "POST",
			url: "Scripts/modal_login/do-login.php",  // Send the login info to this page
			data: str, 
			success: function(msg){
				
					// Hide Gif Spinning Rotator							
					//hideshow('loading');
					
					//jdata = $.toJSON(msg);					
					jdata = $.json.deserialize(msg)
									
					if(jdata.status == 'OK'){  
						
						user_email = jdata.user_email;
						user_name = jdata.user_name;
						
						go_to_private_page(user_email, user_name,true); 
					}  
					else{ 
					
						error(1,"Los datos ingresados son incorrectos.");					
						
					}; 	  
			 
		   
			}  
		   
		});  		  
		// -- End AJAX Call --		
		return false;		
	}); // end submit event
		
	
	//Email Validation
	$("#password").change(function(){									 
		
		//Si es usuario nuevo no valido nada
		if($("#is_new_user").val() == '1')
			return;
	
		$.ajax({  
			type: "POST",
			url: "Scripts/modal_login/do-login.php",  // Send the login info to this page
			data: "user_email="+$("#user_email").val()+"&action=user_login&password="+$("#password").val(),  
			success: function(msg){  	  
				
					jdata = $.json.deserialize(msg)
									
					if(jdata.status == 'OK'){  
						
						user_email = jdata.user_email;
						user_name = jdata.user_name;						
						
						go_to_private_page(user_email, user_name, false);
						
					}
					else
					{
						$('#login_result').html("<DIV styel='color:#FF0000'><strong>Los datos ingresados son incorrectos.</strong></DIV>");
						$("#pass_validation_img").html("<img src='images/ko_icon.png' />");
						
					}								
			}		
			
		});
		
	});
	
	$("#acepta_usuario").click(function(){
		if($("#acepta_usuario:checked").val()){
			$("#is_new_user").val('1');
			$("tr.asociados").css({'display':'none'});
		}else{
			$("#row_email_validation, #row_password, #row_apellido").hide();
		}
		
	});

	//Email Validation
	$("#user_email").blur(function(){	
		
		$("tr.asociados").css({'display':'none'});
		$('#login_result').html("");
		
		// 'this' refers to the current submitted form  
		var str = $(this).serialize(); 

		$.ajax({
			type: "POST",
			url: "Scripts/modal_login/do-email.php",  // Send the login info to this page
			data: 'action=email_validation&email=' + this.value,  
			success: function(msg){

				if(msg == 'OK') {
					//Muestro confirmacion solo el pass 
					$("#is_new_user").val('0');
					$("#email_validation_img").html("<img src='images/ok_icon.png' />");
					$('#row_email_validation').hide();
					$('#row_password').hide();
					//$("#password").focus();			
					
					//busco las personas asociadas a este usuario, si tiene
					$.post('includes/get_asociadas.inc.php',{email:$("#user_email").val()},function(data){
						if(data!=''){
							$("tr.asociados").css({'display':'block'});
							$(".selects_asociados").html(data);
						}else{
							$("tr.asociados").css({'display':'none'});
						}
						
						$(".limpiar_form").click(function(){
							
							$(".bt_siguiente").show();
							
							var cual_select = $(this).attr('id');
							var letra_y_numero_select = cual_select.split('_');
							var letra = letra_y_numero_select[0];
							
							var numero = letra_y_numero_select[2];

							$("#"+letra+"_persona_"+numero).val('');
							$("#"+letra+"_user_"+numero).val('');
							$("#"+letra+"_nombre_"+numero).val('');
							$("#"+letra+"_sexo_"+numero).val('');
							$("#"+letra+"_dia_"+numero).val('');
							$("#"+letra+"_mes_"+numero).val('');
							$("#"+letra+"_ano_"+numero).val('');
							$("#"+letra+"_hora_"+numero).val('');
							$("#"+letra+"_minuto_"+numero).val('');
							$("#"+letra+"_pais_"+numero).val('');
							$("#"+letra+"_localidad_"+numero).val('');
							$("#"+letra+"_provincia_"+numero).val('');
							$("#"+letra+"_profesion_"+numero).val('');
							
							$("#"+letra+"_nombre_"+numero).removeAttr('readonly');
							$("#"+letra+"_sexo_"+numero).removeAttr('disabled');
							$("#"+letra+"_dia_"+numero).removeAttr('disabled');
							$("#"+letra+"_mes_"+numero).removeAttr('disabled');
							$("#"+letra+"_ano_"+numero).removeAttr('disabled');
							$("#"+letra+"_hora_"+numero).removeAttr('disabled');
							$("#"+letra+"_minuto_"+numero).removeAttr('disabled');
							$("#"+letra+"_pais_"+numero).removeAttr('disabled');
							$("#"+letra+"_localidad_"+numero).removeAttr('readonly');
							$("#"+letra+"_provincia_"+numero).removeAttr('readonly');
							$("#"+letra+"_profesion_"+numero).removeAttr('readonly');
						
						});
						
						//cuando cambia cada select de las personas asociadas...
						$(".selects_asociados").change(function(){
							var cual_select = $(this).attr('id');
							var letra_y_numero_select = cual_select.split('_');
							var letra = letra_y_numero_select[0];
							
							var numero = letra_y_numero_select[2];
							
							var id_usuario_select = $(this).val();
							
							var es_curso = $("#"+letra+"_curso_"+numero).val() || "";
							//alert(letra_y_numero_select.length);
							$.getJSON("includes/get_datos_personas.inc.php",{tipo:'id', id:id_usuario_select},function(data){
							
								if(es_curso!=""){
									$.get("includes/validar_usuario_curso.inc.php",{id_curso:es_curso,id_usuario:data.id_usuario},function(data1){
										if(data1==0){
											$(".bt_siguiente").show();
										}else{
											alert("El usuario ya está inscripto en el curso");
											$(".bt_siguiente").hide();
											return false;
										}
									});
								}
								
								$("#"+letra+"_user_"+numero).val(data.id_usuario);
								$("#"+letra+"_nombre_"+numero).val(data.nombre);
								$("#"+letra+"_sexo_"+numero).val(data.sexo);
								$("#"+letra+"_dia_"+numero).val(data.dia);
								$("#"+letra+"_mes_"+numero).val(data.mes);
								$("#"+letra+"_ano_"+numero).val(data.anio);
								$("#"+letra+"_hora_"+numero).val(data.hora);
								$("#"+letra+"_minuto_"+numero).val(data.minutos);
								$("#"+letra+"_pais_"+numero).val(data.pais_nacimiento);
								$("#"+letra+"_localidad_"+numero).val(data.ciudad_nacimiento);
								$("#"+letra+"_provincia_"+numero).val(data.provincia_nacimiento);
								$("#"+letra+"_profesion_"+numero).val(data.profesion);
								
								$("#"+letra+"_nombre_"+numero).attr({'readonly':'true'});
								$("#"+letra+"_sexo_"+numero).attr({'disabled':'disabled'});
								$("#"+letra+"_dia_"+numero).attr({'disabled':'disabled'});
								$("#"+letra+"_mes_"+numero).attr({'disabled':'disabled'});
								$("#"+letra+"_ano_"+numero).attr({'disabled':'disabled'});
								$("#"+letra+"_hora_"+numero).attr({'disabled':'disabled'});
								$("#"+letra+"_minuto_"+numero).attr({'disabled':'disabled'});
								$("#"+letra+"_pais_"+numero).attr({'disabled':'disabled'});
								$("#"+letra+"_localidad_"+numero).attr({'readonly':'true'});
								$("#"+letra+"_provincia_"+numero).attr({'readonly':'true'});
								$("#"+letra+"_profesion_"+numero).attr({'readonly':'true'});
								
							});
							
						});
					});				
				}else{
					//Seteo Nuevo usario 
					$("#is_new_user").val('1');
					
					//Reseteo los valores
					$("#email_validation_img").html("<img src='images/ns_icon.png' />");
					/*$("#pass_validation_img").html("");
					$("#password").val('');
					
					//Muestro confirmacion de email y pass
					$('#row_email_validation').show();
					$('#row_password').show();
					$('#row_apellido').show();
					$("#user_email_validation").focus();
					
					//oculto la fila de personas asociadas
					$("tr.asociados").css({'display':'none'});*/
				}
			
			}
		});
	});
	
	// Launch MODAL BOX if the Login Link is clicked
	$("#login_link").click(function(){
			window.location = 'login.php';
	});
	
	//Logout
	/*$("#logout_link").click(function(){		
		
		$.ajax({  			
			url: "Scripts/modal_login/logout.php",  // Send the login info to this page			
			success: function(msg){
				$('#login_results').html(msg);

				//agrego el login
				// Launch MODAL BOX if the Login Link is clicked
				$("#login_link").click(function(){
					window.location = 'login.php';	
				});
			 }			  
		}); 
		
		
		clear_login();
	});*/

});

function clear_login(){
		
	//Seteo Nuevo usario 
	$("#is_new_user").val('1');
					
	//Reseteo los valores
	$('#login_result').html("");
	$("#email_validation_img").html("<img src='images/ns_icon.png' />");
	$("#pass_validation_img").html("");
	
	$("#user_name").val('');
	$('#user_name').removeAttr("readonly"); 

	$("#user_email").val('');
	$('#user_email').removeAttr("readonly"); 

	$("#user_email_validation").val('');
	$('#user_email_validation').removeAttr("readonly");

	
	$("#password").val('');
		
	//Muestro confirmacion de email y pass
	$('#row_email_validation').hide();
	$('#row_password').hide();
	$("#user_email").focus();
				
}

function set_loged_fields(email, name){
	
	$('#login_result').html("");
	
	//Seteo Nuevo usario 
	$("#is_new_user").val('0');
	
	//imagenes de usuario logeado
	$("#email_validation_img").html("<img src='images/ok_icon.png' />");
	
	//Se transforman los campos en read only
	$("#user_name").val(name);
	$("#user_name").attr("readonly", true);
	
	$("#user_email").val(email);
	$("#user_email").attr("readonly", true);
	
	$("#user_email_validation").val(email);
	$("#user_email_validation").attr("readonly", true);
	
	//Oculto campos de mas
	$('#row_email_validation').hide();
	$('#row_password').hide();
}


//Funcion que se ejectua cuando se logea el usuario correctamente
function go_to_private_page(email, name, redirect){	
		
	if (redirect){
		window.location = 'index.php';
	}
	else{	
			//Parse Login Column
			$.ajax({  
				type: "POST",
				url: "Scripts/modal_login/get-login-colum.php",  // Send the login info to this page			
				success: function(msg){			
						$('#login_results').html(msg);
						
						
						//Logout
						$("#logout_link").click(function(){		
						$.ajax({  
							type: "POST",
							url: "Scripts/modal_login/logout.php",  // Send the login info to this page			
							success: function(msg){	
								$('#login_results').html(msg);
								
								//agrego el login
								// Launch MODAL BOX if the Login Link is clicked
								$("#login_link").click(function(){
									window.location = 'login.php';	
								});
							 }			  
						});
						
						clear_login();
					});
						
						
				}
					  
			}); 
			
			//Se Fija como solo lectura los datos del usuario logeado
			set_loged_fields(email, name);
		
	}		
	//redirect after login
	

}

function validate_login(){
	error(0);
	
	//Nombre
	if($("#fuser_email").val() == ""){
		
		error(1, "Debe ingresar el email");
		$("#user_email_validation_img").html("<img src='images/ko_icon.png' />");
		return false;
	}
	
	//Password
	if($("#fpassword").val() == ""){
		
		error(1, "Debe ingresar el password");
		$("#password_validation_img").html("<img src='images/ko_icon.png' />");
		return false;
	}
	
	return true;

}

function validate_email_remember(){
	
		//Email
	if($("#femail_passf").val() == ""){
	
		error(1, "Debe ingresar una dirección de email");
		$("#femail_passf_validation_img").html("<img src='images/ko_icon.png' />");
		return false
	}
	else{
		//Email Validation					
		$.ajax({
				type: "POST",
				url: "Scripts/modal_login/do-email.php",  // Send the login info to this page
				data: 'action=email_validation&email=' + $("#femail_passf").val(),  
				success: function(msg){
					if(msg == 'OK') {										
						$("#femail_passf_validation_img").html("<img src='images/ok_icon.png' />");
						//Call send pass
						//Email Validation					
							$.ajax({
									type: "POST",
									url: "Scripts/modal_login/do-forget.php",  // Send the login info to this page
									data: 'action=user_pass_forgotten&femail_passf=' + $("#femail_passf").val(),  
									success: function(msg){
									
									if(msg == 'OK') {										
										error(1,"Se envió con exito su password, verifique su email." );						
									}
									else{										
										error(1,"Se produjo un error al enviar su password");	
										return false;
									}
								}
							});
					}
					else{
						$("#femail_passf_validation_img").html("<img src='images/ko_icon.png' />");
						error(1,"No hay un usuario registrado con esa cuenta");	
						return false;
					}
				}
			});
	}
}
