var favType = "ie";			// Use ie or ff to retrieve favorites from different systems
var oFSO = new ActiveXObject("Scripting.FileSystemObject");
var oShell = new ActiveXObject("WScript.Shell");
var ie_favDir = oShell.SpecialFolders("Favorites");
var ff_favDir = oShell.SpecialFolders("Appdata")+"\\Mozilla\\Firefox";
var ff_ProfileDir;
var ff_bookmarkFile;
var ffItemsArray;
var favListArea;
var hiddenContentArea;
var dirCount = 0;

// Get the favorites type
//var favMeth = System.Gadget.Settings.read("favType");
//if(favMeth != "none" && favMeth != "" && favMeth != null) favType = favMeth;

// Setup trim
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

window.onload = function()
{
	favListArea = document.getElementById('favListArea');
	hiddenContentArea = document.getElementById('hiddenContentArea');
	
	// Get favs and folders
	if(favType == "ie") displayLinksAndDirs(ie_favDir, "favListArea", 0);
	else 
	{
		// We need to get the profile to use for FF
		var profilesFile = ff_favDir+"\\profiles.ini";
		if(oFSO.FileExists(profilesFile))
		{
		    // Get the directory to the FireFox profile to use
			ts = oFSO.OpenTextFile(profilesFile, 1);
			line = ts.ReadLine();
			while(line != null)
			{
				
				if(line.substr(0, 5) == "Path=")
				{
					chunks = line.split("=");
					profileDir = chunks[chunks.length - 1];
					ff_ProfileDir = ff_favDir+"\\"+profileDir.replace(/\//g, '\\');
					ff_bookmarkFile = ff_ProfileDir+"\\bookmarks.html";
					break;
				}
				line = ts.ReadLine();
			}
			ts.close();
			
			if(oFSO.FileExists(ff_bookmarkFile))
			{
				// Go through the bookmarks file and get all files/folders
				var bookDirs = new Array();
				var bookFiles = new Array();
				bookFile = oFSO.OpenTextFile(ff_bookmarkFile, 1);
				//bookLine = bookFile.ReadLine();
				ffItemsArray = new Array();
				var ff_dirCount = -1;
				while(!bookFile.AtendOfStream)
				{
					bookLine = bookFile.ReadLine();
					lnTmp = bookLine.trim();
					
					if(lnTmp.substr(0, 5) == "</DL>")  ff_dirCount--;
					else if(lnTmp.substr(0, 4) == "<DL>")  ff_dirCount++;
					if(lnTmp.substr(0, 4) == "<DT>")
					{
						// This is a file/folder element
						lnTmp = lnTmp.substr(4);
						
						// Put the line in the hidden area so we can access the info
						itemInfo = new Array();
						if(lnTmp.substr(0, 3) == "<H3")
						{
							hiddenContentArea.innerHTML = lnTmp;
							
							// We got a "folder" here
							newElem = hiddenContentArea.firstChild;
							itemInfo['type'] = "dir";
							itemInfo['title'] = newElem.innerHTML;
							itemInfo['dir_level'] = ff_dirCount;
							ffItemsArray[ffItemsArray.length] = itemInfo;
						}
						else if(lnTmp.substr(0, 2) == "<A")
						{
							hiddenContentArea.innerHTML = lnTmp;
							
							// We got a "folder" here
							newElem = hiddenContentArea.firstChild;
							itemInfo['type'] = "file";
							itemInfo['title'] = newElem.innerHTML;
							itemInfo['dir_level'] = ff_dirCount;
							itemInfo['url'] = newElem.href;
							ffItemsArray[ffItemsArray.length] = itemInfo;
						}
						//ffItemsArray[ffItemsArray.length] = lnTmp;
					}
					//bookLine = bookFile.ReadLine();
				}
				bookFile.close();
				hiddenContentArea.innerHTML = "";
				
				// Iterate through items and set their parent id's
				for(var i = 0; i < ffItemsArray.length; i++)
				{
					ffItemsArray[i]['parent_id'] = getFFitemParentId(i);
				}
				
				/*
				// Go through the line array extract info
				var uniqueDir = 0;
				for(var i = 0; i < ffItemsArray.length; i++)
				{
					currItem = ffItemsArray[i];
					indent = "<img src=\"images/fill.png\" width=\""+(currItem['dir_level']*20)+"\" height=\"1\" border=\"0\" />";
					
					// Get image
					if(currItem['type'] == "dir")
					{
						uniqueDir++;
						contentOut = "<nobr>"+indent+"<span onclick=\";\" style=\"cursor: pointer;\"><img src=\"images/folder.png\" width=\"16px\" height=\"16px\" align=\"absmiddle\" /> "+currItem['title']+"</span></nobr><br /><div id=\"dir_"+uniqueDir+"\" style=\"display: none;\"></div>"; 
					}
					else
					{
						contentOut = "<nobr>"+indent+"<span onclick=\"\" style=\"cursor: pointer;\"><img src=\"images/url.png\" width=\"16px\" height=\"16px\" align=\"absmiddle\" /> "+currItem['title']+"</span></nobr><br />";	
					}
					
					//favListArea.innerHTML += contentOut;
					favListArea.innerHTML += i+": "+ffItemsArray[i]['title']+", LEVEL: "+ffItemsArray[i]['dir_level']+", PARENT: "+ffItemsArray[i]['parent_id']+"<br /><br />";
					
				}
				*/
				
				// Display initial folder levels
				displayFFbookmarks("favListArea", -1);
			}
			
			//displayLinksAndDirs(ff_favDir, "favListArea", 0);
		}
	}
	
	document.body.style.height = (getDimension(favListArea, "y") + 10) + "px";
	document.body.style.width = (getDimension(favListArea, "x") + 10) + "px"; 
}

// Get the parent folder for an item
function getFFitemParentId(itemId)
{
	// The first folder with a lower id num is the parent folder
	var parentId = -1;
	for(var z = itemId - 1; z > -1; z--)
	{
		if(ffItemsArray[z]['dir_level'] < ffItemsArray[itemId]['dir_level'])
		{
			parentId = z;
			break;
		}
	}
	return parentId;
}

// Hide or show the sub links for a folder in FF
function toggleFFlinkDisplay(displayElementId, parentIdNum)
{
	var displayObj = document.getElementById(displayElementId);
	if(displayObj.style.display == "none")
	{
		// Show items
		displayFFbookmarks(displayElementId, parentIdNum);
	}
	else
	{
		// Hide items
		displayObj.style.display = "none";
	}
}

// Display FF bookmarks
function displayFFbookmarks(displayElementId, parentIdNum)
{
	var displayObj = document.getElementById(displayElementId);
	displayObj.style.display = "";
	var contentOut = "";
	
	// Go through the line array extract info
	for(var i = 1; i < ffItemsArray.length; i++)
	{
		currItem = ffItemsArray[i];
		if(currItem['parent_id'] != parentIdNum) continue;
		indent = "<img src=\"images/fill.png\" width=\""+(currItem['dir_level']*20)+"\" height=\"1\" border=\"0\" />";
		
		// Get image
		if(currItem['type'] == "dir") contentOut += "<nobr>"+indent+"<span onclick=\"toggleFFlinkDisplay('ffdir_"+i+"', '"+i+"');\" style=\"cursor: pointer;\"><img src=\"images/folder.png\" width=\"16px\" height=\"16px\" align=\"absmiddle\" /> "+currItem['title']+"</span></nobr><br /><div id=\"ffdir_"+i+"\" style=\"display: none;\"></div>"; 
		else contentOut += "<nobr>"+indent+"<span onclick=\"System.Shell.execute('"+currItem['url']+"');\" style=\"cursor: pointer;\"><img src=\"images/ieFav.png\" width=\"16px\" height=\"16px\" align=\"absmiddle\" /> "+currItem['title']+"</span></nobr><br />";	
	}
	displayObj.innerHTML = contentOut;
}

onerror = handleErr; 
function handleErr(msg, url, l) {
   //debugLog("Javascript error: " + msg + " - on line: " + l); 
   favListArea.innerHTML += "ERROR: " + msg + " - on line: " + l;
   }

// Hide or show the sub links for a folder
function toggleLinkDisplay(dp, displayElement, level)
{
	displayObj = document.getElementById(displayElement);
	if(displayObj.style.display == "none")
	{
		// Show items
		displayLinksAndDirs(dp, displayElement, level);
	}
	else
	{
		// Hide items
		displayObj.style.display = "none";
	}
}

// Display links and folders inside a given folder
function displayLinksAndDirs(dp, displayElement, level)
{
	displayElement = document.getElementById(displayElement);
	displayElement.style.display = "";
	contentOut = "";
	oFavDir = oFSO.GetFolder(dp);
	
	// Indent if needed
	indent = "";
	if(level > 0) indent = "<img src=\"images/fill.png\" width=\""+(level*20)+"\" height=\"1\" border=\"0\" />";
	
	
	// Get folders
	favDirs = getSubDirs(dp);
	for(favItem in favDirs) 
	{ 
		dirCount++;
		dname = favDirs[favItem];
		
		d = oFSO.GetFolder(dname);
		if(d.attributes == 18) continue;
		dirPath = d.Path; 
		
		arFileName = dirPath.split("\\");
		label = arFileName[arFileName.length - 1];
		label = label.split(".")[0];
		
		dirPath = dirPath.replace(/\\/g, '\\\\');
		dirPath = dirPath.replace(/\'/g, '\\\'');
		levelUp = parseInt(level) + 1;
		contentOut += "<nobr>"+indent+"<span onclick=\"toggleLinkDisplay('"+dirPath+"', 'dir_"+dirCount+"', '"+levelUp+"');\" style=\"cursor: pointer;\"><img src=\"images/folder.png\" width=\"16px\" height=\"16px\" align=\"absmiddle\" /> "+label+"</span></nobr><br /><div id=\"dir_"+dirCount+"\" style=\"display: none;\"></div>"; 
	}
	
	// Get files
	favFiles = getSubFiles(dp);
	for(favItem in favFiles) 
	{ 
		fname = favFiles[favItem];
		
		f = oFSO.GetFile(fname);
		if(f.attributes == 38) continue;
		filePath = f.Path; 
		
		arFileName = filePath.split("\\");
		label = arFileName[arFileName.length - 1];
		label = label.split(".")[0];
		
		filePath = filePath.replace(/\\/g, '\\\\');
		filePath = filePath.replace(/\'/g, '\\\'');
		contentOut += "<nobr>"+indent+"<span onclick=\"System.Shell.execute('" + filePath + "');\" style=\"cursor: pointer;\"><img src=\"images/ieFav.png\" link=\"" + filePath + "\" width=\"16px\" height=\"16px\" align=\"absmiddle\" /> "+label+"</span></nobr><br />"; 
	}
	displayElement.innerHTML = contentOut;
}

// Get dimension of an element
function getDimension(element, dim) {
   var x, y; 
   if(element.innerHeight) // all except Explorer
   {
      x = element.innerWidth; 
      y = element.innerHeight; 
      }
   else // other Explorers
   {
      x = element.offsetWidth; 
      y = element.offsetHeight; 
      }
   if(dim == "x") return x; 
   return y; 
   }
   
   
function getSubDirs(s) 
{ 
	//s = trim(s) || 'C:';
	//s = s.replace(/\\/g, '\\\\');
	var e, f, i, r = [];
	if(oFSO.FolderExists(s))
	{
		f = oFSO.GetFolder(s);
		e = new Enumerator(f.SubFolders);
		for(; !e.atEnd(); e.moveNext())
		{
			if((i = e.item())) r.push(i); 
		}
	}
	return r;
}

function getSubFiles(s) 
{ 
	var e, f, i, r = [];
	if(oFSO.FolderExists(s))
	{
		f = oFSO.GetFolder(s);
		e = new Enumerator(f.files);
		for(; !e.atEnd(); e.moveNext())
		{
			if((i = e.item())) r.push(i); 
		}
	}
	return r;
}