// copyright 2007 Dean Laforet
// do not modify without permission.

var showTitle = "yes";  //   Show path to file when hovered. yes or no
var makeIconBigger = "yes";  // sets whether the icons grow when hovered over. yes or no
var showHighlight = "no"; //sets whether the icon is highlited when hovered. yes or no

// do not change below this line
var gadgetPath = System.Gadget.path;
var errorImage = gadgetPath+"\\images\\error_24x24.png";
var myComp = gadgetPath+"\\images\\myComp.ico";
var control = gadgetPath+"\\images\\control.ico";
var network = gadgetPath+"\\images\\network.ico";
var ie = gadgetPath+"\\images\\ie.ico";
var rbEmpty = gadgetPath+"\\images\\rbEmpty.ico";
var rbFull = gadgetPath+"\\images\\rbFull.ico";
var imgSmall = 24;
var imgLarge = 28;
var targetLink = 0;  // 0=target file
var perRow = 4; // do not change yet. coming soon

var oShell = new ActiveXObject("WScript.Shell");
var oFSO = new ActiveXObject("Scripting.FileSystemObject");
var bDebug = oFSO.FileExists(gadgetPath+"\\debug.txt");
try{
	if (bDebug)
		var debugLogFile = oFSO.OpenTextFile(gadgetPath+"\\debug.txt", 2);
} catch(err) {bDebug = false; debugLog("Open debug.txt error"+err.name+" - "+err.message)}

function debugLog(outStr) 
{
	try{
		System.Debug.outputString(outStr);
		if (bDebug)
			debugLogFile.WriteLine(outStr);
	} catch(err) {}
}

onerror = handleErr;

function handleErr(msg,url,l) 
{
	debugLog("Javascript error: "+msg+" - on line: "+l);
}

var objWMIService = GetObject("winmgmts:\\\\.\\root\\CIMV2");
var osItems = objWMIService.ExecQuery("SELECT * FROM Win32_OperatingSystem");
var osEnum = new Enumerator(osItems);
for (; !osEnum.atEnd(); osEnum.moveNext()) 
{
	var osItem = osEnum.item();
	var osVersion = osItem.Caption;
}

foundVista = false;
searchVista = osVersion.search(/Vista/i);

if (searchVista >= 0) 
{ 
	foundVista = true; 
	var winPath = System.Shell.knownFolderPath("Windows");
	var wExists = oFSO.FileExists(winPath+"\\explorer.exe");
	if (wExists)
	{
		myComp = winPath+"\\explorer.exe";
		control = winPath+"\\system32\\control.exe";
	}

	var pfPath = System.Shell.knownFolderPath("ProgramFiles");
	var pfExists = oFSO.FileExists(pfPath+"\\Internet Explorer\\iexplore.exe");
	if (pfExists)
	{
		ie = pfPath+"\\Internet Explorer\\iexplore.exe";
	}
}

document.onreadystatechange = function()
{
try{
    if(document.readyState=="complete")
    {
        System.Gadget.settingsUI = "settings.html";
        System.Gadget.onSettingsClosed = settingsClosed;
//		System.Gadget.onUndock = resizeGadget;
//		System.Gadget.onDock = resizeGadget;        
		System.Shell.RecycleBin.onRecycleBinChanged = updateRB;
		getSettings();
		createLayout();
    }        
} catch(err) {debugLog("onreadystatechange: "+err.name+" - "+err.message)}
}

function getSettings()
{
try{
	var firstTime = System.Gadget.Settings.read("FirstTime");
	if (!firstTime)
	{
		linksList = new Array();  
		var dExists = oFSO.FileExists(gadgetPath+"\\defaults.txt");
		if (dExists) {
			var defaultFile = oFSO.OpenTextFile(gadgetPath+"\\defaults.txt", 1, false);
			try{
			index = 0;
			for (var i = 0; !defaultFile.AtEndOfStream; i++) {
				testLink = defaultFile.ReadLine();
				
				if (testLink == "My Computer" || testLink == "Control Panel Category" || testLink == "Control Panel Classic" || testLink == "Control Panel VAIO" || testLink == "Internet Explorer" || testLink == "Recycle Bin" || testLink == "Network" || testLink == "Network VAIO" || testLink == "Internet Explorer Favorites" || testLink == "Firefox Favorites")
				{
					isGood = true;
				}
				else
				{
					isGood = ( fileExists(testLink) ? true : false );
				}
				
				if (isGood)
				{
					linksList[index] = testLink;
					index++;
				}
				
			}
			defaultFile.Close();
			} catch(err) {debugLog("Open default.txt error"+err.name+" - "+err.message)}
		}
		else
		{
			linksList[0] = "My Computer";
			if (foundVista)
			{
				linksList[1] = "Control Panel Classic";
			}
			else
			{
				linksList[1] = "Control Panel VAIO";
			}
			linksList[2] = "Internet Explorer";
			linksList[3] = "Recycle Bin";
		}
		
		System.Gadget.Settings.write("Links", linksList.toString());
		System.Gadget.Settings.write("FirstTime", true);
		System.Gadget.Settings.write("TargetLink", targetLink);
	}
	else
	{   
		var targetLink = System.Gadget.Settings.read("TargetLink");
		var linksString = System.Gadget.Settings.read("Links");
		linksList = linksString.split(",", linksString.length);
	} 
} catch(err) {debugLog("GetSettings: "+err.name+" - "+err.message)}
}

function createLayout()
{
try{
	var nShortcuts = linksList.length;
	document.body.style.marginTop = "22px";
	document.body.style.marginLeft = "4px";
	if ( nShortcuts < 5) 
	{ 
		document.body.style.marginTop = "34px"; 
		if ( nShortcuts == 1) {	document.body.style.marginLeft = "51px";}
		if ( nShortcuts == 2) {	document.body.style.marginLeft = "35px";}
		if ( nShortcuts == 3) {	document.body.style.marginLeft = "20px";}
		divHeight = 60;
	}
	else
	{
		divHeight = Math.ceil(nShortcuts/perRow)*30+6;
	}
	
	document.body.style.height = divHeight + "px"; 

	var imgCounter = 0;
	outputDIV.innerHTML = "";
	for (var i=0; i < linksList.length; ++i)
	{
		var imageID = "img"+i;
		thisPath = linksList[i];
		
		thisTitle = oFSO.GetFileName(thisPath);
		if (thisTitle == "")
		{
			thisTitle = "Drive - "+thisPath;
		}
		
		var tmpPath = thisPath;

		fileExtension = oFSO.GetExtensionName(thisPath).toLowerCase();
		if (fileExtension == "lnk")
		{
			oLink = oShell.CreateShortcut(thisPath);
			tmpPath = oLink.TargetPath;
			var targetLink = System.Gadget.Settings.read("TargetLink");
			if (targetLink == 0)
			{
				if (oFSO.GetFileName(tmpPath).toLowerCase() != "hlsw.exe")
				{
					thisPath = tmpPath;
					linksList[i] = thisPath;
					System.Gadget.Settings.write("Links", linksList.toString());
				}
			}
			else if (targetLink == 2) { tmpPath = thisPath; }
			else {}
			
		}

		if (showTitle == "no") { thisTitle = ""; }

		if (thisPath == "My Computer")
		{
			filePath = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}";
			src = "gimage:///" + myComp + "?width=64&height=64";
		}
		else if (thisPath == "Network")
		{
			filePath = "::{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}";
			src = "gimage:///" + network + "?width=64&height=64";
		}
		else if (thisPath == "Network VAIO")
		{
			filePath = "::{7007ACC7-3202-11D1-AAD2-00805FC1270E}";
			src = "gimage:///" + network + "?width=64&height=64";
		}
		else if (thisPath == "Control Panel Category")
		{
			filePath = "::{26EE0668-A00A-44D7-9371-BEB064C98683}";
			src = "gimage:///" + control + "?width=64&height=64";
		}
		else if (thisPath == "Control Panel Classic")
		{
			filePath = "::{21EC2020-3AEA-1069-A2DD-08002B30309D}";
			src = "gimage:///" + control + "?width=64&height=64";
		}
		else if (thisPath == "Control Panel VAIO")
		{
			filePath = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\::{21EC2020-3AEA-1069-A2DD-08002B30309D}";
			src = "gimage:///" + control + "?width=64&height=64";
		}
		else if (thisPath == "Internet Explorer")
		{
			filePath = "::{871C5380-42A0-1069-A2EA-08002B30309D}";
			src = "gimage:///" + ie + "?width=64&height=64";
		}
		else if (thisPath == "Recycle Bin")
		{
			filePath = "::{645FF040-5081-101B-9F08-00AA002F954E}";
			src = "gimage:///" + rbEmpty + "?width=48&height=48";
			imageID = "rbHere";    
		}
		else if (thisPath == "Internet Explorer Favorites")
		{
			filePath = thisPath;
			src = "images/ieFav.png";
		}
		else if (thisPath == "Firefox Favorites")
		{
			filePath = thisPath;
			src = "images/ffFav.png";
		}
		else
		{
			filePath = thisPath;
			src = "gimage:///" + ( fileExists(filePath) ? tmpPath : errorImage ) + "?width=64&height=64";        
		}

		outputDIV.innerHTML += "<div id=\"cell"+i+"\" class=\"cell\"><img src=\""+src+"\" onclick=\"execLink()\" link=\""+filePath+"\" width=\""+imgSmall+"px\" height=\""+imgSmall+"px\" onmouseover=\"hiliteLink()\" onmouseout=\"unHiliteLink()\" title=\""+thisTitle+"\" id=\""+imageID+"\"></div>";

		imgCounter++;
		if (imgCounter == perRow && i != (linksList.length-1))
		{
			imgCounter = 0;
			outputDIV.innerHTML += "<div class=\"clear\"></div>";
		}

	}

	updateRB();
	
} catch(err) {debugLog("CreateLayout: "+err.name+" - "+err.message);}
}

function fileExists(fullFileName)
{
    var bRetVal = true;
    try
    {
        var obj = System.Shell.itemFromPath(fullFileName);
    }
    catch(err)
    {
        bRetVal = false;
        debugLog("FileExists: "+err.name+" - "+err.message)
    }
    return bRetVal;
}

function execLink()
{
try{
    var img = event.srcElement;
    if (img.link == "::{645FF040-5081-101B-9F08-00AA002F954E}")
    {
		recycleBin();
		img.blur();
    }
    else if (img.link == "Internet Explorer Favorites")
    {
		showFavsIE();
		img.blur();
    }
    else if (img.link == "Firefox Favorites")
    {
		showFavsFF();
		img.blur();
    }
    else
    {
		System.Shell.execute(img.link);
		img.blur();
    }
} catch(err) {debugLog("execLink: "+err.name+" - "+err.message)}
}

function recycleBin()
{
try{
	System.Gadget.Flyout.file = "flyoutRB.html";
	System.Gadget.Flyout.show = !System.Gadget.Flyout.show;
} catch(err) {debugLog("recycleBin: "+err.name+" - "+err.message)}
}

function updateRB()
{
try{
	var link = document.getElementById("rbHere");
	if(link)
	{
		binCount = System.Shell.RecycleBin.fileCount + System.Shell.RecycleBin.folderCount;
		if (binCount == 0)
		{
			link.src = "gimage:///" + rbEmpty + "?width=48&height=48";
		}
		else
		{
			link.src = "gimage:///" + rbFull + "?width=48&height=48";
		}
	}
} catch(err) {debugLog("updateRB: "+err.name+" - "+err.message)}
}

function showFavsIE()
{
try{
	System.Gadget.Flyout.file = "flyoutFavIE.html";
	System.Gadget.Flyout.show = !System.Gadget.Flyout.show;
} catch(err) {debugLog("showFavsIE: "+err.name+" - "+err.message)}
}

function showFavsFF()
{
try{
	System.Gadget.Flyout.file = "flyoutFavFF.html";
	System.Gadget.Flyout.show = !System.Gadget.Flyout.show;
} catch(err) {debugLog("showFavsFF: "+err.name+" - "+err.message)}
}

function fileDragDropped() {
try{
    var  sFile;
    for (var i=0; System.Shell.itemFromFileDrop(event.dataTransfer, i) != null; i++)
    {
        sFile = System.Shell.itemFromFileDrop(event.dataTransfer, i).path;
        addOneToList(sFile);
    }
	System.Gadget.Settings.write("Links", linksList.toString() );
	createLayout();
} catch(err) {debugLog("fileDragDropped: "+err.name+" - "+err.message)}
}

function addOneToList(newOne) {
try{
	var n = linksList.length;
	linksList[n] = newOne;
} catch(err) {debugLog("addOneToList: "+err.name+" - "+err.message)}
}

function hiliteLink()
{
try{
    var img = event.srcElement;
    if (img.link != null)
    {
		if (showHighlight=="yes") {
           img.style.backgroundImage = "url(images/highlight.png)";
        }
        if (makeIconBigger=="yes") {
           img.style.width = imgLarge+"px";
           img.style.height = imgLarge+"px";
        }
        img.style.cursor = "hand";
        
        if (img.link == "::{645FF040-5081-101B-9F08-00AA002F954E}")
        {
			rbCount = System.Shell.RecycleBin.fileCount + " files, " + System.Shell.RecycleBin.folderCount + " folders";
			img.title = rbCount;
        }
        
    }
    else    
    {
        event.returnValue = false;
    }
} catch(err) {debugLog("HiliteLinks: "+err.name+" - "+err.message)}
}

function unHiliteLink()
{
try{
    var img = event.srcElement;
    if (img.link != null)
    {
        img.style.backgroundImage="";
        if (makeIconBigger=="yes") {
           img.style.width = imgSmall+"px";
           img.style.height = imgSmall+"px";
        }
        img.style.cursor = "default";
    }
} catch(err) {debugLog("UnhiliteLinks: "+err.name+" - "+err.message)}
}

function settingsClosed()
{
try{
	var linksString = System.Gadget.Settings.read("Links");
	if (linksString != "none")
	{   
		linksList = linksString.split(",", linksString.length);
	} 
	else { linksList = new Array(); }
	createLayout();
} catch(err) {debugLog("SettingsClosed: "+err.name+" - "+err.message)}
}
