<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<html lang="en">
<head>
  <meta charset="UTF-8">
<script type='text/javascript' charset='utf-8'>
    // Hides mobile browser's address bar when page is done loading.
      window.addEventListener('load', function(e) {
        setTimeout(function() { window.scrollTo(0, 1); }, 1);
      }, false);
</script>
    <meta charset="UTF-8">
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<script src="../upld.js"></script>
	<title>Notepad</title>
	<style>
	body{
		background-color:#2b2b2b;
	}
	* {
      font-family: arial;
    }
	
	.topbar{
		background-color: #f1f1f1;
		overflow: hidden;
		position:fixed;
		top:0px;
		left:0;
		width:100%;height:25px;
		padding-left: 5px;
	}

	#topbarMenu{
		background-color: #f1f1f1;
	}
	
	button{
		padding: 5;
		border: none;
		background: none;
		height:25px;
	}
	
	button:hover {
		background-color: #edeaea;
		opacity: 0.6;
		cursor: pointer;
	}
	
	#codeArea{
		width:100%;
		position:fixed;
		top:48px;
		left:0px;
	}
	
	#tabs{
		background-color: #d6d6d6;
		position:fixed;
		width:100%;
		height:23px;
		top:25px;
		left:0px;
		overflow-x:auto;
	}
	
	.fileTab{
		background-color: #bcbcbc;
		display:inline;
		padding-left: 8px;
		padding-right: 1px;
		margin-left:1px;
		height:25px;
		border-bottom: 3px solid #878787;
		cursor: pointer;
	}
	
	.fileTab.focused{
		background-color: #edeaea;
		display:inline;
		border-bottom: 3px solid #5b4cff;
		cursor: pointer;
	}

	.fileTab.notsaved{
		border-bottom: 3px solid #ffc04c !important;
	}

	.fileTab .star{
		display: none;
	}

	.fileTab.notsaved .star{
		display: auto;
	}

	.closeBtn{
		display:inline;
	}
	
	.contextmenu{
		position:fixed;
		top:25px;
		left:0px;
		width:auto;
		height:auto;
		background-color:#d6d6d6;
		z-index:100;
		border-style: solid;
		border-width: 1px;
		border-color: #dbdbdb;
		font-size:small;
		max-height: 100%;
		overflow-y: auto;
	}
	
	.menuitem{
		padding-top: 2px;
		padding-bottom: 3px;
		padding-left: 25px;
		padding-right: 10px;
	}
	
	.menuitem:hover{
		background-color: #edeaea;
		opacity: 0.7;
		cursor: pointer;
	}
	
	.middleFloat{
		position:fixed;
		top:10%;
		bottom: 10%;
		left: 30%;
		right: 30%;
		background-color:#fafafa;
		padding:25px;
		overflow-y:auto;
	}
	
	.selectable{
	    cursor: pointer;
	    padding:1px;
	    padding-left:10px;
	    border: 1px solid transparent;
	}
	
	.selectable:hover{
	    background-color:#ffffff;
	    border: 1px solid #2890ff;
	}
	
	.scs{
		display:inline-block;
		margin: 3px;
		padding-left: 10px;
		padding-top: 10px;
		width: 20px !important;
		height:30px;
		border: 1px solid #c4c4c4;
		cursor:pointer;
		font-weight: bold;
	}
	.scs:hover{
		border: 1px solid #6e86a0;
		background-color:#a9c7e8;
	}
	.npalogo{
		background-color:#2b2b2b;
		color:white;
		padding:8px;
	}
	#tabList{
		position:fixed;
		right:0px;
		top:45px;
		min-width:100px;
		z-index:99;
		background-color:#d6d6d6;
		text-align:right;
		padding-bottom:5px;
		display:none;
	}
	#showList{
		position:absolute;
		top:0px;
		cursor:pointer;
		right:0px;
		padding:5px;
		margin-top:-2px;
		display:none;
	}
	#showList:hover{
		background-color:#ffffff;
	}
	</style>
</head>
<body>
<div class="topbar">
	<button onClick="startTooggleMenu(this);">File</button>
	<button onClick="startTooggleMenu(this);">Edit</button>
	<button onClick="startTooggleMenu(this);">Search</button>
	<button onClick="startTooggleMenu(this);">Theme</button>
	<button onClick="startTooggleMenu(this);">Font_Size</button>
	<button onClick="startTooggleMenu(this);">About</button>
</div>
<div id="tabs" onClick="hideToggleMenu();">
<div id="showList" onClick="showFullTabMenu();">⬇️ All Tabs</div>
</div>
<div id="tabList">
</div>
<div id="codeArea">

</div>
<div id="topbarMenu" class="contextmenu" style="display:none;">

</div>
<div id="aboutus" class="middleFloat" style="display:none;">
	<h3>πŸ“ Notepad In-System Text Editor</h3>
	<p>Author: Toby Chui 2017-2023</p>
	<hr>
	<p>This web based text editor for ArOZ Online System are made possible by the ace editor, jQuery and ArOZ Project. Part of the system are licensed under BSD License. Please refer to the individual license information under the library folder. <br><br><br>
 	Developed for ArOZ Online Beta and migrated to ArozOS, trimmed down for WebStick project</p>
	<hr>
	<p>BSD License<p>
	<p style="font-size:70%;">All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
   This product includes software developed by the <organization>.
4. Neither the name of the <organization> nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</p>
	<hr>
	<button style="background-color:white;border: 1px solid #707070;" onClick="$('#aboutus').hide();">Close</button>
	<br><br><br><br><br>
</div>

<div id="saveAsSelectionMenu" class="middleFloat" style="display:none;">
    <table id="directoryList" style="width:100%;font-size:80%;">
        <tr><th id="directoryPath">πŸ“‚ /</th></tr>
        <tr><td>Initializing...</td></tr>
    </table>
    <br>
    <hr>
    Save Filename
    <input id="saveAsFilename" style="width:100%;"></input>
    <hr>
    <button style="background-color:white;border: 1px solid #707070;" onClick="saveToDirectory();">Save In Current Directory</button>
    <button style="background-color:white;border: 1px solid #707070;" onClick="$('#saveAsSelectionMenu').hide();">Close</button>
   <br><br><br><br><br>
</div>

<div id="specialCharInsert" class="middleFloat" style="display:none;">
	Insert Special Character
	<hr>
	<br>
	<div id="iscl" style="max-height:70%;left:0;right:0;overflow-y:scroll;overflow-wrap: break-word;">
			
	</div>
	<hr>
	<button style="background-color:white;border: 1px solid #707070;" onClick="$('#specialCharInsert').hide();">Close</button><p style="font-size:50%;display:inline-block;padding-left:20px;" id="scid">N/A</p>
</div>
<script>
//Global variables
var moduleRootPath = "NotepadA/";
var dragIn = "";
var theme = 'github';
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
var is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox')
var lastSelectedMenuItem = "";
var fontsize = 12;
var VDI = false;
var openedFilePath = [];
var previousSavedState = true;
var currentSaveAsPath = "/";
var insertTarget;
var currentTabWidth = 0;
var mainCodingWindow = true;
var functionList = {
	File: ["πŸ“‚Open current directory","Reload","πŸ’Ύ Save","Close All Tabs","πŸ–¨ Print"],
	Edit: ["β€Ί Undo","β€» Redo","Open in New Tab"],
	Search:["Find / Replace"],
	Theme:["ambiance","chaos","chrome","clouds","clouds_midnight","cobalt","crimson_editor","dawn","dracula","dreamweaver","eclipse","github","gob","gruvbox","idle_fingers","iplastic","katzenmilch","kr_theme","kuroir","merbivore","merbivore_soft","mono_industrial","monokai","pastel_on_dark","solarized_dark","solarized_light","sqlserver","terminal","textmate","tomorrow","tomorrow_night","tomorrow_night_blue","tomorrow_night_bright","tomorrow_night_eighties","twilight","vibrant_ink","xcode"],
	Font_Size:["8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25"],
	About:["About NotepadA"]
};

//Init functions
adjustCodeAreaHeight();
bindListener();
init();

//Start all NotepadA services
function init(){
	initTheme(function(){
		console.log("Theme setting loaded");
		initFontSize(function(){
			console.log("Font-size setting loaded");
			initNotepadA(function(){
				console.log("Notepad started");
				reloadAllTabs();
				loadAllSpecialCharacter();
			});
		});
	});
}

function loadInputFiles(){
	try{
		if (window.location.hash.length == 0){
			return null;
		}
		var inputFileInfo = window.location.hash.substring(1,window.location.hash.length);
		inputFileInfo = JSON.parse(decodeURIComponent(inputFileInfo));

		if (inputFileInfo.length == 0){
			return null;
		}
		return inputFileInfo
	}catch{
		return null;
	}
}

//Init notepadA. If there are previos stored page, load them into the environment. Or otherwise, just open a blank page.
function initNotepadA(callback=undefined){
	//Load input file from hash
	inFiles = loadInputFiles();
	if (inFiles == null){
		dragIn = "";
	}else{
		dragIn = [];
		inFiles.forEach(function(file){
			dragIn.push(file.filepath); 
		});
	}

	console.log("Loaded: ", inFiles);

	loadStorage("sessionFiles", function(sessionFiles){
		console.log(sessionFiles);
		if (sessionFiles == ""){
			//No previous opened files
			if (dragIn != ""){
				//If there is a file dragin, open it as well.
				dragIn.forEach(function(openingFile){
					newEditor(openingFile);
				})
			}else{
				newTab();
			}
		}else{
			//There are perviously opened files
			try{
				var pages = JSON.parse(sessionFiles);
				for (var i =0; i < pages.length;i++){
					let page = pages[i];
					newEditor(page);
				}

				if (dragIn != ""){
					//If there is a file dragin, and it hasn't been opened, open it
					dragIn.forEach(function(filepath){
						if (pages.indexOf(filepath) == -1){
							newEditor(filepath);
						}else{
							focusTab($($(".fileTab")[pages.indexOf(filepath)]).attr("tabid"));
						}
					})
				}
			}catch(ex){
				console.log("Unable to open previous files: ", ex);
			}
		
		}

		setTimeout(function(){
			setInterval(function(){
				var tabid = getFocusedTab();
				if (tabid.length == 0){
					return;
				}
				var tab = findTabWithAttr("framematch",tabid[0]);
				var saved = checkTabSaved(tabid[0]);
				if (saved != previousSavedState){
					previousSavedState = saved;
					if (saved){
						document.title = "NotepadA   	 πŸ“ " + tab.attr("filename");
					}else{
						document.title = "NotepadA   	 *πŸ’Ύ πŸ“ " + tab.attr("filename");
					}
				}
				
				
			},1000);
		},500);
		
		toggleFileTabsList();

		if (callback != undefined){
			callback();
		}
		
	})
}

function initTheme(callback=undefined){
	loadStorage("NotepadA_theme", function(data){
		if (data != ""){
			theme = data;
		}
		console.log("NotepadA Theme Loaded: " + theme)
		if (callback != undefined){
			callback();
		}
	});
}

function initFontSize(callback=undefined){
	loadStorage("NotepadA_fontsize", function(data){
		if (data != ""){
			fontsize = data;
		}
		if (callback != undefined){
			callback();
		}
	});

	
}


//Add a new editor window to the editor (?) -->ALL FILE PATH PASSED IN MUST BE FROM AOR OR /media/storage*
function newEditor(filepath){
     if (openedFilePath.includes(filepath)){
        //This page is already opened. Ignore this request and focus on the existing tab.
        $(".fileTab").each(function(){
            if ($(this).attr("filename").includes(filepath)){
                var tabid = $(this).attr("tabid");
                focusTab(tabid);
            }
        });
        return;
    }

	let tabid = Math.round((new Date()).getTime());
	let payload = {
		"tabid": tabid,
		"theme": theme,
		"filename": filepath,
		"fontsize": fontsize,
		"timestamp": Date.now() //Add this to make sure browser dont cache resp
	}

	console.log("Opening",payload);

	let encodedPayload = encodeURIComponent(JSON.stringify(payload))
	var tab = `<div class="fileTab" tabid="${tabid}" framematch="ca${tabid}" filename="${filepath}">
				loading... <div class="closeBtn">β¨―</div>
				</div>`;
	var frame = `<div style="position:fixed;width:100%;"><iframe id="ca${tabid}" class="editor" src="ace/editor.html#${encodedPayload}" width="100%" frameBorder="0"></iframe></div>`;
	$("#tabs").append(tab);
	$("#codeArea").append(frame);
	updateFrameAttr('ca' + tabid);
	focusTab(tabid + "");
	if (openedFilePath.indexOf(filepath) == -1){
		openedFilePath.push(filepath);
	}
	setStorage("sessionFiles",JSON.stringify(openedFilePath));
}

function newTab(){
	let tabid = Math.round((new Date()).getTime());
	let fileID = 'newfile_' + tabid;

	const blob = new Blob([`<html>
	<head>
		<title></title>
	</head>
	<body>
		<h1> Hello World </h1>
	</body>
	</html>`], { type: 'text/html' });
    const file = new File([blob], "new.html");
    handleFile(file, "/", function(){
        //Finish writting to the new file. Open the new file in new tab
		var tab = '<div class="fileTab" tabid="'+tabid+'" framematch="ca'+tabid+'" filename="' + data + '">\
					loading... <div class="closeBtn">β¨―</div>\
					</div>';
		let payload = {
			"tabid": tabid,
			"theme": theme,
			"filename": data,
			"fontsize": fontsize,
			"timestamp": Date.now() //Add this to make sure browser dont cache resp
		}
		let encodedPayload = encodeURIComponent(JSON.stringify(payload))
		var frame = '<div style=""><iframe id="ca'+tabid+'" class="editor" src="ace/editor.html#' + encodedPayload + '" width="100%" frameBorder="0"></iframe></div>';
		$("#tabs").append(tab);
		$("#codeArea").append(frame);
		updateFrameAttr('ca' + tabid);
		setTimeout(function(){focusTab(tabid + "");},100);
		if (openedFilePath.indexOf(data) == -1){
			openedFilePath.push(data);
		}
		setStorage("sessionFiles",JSON.stringify(openedFilePath));
    });
}


function getSelectedText(){
    var id = getFocusedTab()[0];
    var text = $("#" + id)[0].contentWindow.getSelectedText();
    return text;
}

function insertText(text){
    var id = getFocusedTab()[0];
    var text = $("#" + id)[0].contentWindow.insertGivenText(text);
}


function adjustCodeAreaHeight(){
	$(".editor").each(function(i) {
		$(this).css("height",$(document).height() - 38);
	});
}

function checkTabSaved(framematch){
	if (typeof $("#" + framematch)[0].contentWindow.checkIsSaved !== "undefined") { 
		var result = $("#" + framematch)[0].contentWindow.checkIsSaved();
		return result;
	}
}

$( window ).resize(function() {
	adjustCodeAreaHeight();
	toggleFileTabsList();
});

function showFullTabMenu(){
	$("#tabList").slideToggle('fast');
}

var inList = false;
function toggleFileTabsList(){
	//Check if the width of the container is enough for holding all the filetabs. If no, move all of them into the filtab list.
	var totalWidthOfFileTabs = 0;
	var maxWidth = 0;
	$("#tabList").show();
	$(".fileTab").each(function(){
		totalWidthOfFileTabs = totalWidthOfFileTabs + $(this).width();
		if ($(this).width() > maxWidth){
			maxWidth = $(this).width();
		}
	});
	$("#tabList").hide();
	totalWidthOfFileTabs = parseInt(totalWidthOfFileTabs);
	if (window.innerWidth < totalWidthOfFileTabs && !inList){
		//window innerWidth space is less than the space needed to put all tabs. Move all of them into the list instead.
		$(".fileTab").each(function(){
			$("#tabList").append($(this));
			$("#tabList").append("<br>");
		});
		inList = true;
		$("#showList").show();
		$("#tabList").show();
	}else if (window.innerWidth > totalWidthOfFileTabs && inList){
		$(".fileTab").each(function(){
			$("#tabs").append($(this));
		});
		$("#tabList").html("");
		inList = false;
		$("#showList").hide();
		$("#tabList").hide();
	}
	currentTabWidth = totalWidthOfFileTabs;
}

function bindListener(){
	$(document).on('click', '.closeBtn', function () {
		removeTab($(this).parent().attr('tabid'));
	});

	$(document).on('click','.fileTab',function(){
		if ($(this).hasClass("closeBtn") == false){
			focusTab($(this).attr('tabid'));
		}
	});

	$(document).on('click','#codeArea',function(){
		$("#topbarMenu").hide();
	});
	
	$(document).on('click','.menuitem',function(){
		if (lastSelectedMenuItem == "Theme"){
			setTheme($(this).text());
			$("#topbarMenu").hide();
		}else if (lastSelectedMenuItem == "Font_Size"){
			setFontSize($(this).text());
			$("#topbarMenu").hide();
		}else if (lastSelectedMenuItem == "File"){
			handleFileMenu($(this).text());
			$("#topbarMenu").hide();
		}else if (lastSelectedMenuItem == "About"){
			handleAboutMenu($(this).text());
			$("#topbarMenu").hide();
		}else if (lastSelectedMenuItem == "Search"){
		    if ($(this).text() != ""){
		        launchFocusedTabSearchBox();
		    }
		    $("#topbarMenu").hide();
		}else if (lastSelectedMenuItem == "Edit"){
		    handleEditMenu($(this).text());
		    $("#topbarMenu").hide();
		}else{
			alert(lastSelectedMenuItem);
		}
		
	});
	
}

function handleEditMenu(itemText){
    var indexvalue = functionList.Edit.indexOf(itemText);
	switch (indexvalue){
		case 0:
			var id = getFocusedTab()[0];
			$("#" + id)[0].contentWindow.callUndo();
			break;
		case 1:
			var id = getFocusedTab()[0];
			$("#" + id)[0].contentWindow.callRedo();
			break;
	    case 2:
			var id = getFocusedTab()[0];
	        $("#" + id)[0].contentWindow.openInNewTab();
			//Call to openInNewTab function for opening new tab;
	        break;
	}
    
}

function updateFrameAttr(framematch){
	//This function will update the tab title, iframe attr at the same time. 
	var frame = $("#" + framematch);
	var tab = findTabWithAttr("framematch",framematch);
	var filepath = tab.attr("filename");
	var filedata = getFilenameAndBasedir(filepath);
	var basedir = filedata[0];
	var filename = filedata[1];
	
	$(tab).html(filename + ' <div class="closeBtn">β¨―</div>');
	//Update the iframe attr
	$(frame).attr("basedir",basedir);
	$(frame).attr("filename",filename);
	//
	adjustCodeAreaHeight();
}

function getFilenameAndBasedir(filepath){
	var f = filepath.split("/").pop();
	var b = filepath.replace(f,"");
	return [b,f];
}

function reloadAllTabs(){
	$(".fileTab").each(function(){
		var tid = $(this).attr("tabid");
		reloadTab(tid + "");
		updateFrameAttr($(this).attr("framematch"));
	});
}

function reloadTab(tabID){
	var object = findTabWithAttr("tabid",tabID);
	var filename = $(object).attr("filename");
	var codeAreaID = $(object).attr("framematch");
	let payload = {
		"tabid": tabID,
		"theme": theme,
		"filename": filename,
		"fontsize": fontsize,
		"timestamp": Date.now() //Add this to make sure browser dont cache resp
	}
	let encodedPayload = encodeURIComponent(JSON.stringify(payload))
	console.log($("#" + codeAreaID));
	$("#" + codeAreaID).attr("src","ace/editor.html#" + encodedPayload);
	$("#" + codeAreaID)[0].contentWindow.location.reload();
}

function launchFocusedTabSearchBox(){
    var framematch = getFocusedTab()[0];
    $("#" +framematch)[0].contentWindow.startSearchBox();
    //alert(framematch);
}


function handleFileMenu(itemText){
	var indexvalue = functionList.File.indexOf(itemText);
	switch (indexvalue){
		case 0:
			//Open the current folder in explorer
			var base = getFocusedTab()[1];
			if (base == undefined){
				break;
			}

			window.open("fs.html#" + base)
			break;
		case 1:
			//Reload is pressed
			var currentFocusedtid = getFocusedTab()[0];
			if (currentFocusedtid == undefined){
				break;
			}
			var tabobject = findTabWithAttr("framematch",currentFocusedtid);
			reloadTab(tabobject.attr("tabid") + "");
			break;
		case 2:
			//Save is pressed
			var currentFocusedtid = getFocusedTab()[0];
			if (currentFocusedtid == undefined){
				break;
			}
			$("#" + currentFocusedtid)[0].contentWindow.Save();
			break;
		case 3:
			$(".fileTab").each(function(){
				removeTab($(this).attr("tabid"));
			});
			break;
		case 4:
			var id = getFocusedTab()[0];
			$("#" + id)[0].contentWindow.Print();
			break;
	}
}

function handleAboutMenu(itemText){
	var indexvalue = functionList.About.indexOf(itemText);
	if (indexvalue == 0){
		$("#aboutus").show();
	}
}

function getFocusedTab(){
	result = [];
	$(".fileTab").each(function(){
		if ($(this).hasClass("focused")){
			//This tab is focused. Check its filename and pathinfo
			var id = $(this).attr("framematch");
			var filename = $("#" + id).attr("filename");
			var basedir = $("#" + id).attr("basedir");
			result = [id,basedir,filename];
		}
	});
	return result;
}

function setTheme(themeName){
	setStorage("NotepadA_theme",themeName);
	theme = themeName;
	
	if (checkIfAllTabSaved() == false){
		//Ask the user if confirm close
		var confirmClose = confirm("Reloading NotepadA is required to apply the changes. Confirm?");
		if (confirmClose == false){
			return false;
		}
	}
	console.log("Updating theme to: " + themeName);
	//Reload all tabs with the corrispoding themes after changing theme settings
	reloadAllTabs();
}

function setFontSize(newsize){
	setStorage("NotepadA_fontsize",newsize);
	fontsize = newsize;

	if (checkIfAllTabSaved() == false){
		//Ask the user if confirm close
		var confirmClose = confirm("Reloading NotepadA is required to apply the changes. Confirm?");
		if (confirmClose == false){
			return false;
		}
	}
	reloadAllTabs();
}

function checkIfAllTabSaved(){
	var allSaved = true;
	$(".editor").each(function(){
		if ($(this)[0].contentWindow.checkIsSaved() == false){
			allSaved = false;
		}
	});
	return allSaved;
}

function setStorage(configName,configValue){
	$.ajax({
		type: 'GET',
		url: "/api/pref/set",
		data: {key: "notepad/" + configName, value:encodeURIComponent(JSON.stringify(configValue))},
		success: function(data){},
		async:true
	});
	return true;
}

function loadStorage(configName, callback){
	var result = "";
	$.ajax({
		type: 'GET',
		url: "/api/pref/get",
		data: {key: "notepad/" + configName},
		success: function(data){
			if (data.error != undefined){
				callback("");
				return;
			}
			data = JSON.parse(decodeURIComponent(data));
			console.log(configName, data);
			callback(data);
		},
		error: function(data){
			callback("");
		},
		timeout: 3000
	});
}

function setTabIsSaved(tabid, saveState=true){
	var targetTab = findTabWithAttr("tabid",tabid);
	if (!saveState){
		$(targetTab).addClass("notsaved");
	}else{
		$(targetTab).removeClass("notsaved");
	}
	//console.log(targetTab, tabid, saveState);
}

function removeTab(tabid){
	var focusingTabFramematchBeforeRemove = getFocusedTab()[0];
	let origianlTabID = findTabWithAttr("framematch",focusingTabFramematchBeforeRemove).attr("tabid");
	var targetTab = findTabWithAttr("tabid",tabid);
	var filepath = targetTab.attr("filename").replace("../../","");
	var codeAreaTag = $(targetTab).attr("framematch");
	//Check if the tab is saved
	var saved = checkTabSaved(targetTab.attr("framematch"));
	if (saved == false){
		//Ask the user if confirm close
		var confirmClose = confirm("This file is not saved. Confirm closing?");
		if (confirmClose == false){
			return false;
		}
	}
	//Remove this record from the filepath so we will not open this again by the enxt time we startup NotepadA
	openedFilePath.remove(filepath);
	if ($(targetTab).hasClass("focused")){
		//This tab is currently focused, move focus to another tab after closing
		$(targetTab).remove();
		//I have no idea why this only works with a delay... but just don't change this.
		setTimeout(function(){
			var focusTarget = $(".fileTab").last().attr("tabid");
			focusTab(focusTarget); }, 100);
	}else{
		$(targetTab).remove();
		setTimeout(function(){ focusTab(origianlTabID);}, 100);
	}
	$("#" + codeAreaTag).remove();
	if ($(".fileTab").length == 0){
		//There is no more tab left, create a new tab instead
		setTimeout(function(){ newTab("untitled"); }, 100);
	}
	setStorage("sessionFiles",JSON.stringify(openedFilePath));
	toggleFileTabsList();
}

function hideToggleMenu(){
	$("#topbarMenu").hide();
}

$(".scs").hover(function(){
	var keyid = $(this).attr("keyid");
	$("#scid").html("HTML Keycode: #&" + keyid);
});

$(".scs").on("mousedown",function(){
	insertTarget.insertChar($(this).text());
	$("#specialCharInsert").hide();
});

function startTooggleMenu(object){
	var menu = $(object).text();
	var pos = $(object).offset().left - 5;
	toogleMenu(pos,menu);
}

function toogleMenu(left,contentID){
	$("#topbarMenu").css("left",left + "px");
	if (contentID != lastSelectedMenuItem && $("#topbarMenu").is(":visible")){
		$("#topbarMenu").hide();
	}
	loadOptionToMenu(contentID);
	$("#topbarMenu").toggle();
	lastSelectedMenuItem = contentID;
}

function loadOptionToMenu(menuItem){
	var items = functionList[menuItem];
	$("#topbarMenu").html("");
	for (var i=0; i < items.length;i++){
		$("#topbarMenu").append("<div class='menuitem'>" + items[i] + "</div>");
	}
}

function focusTab(tabid){
	//Defocus every tabs and hide all coding windows
	$(".fileTab").each(function(i) {
		$(this).removeClass("focused");
	});
	$(".editor").each(function(i) {
		$(this).hide();
	});
	//Only show the tab and code window selected
	var selectedTab = findTabWithAttr("tabid",tabid);
	$(selectedTab).addClass("focused");
	var corrispondingCodingTab = $(selectedTab).attr("framematch");
	var targetFrame = $("#" + corrispondingCodingTab);
	targetFrame.show();
	if (selectedTab.attr("filename") != undefined){
		document.title = "NotepadA   	 πŸ“ " + selectedTab.attr("filename");
	}else{
		document.title = "NotepadA   	 πŸ“ newfile";
	}
	
}

function findTabWithAttr(attr,value){
	return $('div['+attr+'="'+value+'"]').each(function() {
		return this;
	});
}

function loadAllSpecialCharacter(){
	$("#iscl").html("");
	for (var i =161; i < 1023; i++){
		if (i != 173){
			$("#iscl").append("<div class='scs' keyid='" + i +"'>" + String.fromCharCode(i) + "</div>");
		}
		
	}
}

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};


</script>
</body>
</html>