$(document).ready(function(){
// process the login form 
    $('#login-form').submit(function(event) { 
		$('#login-button').hide();
		$('#login-spin').show();
        var formData = {
            'password'     : $('#password').val(),
            'email'    : $('#email').val(),
            'login'    : '1'
        };

        $.ajax({
            type        : 'POST', 
            url         : 'index.php', 
            data        : formData, 
            dataType    : 'json',
            encode      : true
        }).done(function(data) {
            if ( ! data.success) {
				if (data.errors) {
					swal("Oops!", data.errors, "warning");
					$('#login-button').show();
					$('#login-spin').hide();
				}
			} else {
				localStorage.setItem("username", $('#email').val());
				localStorage.setItem("password", $('#password').val());
				window.location = 'Inbox.html'; 
			}
            }).fail(function (jqXHR,status,err) {
				swal("Oops!", 'Connection to mail server failed', "warning");
				$('#login-button').show();
				$('#login-spin').hide();
			});
        event.preventDefault();
    });	
	
	$('#message-form').submit(function(event) { 
		$('#send').hide();
		$('#login-spin').show();
		var saveToAdd = 0;
		if($('#add-address').is(':checked')) {
			var saveToAdd = 1;
		}
		var user = localStorage.getItem("username")
		var pass = localStorage.getItem("password")
        var formData = {
            'message'  		: $('#message').val(),
            'subject'    	: $('#subject').val(),
			'to'    		: $('#to').val(),
			'cc'    		: $('#cc').val(),
			'from'    		: localStorage.getItem("username"),
            'send'    		: '1',
			'save_address'	: saveToAdd,
			'email'			: user,
			'password'		: pass
        };

        $.ajax({
            type        : 'POST', 
            url         : 'index.php', 
            data        : formData, 
            dataType    : 'json',
            encode      : true
        }).done(function(data) {
            if ( ! data.success) {
				if (data.errors) {
					swal("Oops!", data.errors, "warning");
					$('#send').show();
					$('#login-spin').hide();
				}
			} else {
				swal("Done!", 'Message sent', "success");
				$('#message').val(''),
				$('#subject').val(''),
				$('#to').val(''),
				$('#cc').val(''),
				setTimeout( function() {
					window.location = 'Inbox.html'; 
				  }, 5000);
				
			}
            }).fail(function (jqXHR,status,err) {
				swal("Oops!", 'Connection to mail server failed', "warning");
				$('#send').show();
				$('#login-spin').hide();
			});
        event.preventDefault();
    });	
	
	var currents = window.location.pathname; 
	//check login
	if(currents.indexOf('index') < 1) { 
		if(localStorage.username === null) {
			window.location = 'index.html'; 
		} else { 
			var user = localStorage.getItem("username");
			if(user === null) {
				window.location = 'index.html'; 
			} else {
				//just move opn for now. I may decide to make things more interesting later. 
				$('#user-log').html(user+''); 
			}
		}
	} 
	//load inbox
	if(currents.indexOf('Inbox') > -1) { 
		loadInbox(); 
	}
	
	//pop up reply box
	$('#reply').click(function() { 
		$('#to').val($('#msg-from').text());
		 //$("#to").focus();
		$('#subject').val('Re: '+$('#msg-title').text());
		 //$("#subject").focus();
		$('#message').val('<br><bt>-----------<br>'+$('#msg-body').html());
		$('#message').focus();
		$('#mail-detail').hide();
		$('#compose-btn').hide();
		$('#inbox-list').hide();
		$('#composer').show('slow');
	});

});
	//load inbox
	function loadInbox() { 
		var user = localStorage.getItem("username")
		var pass = localStorage.getItem("password")
		var formData = {
            'password' : pass,
            'email'    : user,
            'inbox'    : '1'
        };

        $.ajax({
            type        : 'POST', 
            url         : 'index.php', 
            data        : formData, 
            dataType    : 'html',
        }).done(function(data) { 
            if ( data.indexOf('No massages found') > -1) { 
				swal("Oops!", data, "warning");
				$('#mail-y').html('<p>No connection</p>');
			} else {
				//set contents
				$('#inbox-list').html(data);
			}
        }).fail(function (jqXHR,status,err) { alert(err);
				swal("Oops!", 'Connection to mail server failed', "warning");
				$('#mail-y').html('<p>No connection</p>');
		});
	}
	
	//logout
	function doLogout() {
		localStorage.removeItem("username");
		localStorage.removeItem("password");
		window.location = 'index.html'; 
	}
	
	//read selected mail
	function fetchMail(mail_id) { 
	   $('#msg-body').html('<p>Fetching full message...</p>');
	   $('#mail-detail').show();
	    var formData = {
            'email_id'    : mail_id,
            'loadmail'    : '1'
        };

        $.ajax({
            type        : 'POST', 
            url         : 'index.php', 
            data        : formData, 
            dataType    : 'json',
            encode      : true
        }).done(function(data) {
            if ( ! data.success) {
				if (data.errors) {
					swal("Oops!", data.errors, "warning");
					$('#msg-body').html('');
					$('#mail-detail').hide()
				}
			} else {
				$('#msg-from').text(data.sender);
				$('#msg-to').text(data.to);
				$('#msg-date').text(data.date);
				$('#msg-from2').text(data.sender);
				$('#msg-title').text(data.subject);
				$('#msg-body').html(data.message);
				$('#mail-detail').show();
				
			}
        }).fail(function (jqXHR,status,err) { 
				swal("Oops!", 'Connection to mail server failed', "warning");
				$('#msg-body').html('<p>No connection</p>');
				$('#mail-detail').hide()
		});
	}
window.onerror = function(msg, url, linenumber) {
    alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
    return true;
}
