
/*
* ------------------------------------------------------------------------------
* login js file 
* Includes scripts for logging in
* Author Dinesh Kumar Muthukrishnan 
* -------------------------------------------------------------------------------
*/

/*
* Clear message 
*/
$(document).ready(function() {
	$('.message').html('');	
});
/*
* login click event handler
*/
$(document).on('click','#sign_in',function() {
	var username    = $('#username').val();
	var password    = $('#password').val();	
	var formData    = $('#loginForm').serialize();
	//alert(formData);
	var message     = '';
	var flag        = 1 ;

	if( username == "" ){
		message = "Please enter Username";
		flag = 0;
		$('#username').focus();
		setNotification( 'error', message, 'red' );
		return false;
	}	

	if ( password == "" ){
		message = "Please enter password";
		flag = 0;
		$('#password').focus();
		setNotification( 'error', message, 'red' );
		return false;
	}

	if ( flag == 1 ){
		$.ajax({
			url  : serverUrl+'login.php',
			data : formData,
			method : 'POST',
			success: function( response ) {
				console.log(response);
				var objData = JSON.parse( response );
				if( objData.code == 200 ){					
					setNotification( 'success', 'Login success..', 'green' );
	                setTimeout(function() {
	                    window.location.href = objData.url+'.php'; }, 2500 );		       		
			    }
			   	if( objData.code == 404 || objData.code == 405 ){	       	
		   			setNotification( 'error', 'Login failed', 'red' );
		   		}	
		    },
		    error: function () {
		        if( response.code == 401 ){
		       		window.location.replace('/');		       	
		        }
		        $('.message').addClass('error').html(message);
		    } 
		});
	}

});