var validAccounts = [];
var closestLoc = null;
var currentEditingAccName = null;
var currentEditingAccId = 0;
var isHUDShowing = true;

function moveToManagePage(accname, accid, accbalance) {
	$('#homePage').hide();
	$('#manageAccountPanel').css('display', 'block');
	currentEditingAccName = accname;
	currentEditingAccId = accid;
	$('#manageAccountTitle').text('Account: '+accname+' - (#'+accid+')');
	$('#manageAccountBalance').text('Account Balance - $'+accbalance);
}

function moveToHomePage() {
	$('#manageAccountPanel').css('display', 'none');
	$('#homePage').show();

}

function setupAndDisplayCreateAccountModal() {
	//Empties fields and shows modal:
	$('#createAccountName').val('');
	$('#createAccountDeposit').val('');
	$('#createAccount').modal('show');
}

function setupAndDisplayEditModal() {
	$('#editAccName').val(currentEditingAccName);
	$('#editAccount').modal('show');
}

function displayWithdrawModal() {
	$('#withdrawAmountField').val('');
	$('#withdrawModal').modal('show');
}
function displayDepositModal() {
	$('#depositAmountField').val('');
	$('#depositModal').modal('show');
}

function setupAndDisplayDeleteModal() {
	$('#deleteModal').modal('show');
}


function validateValuesAndEditAccount() {
	var newname = $('#editAccName').val();
    if (newname.length > 25) showErrorModal("Name too long! Must be 25 characters or less.");
	else if (!isNullOrWhitespace(newname)) editAccount(newname, currentEditingAccId);
	else showErrorModal("An error occurred creating this bank account.");
}

function verifyAndDeleteAccount() {
	deleteAccount(currentEditingAccId);
}

function validateValuesAndCreateAccount() {
	var name = $('#createAccountName').val();
	var initDeposit = $('#createAccountDeposit').val();

	if (name.length > 25) showErrorModal("Name too long! Must be 25 characters or less.");
	else if (!isNullOrWhitespace(name) && !isNullOrWhitespace(initDeposit)) createAccount(name, initDeposit);
	else showErrorModal("An error occurred creating this bank account.");
 
}

function verifyAndSendCash() {
	var amount = $('#giveCashAmountField').val();
	var plId = $('#giveCashPlayer').val();

	if (isNullOrWhitespace(amount) || isNullOrWhitespace(plId) || plId == "-1") {
		showErrorModal("An error occurred sending this money");
	}
	else {
		$.post('https://core.economy/GiveCash', JSON.stringify({
			idToSend: plId,
			amount: amount
		}));
	}
}

//misc. functions:
function closeUI() {
    $.post('https://core.economy/closeUI', JSON.stringify({}));
}

function createAccount(name, initDeposit) {
	$('#createAccount').modal('hide');
    $.post('https://core.economy/CreateAccount', JSON.stringify({
		name: name.toString(),
		initDeposit: initDeposit.toString(),
		closestLoc: closestLoc.LocationId.toString()
	}));
}

function editAccount(name, id) {
	$('#editAccount').modal('hide');
    $.post('https://core.economy/EditAccount', JSON.stringify({
		name : name.toString(),
		id: id.toString()
	}));
}

function deleteAccount(id) {
	$('#deleteModal').modal('hide');
    $.post('https://core.economy/DeleteAccount', JSON.stringify({ 
		id: id.toString()
	}));
}

function depositCash() {
	$('#depositModal').modal('hide');
    $.post('https://core.economy/DepositCash', JSON.stringify({
		id: currentEditingAccId,
		amount : $('#depositAmountField').val().toString()
	}));
}

function withdrawCash() {
	$('#withdrawModal').modal('hide');
    $.post('https://core.economy/WithdrawCash', JSON.stringify({
		id: currentEditingAccId,
		amount : $('#withdrawAmountField').val().toString()
	}));
}

function showErrorModal(msg) {
	$('#errorMsg').text('Error: '+ msg);
	$('#errorModal').modal('show');
}

function isNullOrWhitespace( input ) {

    if (typeof input === 'undefined' || input == null) return true;

    return input.replace(/\s/g, '').length < 1;
}

function setupLightOrDarkTheme() {
	$('#bank-body').css('background-color', '#212121');
	$('#panelCard1').addClass('bg-dark text-white');
	$('#panelCard2').addClass('bg-dark text-white');
	$('#panelCard3').addClass('bg-dark text-white');
	$('#welcomeToBankHeader').css('color', 'white');
	$('#navbar').addClass('bg-dark text-white');
	$('#createAtBranchesLabel').addClass('text-white');

	$('.modal-content').addClass('bg-dark text-white');
	$('input').addClass('bg-dark text-white');

	$('#accountsTable').addClass('table-dark');

	$('#manageAccountCard').addClass('bg-dark text-white');
	$('#sendCashCard').addClass('bg-dark text-white');

	$('.accInfoText').removeClass('text-primary');
	$('.accInfoText').addClass('text-white');
}

function setupDisplays(character, bankAccounts, loc) {
	var currentBank = "your accounts";
	totalMoney = 0;
	validAccounts = [];
	closestLoc = loc;
    $('#accountsTableBody').empty();

    if (loc && loc.T == 1) { currentBank = "Fleeca Bank"; $('#currentLogo').attr("src", "assets/img/fllogo.png"); $('#totalValidType').text('Fleeca Bank Accounts'); } else if (loc && loc.T == 2) {currentBank = "Maze Bank"; $('#currentLogo').attr("src", "assets/img/mblogo.png"); $('#totalValidType').text('Maze Bank Accounts'); } else { currentBank = "San Andreas Banking"; $('#currentLogo').attr("src", "assets/img/bothlogo.png"); $('#totalValidType').text('Bank Accounts'); }

	$('#bankHeader').text(loc && loc.IsATM ? character.FirstName + ' '+character.LastName + ' - ATM' : character.FirstName + ' '+character.LastName);
	$('#welcomeToBankHeader').text('Welcome to '+currentBank+', '+character.FirstName + ' '+character.LastName);

	if (!loc || loc.IsATM) {
		$('#createAccountButton').css('display', 'none');
		$('#createAtBranchesLabel').css('display', 'block');
	}
	else {
		$('#createAccountButton').css('display', 'block');
		$('#createAtBranchesLabel').css('display', 'none');
	}	
	
	//Setup valid accounts:
	for(i = 0; i < bankAccounts.length; i++) {
		acc = bankAccounts[i];
		if ((!loc || loc.T == 0 || ((loc.T == 1 && acc.BankAccountType == "FLEECA") || (loc.T == 2 && acc.BankAccountType == "MAZE"))) && !acc.DeletedAt) validAccounts.push(acc);
	}

	var totalMoney = 0;
	for (i = 0; i < validAccounts.length; i++) {
		$('#accountsTableBody').append('<tr><td scope="row" style="vertical-align: middle;">' + validAccounts[i].BankAccountName + '</td><td style="vertical-align: middle;">' + validAccounts[i].BankAccountType + '</td><td style="vertical-align: middle;">$' + validAccounts[i].Balance.toFixed(2) + '</td><td style="vertical-align: middle;"><button class="btn btn-primary" style="text-align: center; width: 100%; min-height: 10px;" onclick="moveToManagePage(\'' + escapeHtml(validAccounts[i].BankAccountName) + '\',\'' + validAccounts[i].BankAccountId + '\',\'' + validAccounts[i].Balance + '\')">Manage</button></td></tr>');
		totalMoney += validAccounts[i].Balance;
	}

	$('#totalBankedMoneyDisplay').text('$'+totalMoney.toFixed(2));
	$('#totalValidAccountsDisplay').text(validAccounts.length);

	UpdateCashDisplays(character.CashOnHand);
}

function escapeHtml(unsafe) {
	return unsafe
		.replace(/&/g, "&amp;")
		.replace(/</g, "&lt;")
		.replace(/>/g, "&gt;")
		.replace(/"/g, "&quot;")
		.replace(/'/g, "\\'");
}

function setupPlayerList(players) {
	$('#giveCashPlayer').empty();
	$('#giveCashPlayer').append('<option selected disabled="" value="-1">Select Player</option>');
	for (i = 0; i < players.length; i++) {
		$('#giveCashPlayer').append('<option value="'+players[i].ServerId+'">'+players[i].Name+'</option>');
	}

}

function UpdateCashDisplays(cash) {
	$('#cash').text(Number.isInteger(cash) ? cash : Number(cash).toFixed(2));
}

$(function() { //This code will run immediately on initialisation
	$('.js-example-basic-single').select2(); //initialises custom <select> as NUI/CEF does not support them natively

	window.addEventListener('message', function(event) {
		if (event.data.type == "ECONOMY_ENABLE_MAIN_UI") {

            setupLightOrDarkTheme();
			setupDisplays(event.data.character, event.data.bankAccounts, event.data.closestLoc);

			$('#homePage').show();
			$('#manageAccountPanel').css('display', 'none');
			$('#sendCashPage').css('display', 'none');
			$('#bank').fadeIn(300, function() {
				$('#bank').css("display", "block");
			});
		}
        else if (event.data.type == "ECONOMY_REFRESH_UI") {
			setupDisplays(event.data.currentChar, event.data.currentUsr, event.data.closestLoc);
		}

		else if (event.data.type == "ECONOMY_DISABLE_UI") {
			$('#bank').fadeOut(300, function() {
				$('#bank').css('display', 'none');
				$('#homePage').hide();
				$('#manageAccountPanel').css('display', 'none');
				$('#sendCashPage').css('display', 'none');
			});
		}

		else if (event.data.type == "ECONOMY_ERROR_MESSAGE") {
			$('#errorMsg').text('Error: '+event.data.msg);
			$('#errorModal').modal('show');
		}
		else if (event.data.type == "ECONOMY_SUCCESS_MESSAGE") {
			$('#successMsg').text('Success! '+event.data.msg);
			$('#successModal').modal('show');
		}

		else if (event.data.type == "UPDATE_CASH") {
			UpdateCashDisplays(event.data.cash);
		}

		else if (event.data.type == "ECONOMY_DISPLAY_GIVECASH_UI") {
			$('#sendCashPage').css('display', 'block');

			$('#bankHeader').text(event.data.character.FirstName + ' '+event.data.character.LastName);
			$('#giveCashBalance').text('Your Cash: $'+event.data.character.CashOnHand.toFixed(2));
			$('#welcomeToBankHeader').text('Send Cash');
			$('#giveCashAmountField').val('');
			$('#currentLogo').attr("src", "assets/img/bothlogo.png");
			
			setupLightOrDarkTheme(event.data.currentSettings);
			setupPlayerList(event.data.players);

			$('#bank').fadeIn(300, function() {
				$('#bank').css("display", "block");
			});

		}
		else if (event.data.type == "TOGGLE_HUD") {
			isHUDShowing = event.data.enable;
			if (isHUDShowing) $('#cashDisplay').fadeIn();
			else $('#cashDisplay').fadeOut();
		}
	});

	withdrawAmountField.onkeypress = function(e) {
		if(!(e.keyCode >= 48 && e.keyCode <= 57) && e.keyCode != 46) return false;
		if (withdrawAmountField.value.length > 9) return false;
	}
	depositAmountField.onkeypress = function(e) {
		if(!(e.keyCode >= 48 && e.keyCode <= 57) && e.keyCode != 46) return false;
		if (depositAmountField.value.length > 9) return false;

	}
	createAccountDeposit.onkeypress = function(e) {
		if(!(e.keyCode >= 48 && e.keyCode <= 57) && e.keyCode != 46) return false;
		if (createAccountDeposit.value.length > 9) return false;
	}



 	$('#createAccountDeposit').bind('copy paste cut',function(e) { 
		 e.preventDefault(); //disable cut,copy,paste
	 });
  	$('#withdrawAmountField').bind('copy paste cut',function(e) { 
		 e.preventDefault(); //disable cut,copy,paste
	 });
   	$('#depositAmountField').bind('copy paste cut',function(e) { 
		 e.preventDefault(); //disable cut,copy,paste
	 });
    $('#createAccountName').bind('copy paste cut',function(e) { 
		 e.preventDefault(); //disable cut,copy,paste
	 });
    $('#editAccName').bind('copy paste cut',function(e) { 
		 e.preventDefault(); //disable cut,copy,paste
	 });
});