//LOCALIZABLE STRINGS

var sTitle = "Guide de l'utilisateur Hewlett-Packard";

var sInstallTitle = sTitle + " - Installation";

var sDocOpenTitle = 'QBhpGuide.pdf';

var sInstallConfirm = "Voulez-vous installer le Guide de l'utilisateur HP sur votre disque dur ?";

var sUninstallConfirm = "Voulez-vous supprimer le Guide de l'utilisateur HP de votre disque dur ?";

var sInstallSuccess = "Votre Guide de l'utilisateur HP a été installé sur votre disque dur";

var sUninstallSuccess = "Votre Guide de l'utilisateur HP a été supprimé de votre disque dur";

var sReaderNotInstalled = "Vous ne pouvez pas utiliser le Guide de l'utilisateur HP sans installer le lecteur Acrobat Reader avec recherche.\n\nVoulez-vous reprendre l'installation de Acrobat Reader avec recherche ?";

//END LOCALIZABLE STRINGS
/* ======================================================================

JScript Source File -- Created with SAPIEN Technologies PrimalSCRIPT(TM)

NAME: UserGuide.js

AUTHOR: Ion C. Freeman

COMMENT: Contains the various UserGuide objects
		2/24 -- changed to encourage user to go through with entire Acrobat install 
========================================================================= */
//set variables useful to multiple objects
var docPathCD = ':\\HP\\support\\hpguide\\'; //the path to the docset on cd
var docPathDisk = 'c:\\hp\\support\\hpguide\\';
var installKey = 'HKCR\\Software\\HP\\HPUserGuide\\InstallToDisk'; //registry key to mark doc installation
var shortcutPath= '\\Start Menu\\HP User Guide.lnk';
var readerInstallPath = ':\\AcrobatReaderWithSearch32e301.exe'; //the path to the install exe for reader on cd
var cdrom = 4; //define the CD-ROM drive constant
//the first argument is the name of the object to create
//the second argument is the function to call on that object
//the remaining arguments are the arguments to that function
var args = WScript.Arguments;
var sArgs = '';
var aCDDrive = GetCDRomDrives();
switch(args.length){
case (0):
	break;
default:
	for(var iArg = 2; iArg < args.length; iArg++)
		sArgs += args(iArg) + ','
	sArgs = sArgs.replace(/,$/,''); //take off the last comma
	sArgs = '.' + args(1) + '(' + sArgs + ')';
case (1):
	var command = 'new ' + args(0) + '()' + sArgs;
	var obj = eval(command);
}
//***************************************************************
//UGProxy
function UGProxy(){

	if(!new UGLoad().main()){
		var shl = WScript.CreateObject("WScript.Shell");
		var path = WScript.ScriptFullName.replace(/[^\\]*$/,'');
		shl.Run('"' + path + 'UGDlgBx.exe"', 1, false);
	}
}

//***************************************************************
//UGLoad
function UGLoad(){	//set some constants
	this.docStartPage = sDocOpenTitle;
	this.docPathCD = docPathCD;
	this.docPathDisk = docPathDisk;
	this.readerInstallPath = readerInstallPath;
	//get a shell
	this.shl = WScript.CreateObject('WScript.Shell');
	//access the file system
	this.fso = WScript.CreateObject('Scripting.FileSystemObject');
	//define interface:
	//load the documentation
	this.main = loadDocs;
	//check if the docs are on the disk
	this.checkInstallKey = doCheckInstallKey;
	//check if the acrobat reader is installed
	this.checkReaderInstall = doCheckReaderInstall;
	//install the acrobat reader
	this.installReader = doInstallReader;
	//check for a start menu link
	this.checkStartMenu = doCheckStartMenu;
	//add a start menu link
	this.addStartMenu = doAddStartMenu;
	this.onCD = doOnCD;
}
function loadDocs(){
	var cddrive; // if I need to interact with a cd-rom drive, store its letter here
	var inst = new UGInstall();//get a uginstall object for enforcing conformity
	var path = this.checkInstallKey();
	if (null == path) { //try to find the correct cd-rom drive
		//if there's no such file, return false
		for(var iDrv = 0; iDrv < aCDDrive.length; iDrv++)
			if(this.fso.FolderExists(aCDDrive[iDrv] + this.docPathCD))
				cddrive = aCDDrive[iDrv];
		if(null == cddrive) //if I didn't find a likely drive
			return false;	//fail
		this.docPathCD = cddrive + this.docPathCD;
		path = this.docPathCD;
		//check if I'm running from the CD Rom -- copy all the cd files to the hard drive if I am
		if(this.onCD()){
			inst.compareFiles(this.docPathCD, this.docPathDisk, true);
		}
	}
	else //update docPathDisk
		this.docPathDisk = path;
	//make sure the index appears on the hard drive
	if(null != cddrive){
		var mitten = new Array('Index\\');
		for(var i=0; i< mitten.length; i++){
			var mit = mitten[i];
			inst.compareFiles(this.docPathCD + mit, this.docPathDisk + mit);
		}
	}
	path += this.docStartPage;
	//if there's no such file, fail
	if(!this.fso.FileExists(path))
		return false;
	//WScript.Echo(path + ' exists!');
	if (!this.checkReaderInstall()){ //if reader's not installed, install it
		//if I found my documentation on a cd drive, prepend its drive letter
		if(null != cddrive){
			this.readerInstallPath = cddrive + this.readerInstallPath;
		}else{
			//look for the reader install on all the cd-drives
			for(var iDrv = 0; iDrv < aCDDrive.length; iDrv++){
				if(this.fso.FileExists(aCDDrive[iDrv] + this.readerInstallPath))
					cddrive = aCDDrive[iDrv];
			}
			if(null == cddrive) { //if I didn't find a likely drive
				return false;	//fail
			}
			else	//if I did
				this.readerInstallPath = cddrive + this.readerInstallPath; //prepend it to the install exe path
		}
		//if I can't install reader, return false
		if(!this.installReader()){
			return false;
		}
	}
	//see that I've got a link in the file system
	if (!this.checkStartMenu()){
		var arg = '"' + this.docPathDisk + 'open.js"';
		this.addStartMenu(arg); 
	}		
	//send the doc path to the operating system to deal with (asynchronously)
	this.shl.Run('acrord32 "' + path + '"', 1, false);
	//this.shl.Popup(path);
	return true;
}
function doCheckInstallKey(){
	return getRegVal(installKey);
}
function doCheckReaderInstall(){
	//find the first acrobat reader with search key that defines data
	var keyName = 'HKEY_CURRENT_USER\\Software\\Adobe\\Acrobat\\AcroSrch\\3.0\\Options\\SortBy\\';
	var ret = getRegVal(keyName);
	//should there not be any such key, return false
	if (null == ret)
		return false;
	//if the user has uninstalled reader, the key will still be there!
	keyName= 'HKCR\\Software\\Adobe\\AcrobatReader\\InstallPath\\';
	ret = getRegVal(keyName);
	if (null == ret ||!this.fso.FileExists(ret +'\\AcroRd32.exe'))
		return false;
	//report success!
	return true;
}
function doInstallReader(){
	//if the cd's not in, of course, I can't install reader
	if(!this.fso.FileExists(this.readerInstallPath))
		return false;
	//fire the Acrobat Reader Install (wait for return, return 'true' for error code 0)
	if(0 != this.shl.Run(this.readerInstallPath,1,true))
		return false;
	//make sure that the user has completely installed reader
	/*get the install path from the registry -- if it's null, or the executable is not
		where it should be, try to get the user to install again
	*/
	var readerPath = getRegVal('HKCR\\Software\\Adobe\\AcrobatReader\\InstallPath\\');

	if(null == readerPath || !this.fso.FileExists(readerPath + '\\AcroRd32.exe')){
		//create a UGInstall object, just for the confirmation box
		var ugi = new UGInstall();
		if(ugi.confirm(sReaderNotInstalled, sTitle))
			return this.installReader();
		else	
			WScript.Quit();
	}
	return true;
}
//checks the start menu path for a link to the guide
function doCheckStartMenu(){
	if (!this.fso.FileExists(this.shl.ExpandEnvironmentStrings('%WINDIR%') + shortcutPath))
			return false;
	return true;
}
//puts a link to the specified file in the start menu path
function doAddStartMenu(target){
	var windows = this.shl.ExpandEnvironmentStrings('%WINDIR%');
	var stc = this.shl.CreateShortcut(windows + '\\start menu\\HP User\'s Guide.lnk');
	stc.TargetPath =  windows + '\\WScript.exe';
	stc.Arguments = target;
	var re = /\"?(.*\\)[^\\]*$/;
	target.match(re);
	stc.WorkingDirectory = RegExp.$1;
	//WScript.Echo(stc.WorkingDirectory);
	var icon = this.docPathDisk + 'HPUserGuide.ico';
	stc.IconLocation = icon;
	stc.Save();
	//FullName seems to be read only. Work around this with a file move.
	//var destination =  this.shl.ExpandEnvironmentStrings('%WINDIR%') + shortcutPath;
	//this.fso.GetFile(stc.FullName).Move(destination);
}
//checks if the script is running from the cd drive
function doOnCD(){
	if(cdrom == this.fso.GetDrive(this.fso.GetDriveName(WScript.ScriptFullName)).DriveType)
		return true;
	return false;
}
//***************************************************************
//UGInstall
function UGInstall(){
	this.preserveExtensions = new Array('vbs','js','exe','dll',/* 'pdx', 'log',*/ 'ico');
	this.selectiveDelete = doDeleteUnpreserved;
	this.docPathCD = docPathCD;
	this.shl = WScript.CreateObject('WScript.Shell');
	this.docPathDisk = docPathDisk;
	//WScript.Echo(this.docPathDisk);
	this.fso = WScript.CreateObject('Scripting.FileSystemObject');
	this.install = doInstall;
	this.getFolder = doGetFolder;	
	//compare files -- used to make sure that index.pdx on the disk is the same as the one on the cd
	this.compareFiles = doCompareFiles;
	//a confirmation dialog box
	this.confirm = doConfirm;
	//the function to check whether or not to keep or enforce a file
	this.preservable = testPreservable;
}
//@args whether (boolean) false to uninstall, true to install
function doInstall(whether){
	//ensure that this is what the user would like to do
	if(whether)
		confirmPrompt = sInstallConfirm;
	else
		confirmPrompt = sUninstallConfirm;
	if(!this.confirm(confirmPrompt))
		return false;
	//the key for uninstalling from the control panel
	var rkUninstall = 'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\HPUserGuide\\';
	if (whether){
		//install
		//copy the files -- assume the install has already been done if the cd is not in
		//test each cd for the file of interest (FOI)
		for(var iDrv = 0; iDrv < aCDDrive.length; iDrv++){
			if(this.fso.FolderExists(aCDDrive[iDrv] + this.docPathCD)){
				this.docPathCD = aCDDrive[iDrv] + this.docPathCD;
				var fol = this.fso.GetFolder(this.docPathCD);
				//ensure the target exists
				this.getFolder(this.docPathDisk);
				//fol.Copy(this.docPathDisk, true);
				this.compareFiles(this.docPathCD, this.docPathDisk);
				//write the 'install to disk' key
				this.shl.RegWrite(installKey, this.docPathDisk + '\\', 'REG_SZ');
				//write the uninstall information
				//write the name to display in add/remove programs
				this.shl.RegWrite(rkUninstall + 'DisplayName', 'Hewlett Packard User Guide', 'REG_SZ');
				//write the command for uninstalling the user guide -- call this function with argument 'false'
				this.shl.RegWrite(rkUninstall + 'UninstallString', 'WScript "' + this.docPathDisk + '\\UserGuide.js" UGInstall install false', 'REG_SZ');
				break; //get out of this for loop
			}
		}
		successReport = sInstallSuccess;
	} else {
		//remove the files
		if(null!=getRegVal(installKey)){
			this.selectiveDelete(this.fso.GetFolder(this.docPathDisk));
			//remove the 'install to disk' key
			this.shl.RegDelete(installKey);
			//remove the uninstall information
			this.shl.RegDelete(rkUninstall);
		}
		successReport = sUninstallSuccess;
	}
	//report success
	this.shl.Popup(successReport, 0, sInstallTitle);
	return true;
}
//returns a folder object pointing at the given path
function doGetFolder(path){
	var re = /([^\\]+\\?)/g;
	var a = path.match(re);
	var spec = '';
	for(var i = 0; i<a.length; i++){
		spec += a[i];
		if(!this.fso.FolderExists(spec))
			var fol = this.fso.CreateFolder(spec);
		else
			var fol = this.fso.GetFolder(spec);
	}
	return fol;
}
//UGInstall.compareFiles
//takes two pathnames -- ensures that the second exists and is the same as the first
//can also only enforce conformity of files marked for preservation
function doCompareFiles(source, target, preservedOnly){
	if ('undefined' == typeof(preservedOnly))
		preservedOnly = false;
	//check if source is a file or a folder
	//exit if there is no first file
	var type;
	if (this.fso.FileExists(source)){
		if(preservedOnly && !this.preservable(source))
			return; // get out if I won't copy this file
		type = 'file';
	}else if (this.fso.FolderExists(source)){
		type = 'folder';
		//ensure that the target name ends in backslashes
		if (target.match(/[^\\]$/))
			target += '\\';
	} else
		return;
	//make sure the folder exists
	var fol = this.getFolder(target.replace(/[^\\]*$/,''));
	if ('file' == type){
		//if the target doesn't exist, copy the source to it
		if (!this.fso.FileExists(target)){
			this.fso.CopyFile(source, target);
			return;
		}
		//check the size and modification date
		var sourceFile = this.fso.GetFile(source);
		var targetFile = this.fso.GetFile(target);
		//COMPARING FILE MODIFICATION DATES FAILS! (win98, wsh 1, jscript 4)
		if(/*sourceFile.DateLastModified != targetFile.DateLastModified ||*/
			sourceFile.Size != targetFile.Size){
			//if they differ, drop the target file and copy over the source file
			targetFile.Delete(true);
			sourceFile.Copy(target);
		}
	} else {
		var sourceFolder = this.fso.GetFolder(source);
		//fol already equals the target folder
		//recursively check the elements of the folders
		for(var enu = new Enumerator(sourceFolder.SubFolders); !enu.atEnd(); enu.moveNext()){
			this.compareFiles(enu.item().Path + '\\', fol.Path + '\\' + enu.item().Name + '\\', preservedOnly);
		}	
		for(var enu = new Enumerator(sourceFolder.Files); !enu.atEnd(); enu.moveNext()){
			this.compareFiles(enu.item().Path, fol.Path + '\\' + enu.item().Name, preservedOnly);
		}
	}
	return;
}
//tests the file extension of a given file against the list of non-content file extensions
function testPreservable(filename){
	var ext = this.fso.GetExtensionName(filename);
	var whether = false;
	for(var iCnt = 0; iCnt < this.preserveExtensions.length; iCnt++)
		if(this.preserveExtensions[iCnt] == ext)
			whether = true;
	return whether;
}
//recursively removes all files and folders in a tree, leaving files with preserved extensions
function doDeleteUnpreserved(fol){
	var keepThis = false;
	//for each subfolder in the path, recurse -- NO! Only check files! Never delete subfolders!
	/*
	for(var enu = new Enumerator(fol.SubFolders); !enu.atEnd(); enu.moveNext()){
		this.selectiveDelete(enu.item());
	}
	*/
	//for each file in the folder, check its extension and delete it (if it's not preserved, of course)
	var fls = fol.files;
	var enu = new Enumerator(fls);
	for(; !enu.atEnd(); enu.moveNext()){
		var ext = this.fso.GetExtensionName(enu.item().Name);
		//check if this extension is listed
		var preserve = false;
		for(var iExt = 0; false == preserve && iExt<this.preserveExtensions.length; iExt++)
			if (this.preserveExtensions[iExt].toLowerCase() == ext.toLowerCase())
				preserve = true;
		if(!preserve)
			enu.item().Delete(true);//delete the file
		else
			keepThis = true;
	}
	//if there are no files left in the folder, delete it -- this causes an error in Windows Scripting Host 2.0 w/ JScript 4
	/*
	if(fol.SubFolders.Count == 0 && !keepThis)
		fol.Delete(true);
	*/
	//count the subfolders -- I don't care about subfolders! They're the index!
	/*
	var folCount = 0;
	for(var folenum = new Enumerator(fol.SubFolders); !folenum.atEnd(); folenum.moveNext()){
		folCount++;
	}
	//if I'm not keeping this folder and it has no subfolders, delete
	if(folCount == 0 && !keepThis)
		fol.Delete(true);
	*/
}
//UGInstall.confirm
//fires a Yes/No dialog box asking the user if s/he'd like to proceed
//returns true (for 'yes') or false (for 'no')
function doConfirm(prompt, title){
	if ('undefined' == typeof(title))
		title = sInstallTitle;
	if (6 == this.shl.Popup(prompt, 0, title, 4 + 32))
		return true
	return false;
}
//static functions
//getRegVal reads a registry key, and returns undefined or the value
function getRegVal(keyName){
	var shl = WScript.CreateObject("WScript.Shell");
	//check for blow-up
	var command = 'WScript "' + WScript.ScriptFullName.replace(/[^\\]*$/,'') + 'KeyChecker.vbs" ' + keyName;
	//WScript.Echo(command);
	var attempt = shl.Run(command, 1, true);
	if (0 != attempt){
		//shl.Popup("Error Number " + attempt);
		return null;
	}
	return(shl.RegRead(keyName));
}

//returns an array of all the drive letters in the system
function GetCDRomDrives(){
	var fso = WScript.CreateObject('Scripting.FileSystemObject');
	var adv = new Array();
	//loop through the drives, appending the cd-rom drives to the return array
	for(var enu = new Enumerator(fso.Drives);!enu.atEnd(); enu.moveNext()){
		var drv = enu.item();
		if(cdrom == drv.DriveType)
			adv[adv.length] = drv.DriveLetter;
	}
	//end
	return adv;
}
