window.addEventListener("load", updateIcon);

regExistingTabs();

chrome.runtime.onStartup.addListener(function() {
//console.log("LOAD");
	var settings = JSON.parse(localStorage.settings);
	if (!settings.saveHistory) {
		resetData(); 
	}
	else {
		tabListCleanup();
		setBadge();
	}
	//console.log("START: "+Object.keys(settings).length);
});

chrome.runtime.onInstalled.addListener(function(runInfo) {
	if (runInfo.reason=="install") {
		localStorage.settings = JSON.stringify({ "showClear": true, "showBadge": false, "showTime": true, "showSearch": true, "searchMode": 1, "bold": false, "saveHistory": true, "ctrlZ": false, "menuTop": false, "disableDClick": false, "tooltipText": true, "numLimit":10, "numItems":10, "numLines":1, "altBut": false, "hkey1": 17, "hkey2": 90});
		
		localStorage.minimumTabInc = 0;
		localStorage.uniqueTabInc = 1;
		localStorage.closedTabCount = 0;
		localStorage.openTime = 0;
		localStorage.closTime = 0;
	}
	if (runInfo.reason=="update") {
	//update settings
		var settingsOld = JSON.parse(localStorage.settings);
	
		localStorage.removeItem("lastOpened");
		localStorage.openTime = 0;
		localStorage.closTime = 0;

		//if old length add new keys
		if(Object.keys(settingsOld).length == 15){
			localStorage.settings = JSON.stringify({ "showClear": settingsOld.showClear, "showBadge": settingsOld.showBadge, "showTime": settingsOld.showTime, "showSearch": settingsOld.showSearch, "searchMode": 1, "bold": settingsOld.boldFont, "saveHistory": settingsOld.saveHistory, "ctrlZ": settingsOld.ctrlZ, "menuTop": settingsOld.menuTop, "disableDClick": settingsOld.disableDClick, "tooltipText": settingsOld.tooltipText, "numLimit":settingsOld.numLimit, "numItems":settingsOld.numItems, "numLines":settingsOld.numLines, "altBut": settingsOld.altBut, "hkey1": 17, "hkey2": 90});
		}
	}
	setBadge();
});

function regExistingTabs(){
	chrome.tabs.query({}, function (tabs) {
		for(var t = 0; t<tabs.length; t++){
			addNewTab(tabs[t]);
		}
	});
}

function getLastTab(){
	//console.log("LAST TAB");
	var min_limit = localStorage.minimumTabInc;
	for (var i = localStorage.uniqueTabInc - 1; i>=min_limit ; i--){
		if (localStorage["ClosedTab-"+i]){
			showUrl(i,true);
			return;
		}
	}
}

// Replace HTML tags < >
function quote(s) {
	var s1=s;
	s1 = s1.replace(new RegExp("<", "g"), "&lt;");
	s1 = s1.replace(new RegExp(">", "g"), "&gt;");
	return s1;
}

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
	var settings = JSON.parse(localStorage.settings);
	if ((request == "ctrlZ")&&settings.ctrlZ) {
	// console.log("DISPLAY");
		getLastTab();
	}	
});

function addNewTab(tab) {
//console.log("ADD NEW "+tab.url);
	var re = /^(http:|https:|ftp:|file:)/;
	if (re.test(tab.url)) {
		var insertThis = tab.url+"%%";
		if(tab.title != null){
		insertThis += quote(tab.title);
		}else{
		insertThis += tab.url;}
		if (tab.incognito==true){
			insertThis += "%%1";
		}else{
			insertThis += "%%0";
		}
		localStorage["TabList-"+tab.id] = insertThis;
	}
}

function sendHotKey(tabId){
//console.log("send to tab "+tabId);
	var settings = JSON.parse(localStorage.settings);
	chrome.tabs.sendMessage(tabId, {key1:settings.hkey1,key2:settings.hkey2,active:settings.ctrlZ});
}

chrome.tabs.onActivated.addListener(function(activeInfo){
sendHotKey(activeInfo.tabId);
});

chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
sendHotKey(tabId);
addNewTab(tab);
});

chrome.tabs.onRemoved.addListener(function(tabId, info)  {
//console.log("REMOVED: "+tabId);
	if(localStorage["TabList-"+tabId]!=undefined){
		var settings = JSON.parse(localStorage.settings);
		// Should we record this tab?
		var splitValue = localStorage["TabList-"+tabId].split("%%");
		var url = splitValue[0];
		var re = /^(http:|https:|ftp:|file:)/;
		//if url is valid?
		if (url && re.test(url)) {
			var exists = -1;
			//go through all saved closed tabs
			for (i = localStorage["uniqueTabInc"] - 1; i>=0; i--){
				var closedTab=localStorage["ClosedTab-"+i];
				if (closedTab){
					var split = closedTab.split("%%");
					//if new removed exists in saved closed tabs
					if (split[2]===url){
						exists=i;
					}
					break;
				}
			}
			var digital = new Date();
			//if new removed exists in saved closed tabs, update time and tab id
			if (exists!=-1){
				localStorage["ClosedTab-"+exists] = tabId + "%%" + digital.getTime() + "%%" + localStorage["TabList-"+tabId];
			}
			//else new removed not in saved
			else{
				localStorage["ClosedTab-"+localStorage["uniqueTabInc"]] = tabId + "%%" + digital.getTime() + "%%" + localStorage["TabList-"+tabId];
				var uniqueTabInc = localStorage["uniqueTabInc"] ++;
				//localStorage["closedTabCount"];

				// Code for deleting last TAB, refresh minimumTabInc on overflow
				if (localStorage["closedTabCount"]>=settings.numLimit){
					for (i = localStorage["minimumTabInc"]; i<uniqueTabInc; i++){
						var closedTab=localStorage["ClosedTab-"+i];
						if (closedTab){
						//console.log("CLOSE TAB - limit "+settings.numLimit);
							localStorage["minimumTabInc"]=i;
							delete localStorage["ClosedTab-"+i];
							break;
						}
					}
				}else{
					localStorage["closedTabCount"] ++;
				}
				setBadge();
			}
		}
		delete localStorage["TabList-"+tabId];
	}
});

function tabListCleanup() {
	var storageSize = localStorage.length;
	for (var i = 0; i < storageSize; i++){
	//console.log("TLC"+i+" of "+storageSize+": "+localStorage.key(i));
		if(localStorage.key(i).indexOf("TabList-")!=-1) {localStorage.removeItem(localStorage.key(i));}
		storageSize = localStorage.length;
	}
}