var objSWbemLocator = new ActiveXObject("WbemScripting.SWbemLocator");
var objWMIService;

// Удаление лишней информации
function ReplaceAdv(str){
	return str.replace(/\(R\)/g, '').replace(/\(TM\)/gi, '').replace(/\(Microsoft Corporation\)/,'').replace(/Microsoft /g,'').replace(/Service Pack /,'SP').replace(/Edition /g,'').replace(/Professional/,'Pro').replace(/CPU /, '').replace(/Процессор|Processor/, '').replace(/(Express|Chipset|Controller|Graphics|Family|Model)/g, '').replace(/\s+/g, ' ').replace(/\s+$/, '').replace(/^\s+/, '');
}

function GetProcessorInfo(i){
	INI['host'+i].proc_name = '';
	INI['host'+i].proc_clock = '';
	try {
		var colItems = objWMIService.ExecQuery ("select * from Win32_Processor");
		var enumItems = new Enumerator(colItems);
		for (; !enumItems.atEnd(); enumItems.moveNext()) {
			var objItem = enumItems.item();
			INI['host'+i].proc_name = ReplaceAdv(objItem.Name);
			INI['host'+i].proc_clock = objItem.CurrentClockSpeed;
		}
	} catch(e) {};
}

function GetDisksSize(i){
	INI['host'+i].disks_size = '';
	try {
		var colItems = objWMIService.ExecQuery ("select * from Win32_DiskDrive");
		var enumItems = new Enumerator(colItems);
		var arr_disks_size = [];
		for (; !enumItems.atEnd(); enumItems.moveNext()) {
			var objItem = enumItems.item();
			arr_disks_size[arr_disks_size.length] = Math.round(objItem.Size/1000/1000/1000);
		}
		INI['host'+i].disks_size = arr_disks_size.join(", ");
	} catch(e) {};
}

function GetMemoryInfo(i){
	INI['host'+i].memory_size = '';
	INI['host'+i].memory_info = '';
	var aFormFactor = ['Unknown','Other','SIP','DIP','ZIP','SOJ','Proprietary','SIMM','DIMM','TSOP','PGA','RIMM','SODIMM','SRIMM','SMD','SSMP','QFP','TQFP','SOIC','LCC','PLCC','BGA','FPBGA','LGA'];
	var aMemoryType = ['Unknown','Other','DRAM','Synchronous DRAM','Cache DRAM','EDO','EDRAM','VRAM','SRAM','RAM','ROM','Flash','EEPROM','FEPROM','EPROM','CDRAM','3DRAM','SDRAM','SGRAM','RDRAM','DDR','DDR-2'];
	try {
		var colItems = objWMIService.ExecQuery ("select * from Win32_PhysicalMemory");
		var enumItems = new Enumerator(colItems);
		var arr_mem_size = [];
		var mem_speed = mem_type = mem_formfactor = '';
		for (; !enumItems.atEnd(); enumItems.moveNext()) {
			var objItem = enumItems.item();
			arr_mem_size[arr_mem_size.length] = objItem.Capacity/1024/1024;
			if (objItem.FormFactor) mem_formfactor = aFormFactor[objItem.FormFactor];
			if (objItem.MemoryType) mem_type = aMemoryType[objItem.MemoryType];
			if (objItem.Speed) mem_speed = objItem.Speed;
		}
		INI['host'+i].memory_size = arr_mem_size.join("+");

		var mem_info = mem_formfactor ? mem_formfactor : '';
		mem_info += mem_type ? ' ' + mem_type : '';
		mem_info += mem_speed ? ' ' + mem_speed : '';
		INI['host'+i].memory_info = mem_info;
	} catch(e) {};
}

function GetVideoProc(i){
	INI['host'+i].video = '';
	INI['host'+i].video_mem = '';
	try {
		var colItems = objWMIService.ExecQuery ("select * from Win32_VideoController");
		var enumItems = new Enumerator(colItems);
		for (; !enumItems.atEnd(); enumItems.moveNext()) {
			var objItem = enumItems.item();
			if (/^PCI\\/.test(objItem.PNPDeviceID)) {
				INI['host'+i].video = ReplaceAdv(objItem.Name);
				INI['host'+i].video_mem = Math.round(objItem.AdapterRAM/1024/1024);
			}
		}
	} catch(e) {};
}

function GetNetInfo(i){
	INI['host'+i].mac = '';
	INI['host'+i].ip_all = '';
	INI['host'+i].DefaultIPGateway = '';
	INI['host'+i].DNSServerSearchOrder = '';
	try {
		var colItems = objWMIService.ExecQuery ("select * from Win32_NetworkAdapterConfiguration where IPEnabled = True");
		var enumItems = new Enumerator(colItems);
		var objItem = enumItems.item();
		INI['host'+i].mac = objItem.MACAddress;
		try {
			var ip_address = objItem.IPAddress.toArray();
			INI['host'+i].ip = ip_address[0];
			INI['host'+i].ip_all = ip_address.join(",")
		} catch(e) {};
		try {INI['host'+i].DefaultIPGateway = objItem.DefaultIPGateway.toArray().join(",")} catch(e) {};
		try {INI['host'+i].DNSServerSearchOrder = objItem.DNSServerSearchOrder.toArray().join(",")} catch(e) {};
	} catch(e) {};
}

function GetComputerSystem(i){
	INI['host'+i].name = '';
	INI['host'+i].domain = '';
	INI['host'+i].username = '';
	try {
		var colItems = objWMIService.ExecQuery ("select * from Win32_ComputerSystem");
		var enumItems = new Enumerator(colItems);
		for (; !enumItems.atEnd(); enumItems.moveNext()) {
			var objItem = enumItems.item();
			INI['host'+i].name = objItem.Name;
			INI['host'+i].domain = objItem.Domain;
			INI['host'+i].username = objItem.UserName;
			if ((INI.main.username_without_domain) && (INI.main.username_without_domain != 0)){
				INI['host'+i].username = INI['host'+i].username.replace(/^.*\\/, '');
			}
		}
	} catch(e) {};
}

function GetOperatingSystem(i){
	INI['host'+i].OSVersion = '';
	try {
		var colItems = objWMIService.ExecQuery ("select * from Win32_OperatingSystem");
		var enumItems = new Enumerator(colItems);
		for (; !enumItems.atEnd(); enumItems.moveNext()) {
			var objItem = enumItems.item();
			INI['host'+i].OSVersion = objItem.Caption + ' ' + objItem.Version;
			if (objItem.CSDVersion) INI['host'+i].OSVersion += ' ' + objItem.CSDVersion;
			INI['host'+i].OSVersion = ReplaceAdv(INI['host'+i].OSVersion);
		}
	} catch(e) {};
}

function GetUserInfoFromAD(i){
	function GetLDAPstring(username) {
		var ADS_NAME_INITTYPE_GC = 3;
		var ADS_NAME_TYPE_1779 = 1;
		var ADS_NAME_TYPE_NT4  = 3;

		try {
			with (new ActiveXObject("NameTranslate")) {
				Init (ADS_NAME_INITTYPE_GC, "");
				Set (ADS_NAME_TYPE_NT4, username);
				return Get(ADS_NAME_TYPE_1779);
			}
		} catch(e) {}
	}

	if ((INI['host'+i].domain) && (INI['host'+i].username)) {
		var LDAPstring = GetLDAPstring(INI['host'+i].domain.replace(/\..*$/, '') + '\\' + INI['host'+i].username);
		if (LDAPstring) {
			var oUser = GetObject('LDAP://' + LDAPstring);
			if (oUser.cn) INI['host'+i].user_cn = oUser.cn; // ФИО
			if (oUser.info) INI['host'+i].user_info = oUser.info; // отдел
			if (oUser.title) INI['host'+i].user_title = oUser.title; // должность
			if (oUser.mail) INI['host'+i].user_mail = oUser.mail; // e-mail
			if (oUser.telephoneNumber) INI['host'+i].user_telephoneNumber = oUser.telephoneNumber; // корпоративный
			if (oUser.otherTelephone) INI['host'+i].user_otherTelephone = oUser.otherTelephone; // городской
		}
	}
}

// Подключение к удаленному компьютеру
var curHostName = "";
function ConnectServer(i) {
	function Connect(i, login, pass) {
		try {
			objWMIService = objSWbemLocator.ConnectServer((INI['host'+i].name || INI['host'+i].ip), "ROOT\\CIMV2", login, pass);
			return true;
		} catch(e) {}
	}

	if (Connect(i)) return true; // Без логина/пароля (с правами текущего пользователя)
	if (tmpAdminPass) { // С логином/паролем администратора из INI файла
		if (Connect(i, tmpAdminName, tmpAdminPass)) return true;
	}
	// Задаём логин/пароль в диалоговом окне:
	curHostName = INI['host'+i].name || INI['host'+i].ip;
	showModalDialog('code/logon.html', self, 'status:no; help:no; dialogWidth:10px; dialogHeight:30px;');
	if (Connect(i, tmpAdminName, tmpAdminPass)) return true;
	alert ("Error connecting to host " + curHostName);
}

// Чтение информации с удаленного ПК
function GetHostInfo(i){
	if ( (IsContainArray(['computer', 'server', 'notebook'], INI['host'+i].type)) && ConnectServer(i) ) {
		GetComputerSystem(i);
		GetNetInfo(i);
		GetOperatingSystem(i);
		GetProcessorInfo(i);
		GetMemoryInfo(i);
		GetDisksSize(i);
		GetVideoProc(i);
		GetUserInfoFromAD(i);
		FillRow(i);
	}
	pending--;
	if (pending==0) {
		StartTimer();
		UncheckAll();
	}
}
