// Based on Sexy Undo Close

var settings = JSON.parse(localStorage.settings);

var pageNo = 0;
var popupLoaded = false;

var filterTimeOut;
var filterStrings;
var filterRegEx;

function createLink(id, url, pgTitle) {
  var link = document.createElement('a');
  link.href="";
  link.addEventListener('click',function(e){
	e.preventDefault();
	e.stopPropagation();
	//if middle mouse button click
	if (e.button == 1){ 
		showUrl(id,false); 
		loadText();
	}else{ 
		showUrl(id,true);
		loadText();
	}
  },false);
  if(settings.tooltipText){
	link.href = url;
	link.title = pgTitle;
  }else{
	link.title = url;
  }
  return link;
}

var nowtime,currentTime;
var content;

//--Detect double click
//store time of 1st click, open
localStorage.openTime = new Date().getTime();
//With Aura, 2nd click becomes close thus do dclick chk on close
window.onunload=function(){
	//store time of 2nd click, close
	localStorage.closTime = new Date().getTime();
	if (!settings.disableDClick){
		//difference btw the 2 clicks
		var timeDiff =  localStorage.closTime - localStorage.openTime;
		if (timeDiff<600){ 
			chrome.extension.getBackgroundPage().getLastTab();
			window.close();
			return;
		}
	}
};

function loadText(){

	content = document.getElementById("content");
	// Don't popup if there's nothing to show
	var n = localStorage.closedTabCount;
	
	nowtime = new Date();
	
	popupLoaded=false;

	if (settings.menuTop == true) content = document.getElementById("content2");
	if (settings.boldFont == true) content.className+=" bold";

	content.innerHTML="<center><b>"+chrome.i18n.getMessage("popup_loadMsg")+"</b></center>";
		
	if (n == 0){
		//console.log("No tabs");
		document.getElementById("tailenders").className="tailendersHide";
		document.getElementById("prev").style.visibility="hidden";
		document.getElementById("next").style.visibility="hidden";
		content.innerHTML=chrome.i18n.getMessage("popup_noTabsMsg");
	}else{
		//console.log("to LoadPage..");
		loadPage();
	}
	
	if((settings.showSearch == false && settings.showClear == false && settings.numLimit == settings.numItems)||n == 0) { document.getElementById("controls").style.display="none"; } else{
	//console.log("Controls show..");

		if (settings.showSearch == true){ 
			document.getElementById("searchQ").focus();
		}else {
			document.getElementById("searchQ").style.display="none";
			document.getElementById("searchholder").style.width="175px";
		}
		if (settings.showClear == true) {
			document.getElementById("clr").style.display="inline";
			document.getElementById("clrholder").style.width="64px";
			if(document.getElementById("tailenders").className=="tailendersHide"){
				document.getElementById("searchQ").style.width="210px";
			}else{
				document.getElementById("searchQ").style.width="150px";
			}
		} else {
			document.getElementById("clr").style.display="none";
			if (settings.showSearch == true) {
				document.getElementById("clrholder").style.width="0px";
			} else {
				document.getElementById("clrholder").style.width="64px";
			}
			if(document.getElementById("tailenders").className=="tailendersHide"){
				document.getElementById("searchQ").style.width="272px";
			}else{
				document.getElementById("searchQ").style.width="212px";
			}
		}

		if (filterStrings!=null) {
			document.getElementById("tailenders").className="tailendersShow";
			document.getElementById("delete").style.display="inline";
			document.getElementById("prev").style.display="none";
			document.getElementById("next").style.display="none";
			document.getElementById("clr").style.display="none";
			document.getElementById("clrholder").style.width="0px";
			document.getElementById("searchQ").style.width="210px";
		}else{
			document.getElementById("delete").style.display="none";
			document.getElementById("prev").style.display="inline";
			document.getElementById("next").style.display="inline";
		}
	
	}
}

function loadPage(){
	
	//console.log("LOAD PAGE");
	if (!popupLoaded) {
		content.innerHTML="";
		popupLoaded=true;
	}

	var items_to_display=settings.numItems;
	if (filterStrings!=null) items_to_display=1000;


	nowtime = new Date();
	currentTime = nowtime.getTime(); 
	//console.log("LOAD PAGE.");
	var min_limit = localStorage.minimumTabInc;

	for (var j = 0, i = localStorage.uniqueTabInc - 1; i>=0 && j<pageNo*items_to_display; i--) if (localStorage["ClosedTab-"+i]) j++;

	for (var j = 0; i>=min_limit && j<items_to_display; i--){
		var closedTab = localStorage["ClosedTab-"+i];
		if (closedTab){
			if (filterStrings==null || (filterStrings!=null && closedTab.multiFind(filterStrings))){
				//setTimeout(ShowEntry, 0,i,closedTab);
				ShowEntry(i,closedTab);
				j++;
			}
		}
	}

	if (filterStrings==null) {
		//console.log("No search");
		document.getElementById("tailenders").className="tailendersHide";
		document.getElementById("prev").style.visibility="hidden";
		document.getElementById("next").style.visibility="hidden";
		if (pageNo > 0) {
		//console.log("tailenders4");
		document.getElementById("tailenders").className="tailendersShow";
		document.getElementById("prev").style.visibility="visible";
		}
		if (localStorage.closedTabCount > (pageNo+1) * settings.numItems) {
		//console.log("tailenders5");
		document.getElementById("tailenders").className="tailendersShow";
		document.getElementById("next").style.visibility="visible";
		}
	}else{
		if (j==0) content.innerHTML="<center><b>"+chrome.i18n.getMessage("popup_noSearchResult")+" \'"+unescape(filterStrings.join(" "))+"\'</b></center>";
	}

}
function ShowEntry(i,closedTab) {

	if (!popupLoaded) return;
	
	var split = closedTab.split("%%");
	var tabTime = split[1];
	var tabUrl = split[2];
	var tabTitle = split[3];

	var text_link = createLink(i, tabUrl, tabTitle);
	var html;

	html="<img src=\"chrome://favicon/"+tabUrl+"\" alt=\""+tabUrl+"\" width=16 height=16>"; 

	if (filterStrings!=null) tabTitle=tabTitle.multiReplace(filterStrings);
	
	html+="<div class=\"titleTxt";
	if (settings.numLines!=0 && !isNaN(settings.numLines) && filterStrings==null) html+=" maxh"+settings.numLines+"";
	html+="\"> "+ tabTitle +"</div>";
	
	if (settings.showTime){
		var timeTextz;

		var difference = currentTime - tabTime; 
		var hoursDifference = Math.floor(difference/1000/60/60); 
		difference = difference - hoursDifference*1000*60*60; 
		var minutesDifference = Math.floor(difference/1000/60); 
		difference = difference - minutesDifference*1000*60; 
		var secondsDifference = Math.floor(difference/1000); 
		if ( hoursDifference < 1 &&  minutesDifference < 1 &&secondsDifference < 60) timeTextz = '<b>'+ secondsDifference + 's</b> ago'; 
		else if (hoursDifference < 1) timeTextz ='<b>'+ minutesDifference + ' min</b> ago'; 
		else if (hoursDifference < 4) timeTextz= '<b>' + hoursDifference + 'h ' + minutesDifference + 'min</b>'; 
		else if (hoursDifference < 24) timeTextz='<b>' + hoursDifference + 'h</b> ago'; 
		else {
			var daysDiff=Math.floor(hoursDifference/24);
			timeTextz='<b>' + daysDiff + ' days</b> ago'; 
		}
		html+="<span>"+timeTextz+"</span>";
	}
	
	var itm = document.createElement("div");
	itm.className = "item";
	
	var delBtn = document.createElement("div");
	delBtn.id = "del-"+i;
	delBtn.className = "del";
	delBtn.title = chrome.i18n.getMessage("popup_delbtn");
	delBtn.textContent = "×";
	delBtn.addEventListener('click',function(event){ 
		event.stopPropagation(); //click-shield!
		removeClosedTab(i); 
		location.reload(true);
	},false);
	
	itm.innerHTML=html;
	itm.appendChild(delBtn);
	text_link.appendChild(itm);
	content.appendChild(text_link);
}

function searchFor(string) {
	string = string.replace(/(\%)/g, "%25");
	string = string.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	string = stripVowelAccent(string);

	if ((filterStrings==null && string=="") || (filterStrings!=null && string==filterStrings.join(" "))) return;

	if (string==""){
		pageNo=0;
		filterStrings = null;
	}else{
		pageNo=0;
		//for(var i=0; i < filterStrings.length-1; i=i+1) { 
		string=string.toLowerCase();
		filterStrings = string.split(" "); 
	}
	clearTimeout(filterTimeOut);
	filterTimeOut=setTimeout(loadText,200);
}
function next() {
	if (localStorage.closedTabCount > (pageNo+1) * settings.numItems) pageNo++;
	loadText();
}

function prev() {
	if (pageNo > 0) pageNo--;
	loadText();
}

function reset(){
	if (document.getElementById("searchQ").value!=""){
		document.getElementById("searchQ").value="";
		searchFor("");
	}else{
		resetData();
		pageNo = 0;
		window.close();
	}
}

function deleteFoundTabs(){
if (filterStrings==null) return;
	  for (i = localStorage.uniqueTabInc - 1; i>=0; i--){
		var closedTab = localStorage["ClosedTab-"+i];
		if (closedTab){
			if (filterStrings!=null && closedTab.multiFind(filterStrings)){
				delete localStorage["ClosedTab-"+i];
				localStorage.closedTabCount --;
			}
		}
	}
	loadText();
	setBadge();
}

function stripVowelAccent(str)
{
	var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
		/[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
		/[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
		/[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
		/[\xD9-\xDB]/g, /[\xF9-\xFB]/g ];

	var repChar=['A','a','E','e','I','i','O','o','U','u'];

	for(var i=0, j=rExps.length; i<j; ++i)
		str=str.replace(rExps[i],repChar[i]);

	return str;
}

String.prototype.multiFind = function ( strings ) {
//console.log("this-"+this);
	var str = this, i;
	str = stripVowelAccent(str);
	str = str.toLowerCase();
	if(settings.searchMode!=3){
		var splitStr = str.split("%%");
		if(settings.searchMode==1) str = splitStr[3];
		if(settings.searchMode==2) str = splitStr[2];
	}
	var foundAmount=0;
	for (i = 0, j = strings.length; i < j; i++ ) {
	//console.log("str-"+str+"||strings[i]-"+strings[i]);
		if (str.indexOf(strings[i])!= -1) foundAmount++;
	}
	return (foundAmount==strings.length);
};
String.prototype.multiReplace = function ( strings ) {
	var str_real = this, i;
	var str = str_real;
	str = stripVowelAccent(str);
	str = str.toLowerCase();
	var position=-1;
	for (i = 0, j = strings.length; i < j; i++ ) {
		position = str.indexOf(strings[i]);
		if (position!= -1) {
			str_real = str_real.substr(0,position) + "<u>" + str_real.substr(position, strings[i].length) + "</u>" + str_real.substr(position + strings[i].length); 
			str = stripVowelAccent(str_real).toLowerCase();
		}
		//str = str.replace(new RegExp('(' + strings[i] + ')','gi'), replaceBy);
	}
	return str_real;
};

//keyboard navigation
var selLink = -1;
document.onkeydown = function(evt) {
    evt = evt || window.event;
	//left right
	if (evt.keyCode == 37||evt.keyCode == 39) { 
		if (evt.keyCode == 37) { 
           prev();
        }
        if (evt.keyCode == 39) { 
           next();
        }
	}
	//up down
	else if (evt.keyCode == 38||evt.keyCode == 40) {
        if (evt.keyCode == 38) { 
           if(selLink>0) selLink--;
		   else selLink=(document.links.length-1);
        }
        if (evt.keyCode == 40) { 
           if(selLink<(document.links.length-1)) selLink++;
		   else selLink=(0);
        }
		document.links[selLink].focus();
	}
	//enter
	else if (evt.keyCode == 13) {
		document.links[selLink].click();
	}
	else {
		document.getElementById('searchQ').focus();
	}
};

//populate popup and bind functions to buttons on popup load
document.addEventListener('DOMContentLoaded', function () {

loadText();

document.getElementById('clr').addEventListener('click',reset);
document.getElementById('clr').title = chrome.i18n.getMessage("popup_clrbtn_tooltip");
document.getElementById('clr').innerHTML = chrome.i18n.getMessage("popup_clrbtn");
document.getElementById('searchQ').addEventListener('keyup',function(){
 searchFor(document.getElementById('searchQ').value);
});
document.getElementById('searchQ').title = chrome.i18n.getMessage("popup_search_tooltip");
document.getElementById('delete').addEventListener('click',deleteFoundTabs);
document.getElementById('delete').title = chrome.i18n.getMessage("popup_delbtn_tooltip");
document.getElementById('delete').innerHTML = chrome.i18n.getMessage("popup_delbtn");
document.getElementById('prev').addEventListener('click',prev);
document.getElementById('prev').title = chrome.i18n.getMessage("popup_prvbtn_tooltip");
document.getElementById('next').addEventListener('click',next);
document.getElementById('next').title = chrome.i18n.getMessage("popup_nxtbtn_tooltip");

});