
var login = {};
$(document).ready( function(){
	$(".sign-in").on("click", function(e){
		e.preventDefault();
		$(".callout").hide();

		var errors = 0;

		if( $('[name="login_user"]').val() == ""){
			login.Shake('[name="login_user"]');
			login.Callout({ Status : "Error", Message : "Empty Username" });
			errors ++;
		} else if( $('[name="login_pass"]').val() == ""){
			login.Shake('[name="login_pass"]');
			login.Callout({ Status : "Error", Message : "Empty Password" });
			errors ++;
		}

		if(errors == 0){
			var remember = 0;
			if($(".checkbox input").is(":checked")){ remember = 1; }

			login.GetModal({ 
				action : "login" 
				,login_user : $('[name="login_user"]').val() 
				,login_pass : $('[name="login_pass"]').val()
				,login_remember : remember
			}, function(r){
				if(r.Status == undefined || r.Status != "Success"){
					if(r.Target != undefined){
						login.Shake('[name="'+ r.Target +'"]');
						login.Callout(r);
					} else {
						login.Shake('[name="username"]');
						login.Shake('[name="login_pass"]');
						login.Callout(r);
					}	
				} else if(r.Status == "Success"){
					window.location.href = 'index.php';
				}
			});
		}
	});

	$(".forgot_pass").on("click", function(e){
		e.preventDefault();
		$(".callout").hide();
		var errors = 0;
		if( $('[name="login_user"]').val() == ""){
			login.Shake('[name="login_user"]');
			login.Callout({ Status : "Error", Message : "Empty Username" });
			errors ++;
		} 
		if(errors == 0){
			login.GetModal({  action : "forgot_pass" ,login_user : $('[name="login_user"]').val() }, function(r){
				if(r.Status == undefined || r.Status != "Success"){
					login.Shake('[name="username"]');
					login.Callout(r);
				} else if(r.Status == "Success"){
					login.Callout(r);
				}
			});
		}
	});

	// forgotpass
});

login.GetModal = function(post_data, callback){
	$.ajax({
		url: "app/model/Authentication.php",
		type : 'POST',
		data : post_data,
		success: function(result) {
			var r = $.parseJSON(result);
			callback(r);
		}
	});
}

login.Shake = function(select){
	var duration = 80;
    var offset = 40;

	$(select).animate({marginLeft:('-='+ offset)}, duration,function(){
		$(this).animate({marginLeft:('+=' + offset*2)}, duration, function(){
			$(this).animate({marginLeft:('-=' + offset*2)}, duration, function(){
				$(this).animate({marginLeft:('+='+ offset)}, duration);
			});
		});
	});  
}

login.Callout = function(res) {

	if (res.Status=="Success") {
		$(".callout-danger-template").hide();
		$(".callout-success-template").hide();
		$(".callout-success-template h4").html(res.Message); 
		$(".callout-success-template").fadeIn();
	} else {        		
		$(".callout-danger-template").hide();
		$(".callout-success-template").hide();
		$(".callout-danger-template h4").html(res.Message);
		$(".callout-danger-template").fadeIn();
	}
	return res;
}