var IControl = false;
var countImages = 0;
var orphoCheckTxt = false;
var orphoCheckTxtNB = false;
var currentHashElement = false;
var userInfo;

document.onkeydown = keyEvent;
var imgCorner;

// *************** Обработчики событий ***************
function setPageWidth() {
 if (navigator.appVersion.indexOf('MSIE 6') != -1) {
	 var markDiv = document.getElementById('markDiv');
	 if (screen.width > 1150) markDiv.style.width = '1150px';
	 else markDiv.style.width = '980px';
 }
}

function activateFocusHash(_id) {
	if (_id) {
		currentHashElement = document.getElementById(_id);
	} else if (location.hash) {
		currentHashElement = document.getElementById(location.hash.substr(1));
	}
	if (currentHashElement) {
		currentHashElement.style.color = "#c00";
		setTimeout('deActivateFocusHash();', 2000);
	}
}

function deActivateFocusHash() {
	if (currentHashElement) {
		currentHashElement.style.color = "#000";
	}
}

function getFile(pFileName) {
	getIControl();
	IControl.src = pFileName;
}

function setBodySize() {
	if (top.sw) if (top.sw.objectContent) document.body.style.height = '' + (parseInt(top.sw.objectContent.height) - 2) + 'px';
}


function bodyOnLoad() {
	var lBlock = document.getElementById('lBlock');

	setPageWidth();
	try {
		activateFocusHash();
	} catch (e) {
	}


	var arrA = document.getElementsByTagName('A');
	for (var i=0; i<arrA.length; i++) {
		var linkA = arrA[i];
		var linkHref = linkA.href.toLowerCase();
		var pos = linkHref.indexOf('#');
		if (pos != -1) {
			var hash = linkHref.slice(pos + 1);
			if (!linkA.getAttribute('onclick')) {
				linkA.setAttribute('onclick', 'activateFocusHash(\''+hash+'\');');
			}
		}
	}

	imgCorner = new Image();
	imgCorner.src = 'http://static.' + mainDomain + '/tpl/img/swbg.gif';

	setTimeout('checkImages();', 2000);

	var href = window.document.URL;
	href = href.toLowerCase();
	pos = href.indexOf('#');
	if (pos != -1) href = href.substr(0, pos);

	var host = window.document.domain;

	if (lBlock) {
		// подсветка текущей ссылки в левом меню

		var currentLink = href;
		if (host != mainDomain) {

			var arr = currentLink.split('/');
			var arrA = lBlock.getElementsByTagName('A');
			var link = '';
			var curLink = '';
			for (var i=0; i<arrA.length; i++) {
				link = arrA[i];
				curLink = link.href.toLowerCase();
				var cl = '';
				for (j=0; j<arr.length; j++) {
					cl += '' + arr[j];
					if (curLink == cl || curLink == (cl + '/')) link.className += ' cur';
					cl += '/';
				}
				if (curLink == currentLink) link.className += ' cur';
			}

		} else {
			var arrA = lBlock.getElementsByTagName('A');
			for (var i=0; i<arrA.length; i++) {
				link = arrA[i];
				curLink = link.href.toLowerCase();
				if (curLink == currentLink) {
					link.className += ' cur';
					break;
				}
			}
		}
	}

	try {
		localBodyOnLoad();
	} catch (e) {
	}

	var pp = href;
	var pp_pos = pp.indexOf('/programs/programma-');
	if (pp_pos != -1) {
		pp = pp.slice(pp_pos + 10);
		pp_pos = pp.indexOf('/');
		pp = pp.slice(0, pp_pos);
		setCookie('lastProgram', pp);
	}

}

function keyEvent(event) {
	if (!document.getElementById) return;
  if (window.event) event = window.event;
  if (event.ctrlKey) {
  	if (event.shiftKey) {
  		switch (event.keyCode ? event.keyCode : event.which ? event.which : null) {
  			case 69: try { CallEditor(); } catch(e) {} break; // ctrl-shift-E
  			case 0x0D: setTimeout('userLogin();',100); return false; // ctrl-shift-Enter
  			case 81: setTimeout('userExit();',10); return false; // ctrl-shift-Esc
  			case 73: setTimeout('showAdInfo();',10); return false; // ctrl-shift-I
  		}
  	} else {
	  	var link = null;
	    switch (event.keyCode ? event.keyCode : event.which ? event.which : null) {
	      case 0x27: link=document.getElementById('NextPage'); break;
	      case 0x25: link=document.getElementById('PrevPage'); break;
	      case 0x26: link=document.getElementById('UpPage'); break;
	    	case 0x0D: setTimeout('GetSelectedTXT();',100); return false;
	    }
	    if(link && link.href) document.location.href = link.href;
  	}
  } else if (event.keyCode == 13 && document.activeElement) {
  	if (document.activeElement.id == "strSearch") {
  		getSearchIResult();
  	}
  } else if (event.keyCode == 27) {
	 	setTimeout('swClose();',10);
  }
}


function searchFieldOnFocus(obj) {
	if ((obj.value == "Строка поиска" && obj.id == "strSearchCode")
		|| (obj.value == "Номера статей через запятую" && obj.id == "strStat")
		|| (obj.value == "Номера глав через запятую" && obj.id == "strGlav")
		|| (obj.value == "Коды через запятую" && obj.id == "strCode")
		|| (obj.value == "Строка поиска" && obj.id == "strSearchK") ) {
		obj.value = "";
	}
}

function searchFieldOnBlur(obj) {
	if (!obj.value) {
		if (obj.id == "strSearchCode") obj.value = "Строка поиска";
		if (obj.id == "strStat") obj.value = "Номера статей через запятую";
		if (obj.id == "strGlav") obj.value = "Номера глав через запятую";
		if (obj.id == "strCode") obj.value = "Коды через запятую";
		if (obj.id == "strSearchK") obj.value = "Строка поиска";
	}
}

// Обработка нажатия на иконку картинки - открывается коллекция картинок
function imgIconOnClick(obj, razdel, podrazdel, formId, curPage) {
	var imgs = obj.getElementsByTagName('img');
	var imgHref = "";
	if (imgs.length > 0) {
		var img = imgs[0];
		imgHref = img.src;
	}

	if (!imgHref) return false;
	imgHref = imgHref.replace("-ico.",".");

	var curW = new curWindow();

	var sDiv = document.body.appendChild(document.createElement('div'));
	sDiv.setAttribute("id","imgShadowDiv");
	sDiv.className = "swShadowDIV";
	var bgImgLink = 'http://static.systecs.ru/tpl/img/tr1.png';
	if (!window.outerHeight) {
		sDiv.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + bgImgLink + "', sizingMethod='scale')";
	} else {
		sDiv.style.backgroundImage = 'url(' + bgImgLink + ')';
	}

	sDiv.style.width = "" + curW.bWidth + "px";
	sDiv.style.height = "" + curW.bHeight + "px";

	sDiv.style.display = "block";


	var a4 = parseInt(297/0.26);

	var imgWidth = parseInt(curW.cWidth * 90 / 100);
	var imgHeight = parseInt(curW.cHeight * 90 / 100);

	imgWidth = Math.min(imgWidth, a4) + 20;

	var div = document.body.appendChild(document.createElement('div'));
	div.setAttribute("id","imgPreviewContainer");
	div.style.margin = "auto";
	div.style.cursor ="pointer";
	div.style.border = "4px solid #ddd";
	div.style.width = "" + (imgWidth + 8) + "px";
	div.style.height = "" + (imgHeight + 8) + "px";


	var iframeSrc = 'http://sprbuh.' + mainDomain + '/imgcollection.php?r='+razdel+'&pr='+podrazdel+'&form='+formId+'&cur='+curPage;
	var innerHTMLDiv = '<iframe width="100%" height="100%" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" src="' + iframeSrc + '" style="border: none;">Ваш броузер не поддерживает плавающие фреймы!!!</iframe>';
	div.innerHTML = innerHTMLDiv;

	var imgTop = parseInt(Math.max(curW.cHeight - imgHeight - 2, 0) / 2);
	var imgLeft = parseInt(Math.max(curW.cWidth - imgWidth - 2, 0) / 2);

	div.style.top = "" + (imgTop + curW.bScrollTop) + "px";
	div.style.left = "" + imgLeft + "px";
	div.style.position = "absolute";
	div.style.backgroundColor = "#fff";
	div.style.display = "block";
	div.style.zIndex = 200;

	return false;
}


function setImg(href, title, alt) {
	var div = document.getElementById("imgPreviewContainer");
	if (div) div.innerHTML = '<img style="border: 1px solid #000;" src="' + href + '" alt="' + alt + '" title="' + title + '" onclick="imgOnClick(this);">';
}

function closeImgViewIframe() {
	var div = document.getElementById("imgShadowDiv");
	if (div) div.parentNode.removeChild(div);

	div = document.getElementById("imgPreviewContainer");
	if (div) div.parentNode.removeChild(div);
}

// *************** Обработчики событий (КОНЕЦ) ***************

function checkImages() {
	if (countImages > 5) return false;
	countImages++;
	var m = document.getElementById('counters');
	var err = 0;
	for (i in document.images) {
		var img = document.images[i];
		if (!img.complete || (typeof(img.naturalWidth) != 'undefined' && img.naturalWidth == 0) )
		if (img.src && img.src!="http://"+mainDomain+"/tpl/img/4x4.gif") {
			var src = img.src;
			img.src = "http://"+mainDomain+"/tpl/img/4x4.gif";
			img.src = src;
			err++;
		}
	}
	if (err) setTimeout('checkImages();', 2000);
}

// *************** Работа с Cookie ***************
function setCookie(c_name,value,expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  var dom = ";domain=." + document.domain + ';path=/';
  document.cookie = c_name +  "=" + escape(value)+ ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString()) + dom;
}

function getCookie(c_name) {
  if (document.cookie.length > 0) {
    c_start = document.cookie.indexOf(c_name + "=");
    if (c_start != -1) {
      c_start = c_start + c_name.length+1;
      c_end = document.cookie.indexOf(";", c_start);
      if (c_end == -1) c_end = document.cookie.length;
      return unescape(document.cookie.substring(c_start, c_end));
    }
  }
  return "";
}
// *************** Работа с Cookie (КОНЕЦ) ***************

// ******************** НАЧАЛО: БЛОК АВТОРИЗАЦИИ ********************
function userLogin() {
	swGet('http://cabinet.' + mainDomain + '/index.php?action=login&sw=1', 'php');
}

function userReg() {
	swGet('http://cabinet.' + mainDomain + '/index.php?action=registration&sw=1', 'php');
}

function userExit() {
	getIControl();
	IControl.src = "http://cabinet."+mainDomain+"/index.php?userexit=1";
}
// ******************** КОНЕЦ: БЛОК АВТОРИЗАЦИИ ********************

function getIControl() {
	if (IControl) return IControl;
	var container = document.createElement("div");
	container.setAttribute("id","IControlBox");
	container.innerHTML =
		'<iframe id="IControl" name="IControl" src="about:blank">...</iframe>' +
		'<iframe id="IControl2" name="IControl2" src="about:blank">...</iframe>';
  document.body.appendChild(container);
	container.style.display = "none";
	IControl = document.getElementById("IControl");
	return IControl;
}

function getSearchIResult() {
	var strSearch = document.getElementById("strSearch").value;
	if (!strSearch) return false;
	if (strSearch.length < 2) {
		swGet('Строка поиска слишком короткая!', 'msg', 300, 150);
		return false;
	}
	strSearch = encodeURI(strSearch);

	location = "/search.php?razdel=search&strSearch="+strSearch;
}

function closeNavigateHelp(obj) {
	obj.style.display = "none";
	setCookie("hideNavigateHelp",1);
}

function GetSelectedTXT() {
	orphoCheckTxt = false;
	orphoCheckTxtNB = false;
	var sel = false;
	if (window.getSelection) sel = window.getSelection();
	else if (document.getSelection) sel = document.getSelection();
	else if (window.selection) sel = window.selection();
	else if (document.selection) sel = document.selection;

	if (!sel) return false;

	if (sel.createRange) {
		var rng = document.selection.createRange();
		orphoCheckTxt = rng.text;

		rng.moveStart('word', -3);
		rng.moveEnd('word', 3);
		orphoCheckTxtNB = rng.text;
	} else {
		if (sel.getRangeAt) {
			var rng = sel.getRangeAt(0);
			orphoCheckTxt = rng.toString();

			var rngN = document.createRange();
			rngN.setStartBefore(rng.startContainer.parentNode);
			rngN.setEndAfter(rng.endContainer.parentNode);
			orphoCheckTxtNB = rngN.toString();
		} else {
			orphoCheckTxt = "" + sel;
			orphoCheckTxtNB = "" + sel;
		}
	}
	orphoCheckTxt = orphoCheckTxt.replace(/[\r\n]+/g, " ").replace(/^\s+|\s+$/g, "");
	orphoCheckTxtNB = orphoCheckTxtNB.replace(/[\r\n]+/g, " ").replace(/^\s+|\s+$/g, "");
	if (orphoCheckTxt.length > 150) {
		swGet('Выделен слишком большой объем текста!', 'msg', 300, 150);
		return false;
	}
	if (orphoCheckTxt.length == 0 ) return false;

	orphoCheckTxtNB = orphoCheckTxtNB.replace(orphoCheckTxt, '<span style="color: red; font-weight: bold;">' + orphoCheckTxt + '</span>');

	swGet("http://" + mainDomain + "/tools/sendError.php", 'php', 0, 0, "Сообщение об ошибке");
}

function accOnClick(obj) {
	var bm = obj.firstChild.href;
	var p = bm.indexOf('#');
	var id = bm.substr(p + 1,bm.length);
	var linkA = document.getElementById(id);
	if (linkA) { document.location.href = linkA.href; }
	return false;
}

function curWindow() {
	this.cWidth = 0;
	this.cHeight = 0;
	this.bWidth = 0;
	this.bHeight = 0;
	this.bScrollTop = 0;
	this.bScrollLeft = 0;

	var iw = window.innerWidth;
	var ih = window.innerHeight;
	var cw = document.documentElement.clientWidth;
	var ch = document.documentElement.clientHeight;
	var ow = document.body.offsetWidth;
	var oh = document.body.offsetHeight;

	this.cWidth = (iw ? iw : (cw ? cw : ow));
  this.cHeight = (ih ? ih : (ch ? ch : oh));

	if (iw) {
		this.bWidth = Math.max(this.bWidth, iw);
		this.bHeight = Math.max(this.bHeight, ih);
	}
	if (cw) {
		this.bWidth = Math.max(this.bWidth, cw);
		this.bHeight = Math.max(this.bHeight, ch);
	}
	if (ow) {
		this.bWidth = Math.max(this.bWidth, ow);
		this.bHeight = Math.max(this.bHeight, oh);
	}

	var scroll_1 = document.documentElement.scrollTop;
	var scroll_2 = document.body.scrollTop;
	var scroll_3 = window.pageYOffset;
	if (scroll_1 != 'undefined' && scroll_1) {
		this.bScrollTop = scroll_1;
		this.bScrollLeft = document.documentElement.scrollLeft;
	} else if (scroll_2 != 'undefined' && scroll_2) {
		this.bScrollTop = scroll_2;
		this.bScrollLeft = document.body.scrollLeft;
	} else if (scroll_3 != 'undefined' && scroll_3) {
		this.bScrollTop = scroll_3;
		this.bScrollLeft = window.pageXOffset;
	}
}

// ОПРОСЫ

function getVote() {
	var voteId = document.getElementById('voteId');
	if (voteId) {
		var cook = getCookie('voteId_' + voteId.value);
		if (cook) {
			openVoteResWindow(voteId.value, 2);
			return false;
		}
	}

	var form = document.getElementById('voteForm');
	if (!form) return false;
	var inputs = form.getElementsByTagName('input');
	var cnt = 0;
	for (var i in inputs) {
		if (inputs[i].checked) cnt++;
	}
	if (!cnt) {
		swGet('Не выбран ни один вариант ответа!', 'msg', 300, 150);
		return false;
	}

	setCookie('voteId_' + voteId.value, "1", 360);

	getIControl();
	form.target = "IControl";
	form.submit();
}

function openVoteResWindow(voteId, newVote) {
	if (!newVote) newVote = '';
	var cook = getCookie('voteId_' + voteId);
	if (!cook && !document.getElementById("adInfo")) {
		swGet('Для просмотра результатов нужно проголосовать!', 'msg', 300, 150);
		return false;
	}

	swGet('http://' + mainDomain + '/voteResult.php?voteId=' + voteId + '&new=' + newVote, 'php', 0, 0, 'Результаты опроса');
}

function selVote(obj) {
	var inputs = obj.parentNode.parentNode.getElementsByTagName('input');
	for (var i = 0; i<inputs.length; i++) {
		if (inputs[i] == obj) continue;
		else
			if (inputs[i].type == "checkbox") inputs[i].checked = 0;
	}
}

function wsmBrowser() {
  var userAgent;
  var browserType = [];
  var i;

  this.isIE = false;
  this.isFF = false;
  this.version = null;

  userAgent = navigator.userAgent;

  browserType[0] = "MSIE";
  browserType[1] = "Opera";
  browserType[2] = "Firefox"
  browserType[3] = "Chrome"
  if ((i =  userAgent.indexOf(browserType[0])) >= 0) {
    this.isIE = true;
    this.version = parseFloat(userAgent.substr(i + browserType[0].length));
    return;
  }
  if ((i =  userAgent.indexOf(browserType[1])) >= 0) {
    this.isIE = true;
    this.version = parseFloat(userAgent.substr(i + browserType[1].length));
    return;
  }
  if ((i = userAgent.indexOf(browserType[2])) >= 0) {
    this.isFF = true;
    this.version = parseFloat(userAgent.substr(i + browserType[2].length));
    return;
  }
  if ((i = userAgent.indexOf(browserType[3])) >= 0) {
    this.isFF = true;
    this.version = parseFloat(userAgent.substr(i + browserType[3].length));
    return;
  }

  this.isIE = true;
  return;
}

var browser = new wsmBrowser();


function addToBkm(userUID, userID) {
	getIControl();
	var link = encodeURI("http://"+mainDomain+"/engine/bookmarks.php?mode=add&url="+location.href+"&userUID="+userUID+"&userID="+userID);
	IControl.src = link;
}

function viewBkm(userUID, userID) {
	alert(userUID);
}

// ******************** НАЧАЛО: Класс "Служебное окно" ********************
var sw;
var swTimers = [];

function serviceWindow(_url, _contentType, _width, _height, _title) {
	// Инициализация объекта
	this.widthStart = 100;
	this.heightStart = 100;
	this.width = 100;		// желаемая ширина контента
	this.height = 100;	// желаемая высота контента
	this.dW = 0;
	this.dH = 0;
	this.time = 300;
	this.timeout = 0;
	this.steps = 0;
	this.curStep = 0;
	this.object = false;
	this.objectContent = false;
	this.imgLoadCnt = 0;
	this.url = '';
	this.contentType = 'img';

	this.resize = swResize;
	this.process = swProcess;
	this.showContent = swShowContent;
	this.checkImg = swCheckImg;
	this.showBtnClose = swShowBtnClose;

	var _id = 'swDiv';

	if (!imgCorner) {
		imgCorner = new Image();
		imgCorner.src = 'http://static.' + mainDomain + '/tpl/img/swbg.gif';
	}

	// Действия при инициализации
	if (_width)	this.width =	_width;
	if (_height)	this.height =	_height;
	if (_contentType)	this.contentType = _contentType;

	this.object = document.getElementById(_id);

	if (!this.object) {
		// Создание контейнера
		this.object = document.body.appendChild(document.createElement('div'));
		this.object.id = _id;

		this.object.className = 'swRoundedBox';

		var style = this.object.style;
		if (browser.isIE && browser.version == 6) style.position = 'absolute';
		else style.position = 'fixed';
		style.width =		'' + this.widthStart + 'px';
		style.height =	'' + this.heightStart + 'px';

	} else {
		var style = this.object.style;
		this.widthStart =		parseInt(style.width);
		this.heightStart =	parseInt(style.height);

		this.objectContent = document.getElementById('swContent');
		this.objectContent.style.display = 'none';
	}

	var curImg = false;
	var collection = false;
	if (typeof(_url) == 'object') {
		collection = _url;
		if (_contentType) curImg = _contentType;
		else curImg = 0;

		var img = collection[curImg];
		_url =		img.url;
		this.contentType = 'img';
		_title =	img.title;
		this.width =	img.width;
		this.height =	img.height;
	}

	if (_url) this.url = _url;

	this.object.style.display = 'block';

	setObjectPos(this.object);

	var content = '';
	if (this.contentType == 'img') {
		content += '<img id="swContent" src="' + this.url + '" onclick="swClose();" style="margin: 0px; display: none;" width="' + this.width + 'px" height="' + this.height + 'px">';

	} else if (this.contentType == 'msg') {
		content += '<div id="swContent" style="margin: 0px; display: none;" height="100%">';
		content += '<div style="margin: 0px; padding: 0px; background-color: #ededdd; border: 1px solid #ab0404; color: black; font-family: Arial, sans-serif; font-size: 9pt; overflow: hidden; padding: 0px 16px; text-align: center; height: ' + (this.height - 2) + 'px;">';
		content += '<table cellpadding="0" cellspacing="0" style=" width: 100%; height: ' + (this.height - 30) + 'px;"><tr><td style="color: #000; font-weight: bold; vertical-align: middle; ">' + this.url + '</td></tr></table>';
		content += '<div style="background-color: #ff8200; border: 1px solid #fff; color: #fff;	cursor: pointer; font-size: 9pt; text-align: center; white-space: nowrap;width: 70px; margin: auto; padding: 2px 6px;" onclick="swClose();">Закрыть</div>';
		content += '</div>';
		content += '</div>';

	} else {
		content += '<iframe id="swContent" src="' + this.url + '" width="100%" height="100%" frameborder="0" marginheight="0" marginwidth="0" style="display: none;"></iframe>';
	}

	var innerHTML = '';

	var bw = 15;

	var empty = '&nbsp;';
	if (browser.isIE && browser.version == 6) {
		var imgCLT = '&nbsp;';
		var imgCRT = '&nbsp;';
		var imgCLB = '&nbsp;';
		var imgCRB = '&nbsp;';
		var ts = ' style="background-color: #fff;"';
	} else {
		var imgCLT = '<img src="' + imgCorner.src + '" style="position: absolute; clip: rect(0px,15px,15px,0px); left: 0px; top: 0px;">';
		var imgCRT = '<img src="' + imgCorner.src + '" style="position: absolute; clip: rect(0px,32px,17px,17px); right: 0px; top: 0px;">';
		var imgCLB = '<img src="' + imgCorner.src + '" style="position: absolute; clip: rect(17px,17px,32px,0px); left: 0px; bottom: 0px;">';
		var imgCRB = '<img src="' + imgCorner.src + '" style="position: absolute; clip: rect(17px,32px,32px,17px); right: 0px; bottom: 0px;">';
		var ts = '';
	}
	innerHTML += '<table cellspacing="0" cellpadding="0" ' + ts + '>';

	innerHTML += '<tr style="height: ' + bw + 'px;">';
	innerHTML += '<td style="width: ' + bw + 'px; ">' + imgCLT + '</td>';

	innerHTML += '<td class="swBorder" style="background-color: #fff;">';
	if (_title) {
		innerHTML += '<div id="swTitle" style="width: 80%; margin: auto;">';
		innerHTML += '<table style="width: 100%; height: 100%; margin: auto; margin-top: -10px; padding-left: 8px; "><tr>';
		innerHTML += '<td class="swTitle swTl" style="width: 25px; vertical-align: middle; text-align: left; ">';
		if (collection) {
			var objName = collection['name'];
			var prev = curImg - 1;

			if (collection[prev]) innerHTML += '<span class="swBtnArrow" onclick="swGet(' + objName + ', ' + prev + ');" title="' + collection[prev].title + '">◄</span>';
			else innerHTML += '<span class="swBtnArrowNA">◄</span>';

		} else {
			innerHTML += empty;
		}
		innerHTML += '</td>';

		innerHTML += '<td class="swTitle swT" style="vertical-align: middle; text-align: center;">';
		innerHTML += _title;
		if (collection) {
			innerHTML += '<span style="margin-left: 24px; font-weight: normal; color: #fff;">' + (curImg + 1) + ' из ' + (collection.length) + '</span>';
		}
		innerHTML += '</td>';
		innerHTML += '<td class="swTitle swT" style="width: 16px; vertical-align: middle; text-align: center;">';
		if (collection) {
			var next = curImg + 1;
			if (collection[next]) innerHTML += '<span class="swBtnArrow"  onclick="swGet(' + objName + ', ' + next + ');" title="' + collection[next].title + '">►</span>';
			else innerHTML += '<span class="swBtnArrowNA">►</span>';
		} else {
			innerHTML += empty;
		}
		innerHTML += '</td>';
		innerHTML += '<td class="swTitle swTr" style="width: 16px; vertical-align: middle; text-align: right;">';
		innerHTML += '<span class="swBtnClose" onclick="swClose();" title="Закрыть окно">Х</span>';
		innerHTML += '</td>';
		innerHTML += '</tr></table>';
		innerHTML += '</div>';

	} else {
		innerHTML += empty;
	}
	innerHTML += '</td>';

	innerHTML += '<td style="width: ' + bw + 'px; ">' + imgCRT + '</td>';
	innerHTML += '</tr>';

	innerHTML += '<tr>';
	innerHTML += '<td class="swBorder">' + empty + '</td>';
	innerHTML += '<td class="swBorder" style="vertical-align: middle;">';
	innerHTML += '<img id="swImgWait" src="http://static.' + mainDomain + '/tpl/img/wait.gif" style="margin: auto;">';
	innerHTML += content;
	innerHTML += '</td>';
	innerHTML += '<td class="swBorder">' + empty + '</td>';
	innerHTML += '</tr>';

	innerHTML += '<tr  style="height: ' + bw + 'px;">';
	innerHTML += '<td style="text-align: right; height: ' + bw+ 'px;">' + imgCLB + '</td>';
	innerHTML += '<td class="swBorder">' + empty + '</td>';
	innerHTML += '<td>' + imgCRB + '</td>';
	innerHTML += '</tr>';
	innerHTML += '</table>';

	this.object.innerHTML = innerHTML;

	var title = document.getElementById('swTitle');
	if (title) {
		if (this.widthStart != this.width + bw*2 || this.heightStart != this.height + bw*2) {
			title.style.display = 'none';
		}
	}

	this.objectContent = document.getElementById('swContent');
	this.objectContent.style.display = 'none';

	var imgWait = document.getElementById('swImgWait');
	if (imgWait) imgWait.style.display = 'block';
	if (this.contentType == 'img') {
		setTimeout('sw.checkImg()', 100);
	} else if (this.contentType == 'msg') {
		this.process(this.width, this.height);
	}
}

function swCheckImg() {
	if (!this.objectContent.complete || (typeof(this.objectContent.naturalWidth) != 'undefined' && this.objectContent.naturalWidth == 0) ) {
		this.imgLoadCnt++;
		if (this.imgLoadCnt > 10) return;
		setTimeout('sw.checkImg()', 100);
		return;
	}
	this.process(this.width, this.height);
}

function swClose() {
	if (!sw) return;
	// Сброс таймеров
	for (key in swTimers) {
		if (swTimers[key]) {
			clearTimeout(swTimers[key]);
			swTimers[key] = false;
		}
	}
	//
	sw.object.parentNode.removeChild(sw.object);
	sw = false;
	var shadow = document.getElementById('fullShadow');
	if (shadow) shadow.parentNode.removeChild(shadow);

	if (top.location.href.toLowerCase().indexOf('http://cabinet.' + mainDomain.toLowerCase() + '/') != -1) {
		var lastUrl = getCookie('lastUrl');
		if (lastUrl) {
			top.location = lastUrl;
		} else {
			top.location = 'http://' + mainDomain + '/';
		}
	}
}

function swProcess(_width, _height) {
	if (browser.isIE && browser.version == 6) this.object.style.position = 'absolute';
	else this.object.style.position = 'fixed';

	var ed = '';
	if (this.contentType != 'img') ed = 'px';
	this.objectContent.width = '' + _width + ed;
	this.objectContent.height = '' + _height + ed;

	var bw = 30; // ширина border для контейнера
	//if (browser.isIE) bw = 0;

	this.width = _width + bw;
	this.height = _height + bw;

	var style = this.object.style;

	this.widthStart =		parseInt(style.width);
	this.heightStart =	parseInt(style.height);

	var dW = this.width - this.widthStart;
	var dH = this.height - this.heightStart;

	if (dW != 0 || dH != 0) {
		this.objectContent.style.display = 'none';
		var imgWait = document.getElementById('swImgWait');
		if (imgWait) imgWait.style.display = 'block';
	}

	this.steps = Math.min(Math.round((Math.abs(dW) + Math.abs(dH)) / 2), Math.round(this.time / 1000 * 60));
	this.curStep = 0;
	this.timeout = Math.round(this.time / this.steps);

	this.dW = dW / this.steps;
	this.dH = dH /  this.steps;

	if (this.contentType == 'msg') {
		this.steps = 1;
		this.dW = dW;
		this.dH = dH;
	}

	if (this.contentType == 'msg') this.resize();
	else swTimers['resize'] = setTimeout('sw.resize();', 500);
}

function swShowContent() {
	if (!sw) return;
	this.objectContent.style.display = 'block';
	if (this.contentType == 'msg') this.showBtnClose();
	else swTimers['btnClose'] = setTimeout("sw.showBtnClose()", 400);
}

function swShowBtnClose() {
	var title = document.getElementById('swTitle');
	if (title) {
		title.style.display = 'block';
	}
}

function swResize() {
	var style = this.object.style;
	var curW = parseInt(style.width);
	var curH = parseInt(style.height);
	var curTop = parseInt(style.top);
	var curLeft = parseInt(style.left);

	if (this.width != curW || this.height != curH) {
		this.curStep++;

		var dW = Math.round((this.curStep * this.dW + this.widthStart - curW) / 2);
		var dH = Math.round((this.curStep * this.dH + this.heightStart - curH) / 2);

		curW += dW * 2;
		curH += dH * 2;

		if (dW != 0) curW = dW > 0 ? Math.min(this.width, curW) : Math.max(this.width, curW);
		if (dH != 0) curH = dH > 0 ? Math.min(this.height, curH) : Math.max(this.height, curH);

		curTop += -dH;
		curLeft += -dW;

		style.width =	'' + curW + 'px';
		style.height ='' + curH + 'px';
		style.top =		'' + curTop + 'px';
		style.left =	'' + curLeft + 'px';

		if (this.curStep < this.steps) {
			swTimers['resize'] = setTimeout('sw.resize()', this.timeout);
			return;
		}
	}

	var imgWait = document.getElementById('swImgWait');
	if (imgWait) imgWait.style.display = 'none';

	if (this.contentType == 'msg') swTimers['showContent'] = setTimeout('sw.showContent()', 10);
	else swTimers['showContent'] = setTimeout('sw.showContent()', 500);
}

// swGet принимает параметры 2х типов:
// str url - задается url единичной картинки
// или
// arr url - задается коллекция картинок (массив) формата:
// var b = [];
//	b['name'] = 'b';  - имя коллекции = имени переменной массива
//	b[0...n]={str url, str title, int width, int height};

function swGet(url, type, width, height, title) {
	try {
		if (document.compatMode == 'BackCompat' && browser.isIE) {
			alert('Ваш броузер работает в режиме поддержки страниц устаревшего формата (quirk mode).\n В этом режиме могут возникнуть проблемы с отображением страниц.');
		};
	} catch (e) {
	}

	setShadow();
	sw = new serviceWindow(url, type, width, height, title);
	return false;
}

function swSetWindowPos() {
	if (!sw) return;
	if (sw.object) setObjectPos(sw.object);
}

// ******************** КОНЕЦ: Класс "Служебное окно" ********************

function setObjectPos(obj) {
	var curW = new curWindow();

	var imgWidth = obj.clientWidth;
	var imgHeight = obj.clientHeight;

	var imgTop = parseInt(Math.max(curW.cHeight - imgHeight - 2, 0) / 2);
	var imgLeft = parseInt(Math.max(curW.cWidth - imgWidth - 2, 0) / 2);

	var style = obj.style;
	style.top = '' + imgTop + 'px';
	style.left = '' + imgLeft + 'px';

	var shadow = document.getElementById('fullShadow');
	if (shadow) {
		shadow.style.width = '' + curW.bWidth + 'px';
		shadow.style.height = '' + (curW.bHeight + 8) + 'px';
	}
}

function setShadow() {
	var curW = new curWindow();
	document.body.style.overflowX = 'hidden';

	var sDiv = document.getElementById('fullShadow');
	if (!sDiv) {
		sDiv = document.body.appendChild(document.createElement('div'));
		sDiv.id = 'fullShadow';
		sDiv.className = 'swFullShadow';
		sDiv.onclick = swClose;
	}
	var style = sDiv.style;
	style.width = '' + curW.bWidth + 'px';
	style.height = '' + curW.bHeight + 'px';
}

var swImgArr;

function saveLastUrl() {
	setCookie('lastUrl', document.location.href);
}

function downloadForm(_obj) {
	startProgressBar(_obj);
	return false;
}

var progressTime = 0;
var progressDiv = false;
var progressBar = false;
var progressTitle = false;
var progressObj = false;

function startProgressBar(_obj) {
	if (progressDiv) return;

	var div = document.createElement('DIV');
	div.setAttribute('id', 'progressBar');
	if (_obj.parentNode.nextSibling) {
		_obj.parentNode.parentNode.insertBefore(div, _obj.parentNode.nextSibling);
	} else {
		_obj.parentNode.parentNode.appendChild(div);
	}
	var prog = document.createElement('TABLE');
	prog.setAttribute('style','border: 1px solid silver; width: 50%; border-spacing: 1px 2px; border-collapse: separate; margin: auto;');
	var tr = prog.appendChild(document.createElement('TR'));
	var td;
	for (i = 0; i < 30; i++) {
		td = tr.appendChild(document.createElement('TD'));
		td.innerHTML = '&nbsp;';
		td.setAttribute('style','width: 3%;');
	}

	var title = document.createElement('DIV');
	div.appendChild(title);
	div.appendChild(prog);
	title.setAttribute('style', 'padding: 6px; color: navy; font-weight: bold; font-size: 9pt; text-align: center;');
	title.innerHTML = 'Загрузка файла начнется автоматически через 30 секунд...';

	progressTime = 0;
	progressDiv = div;
	progressBar = tr;
	progressTitle = title;
	progressObj = _obj;
	setTimeout('drawProgressBar();', 1000);
}

function drawProgressBar() {
	var timeLimit = 30;
	if (progressTime == timeLimit) {
		startDownloadForm(progressObj);
		return;
	}
	progressTime++;

	progressBar.childNodes[progressTime - 1].style.backgroundColor = 'silver';
	var t = timeLimit - progressTime;
	var ts = 'секунд';
	if (t == 0) {
		progressTitle.innerHTML = 'Загрузка файла началась...';
	} else {
		if (t == 1) ts = 'секунду';
		else if (t < 5) ts = 'секунды';
		else if (t <= 20) ts = 'секунд';
		else if (t == 21) ts = 'секунду';
		else if (t < 25) ts = 'секунды';
		else if (t <= 30) ts = 'секунд';
		progressTitle.innerHTML = 'Загрузка файла начнется автоматически через ' + t + ' ' + ts + '...';
	}

	setTimeout('drawProgressBar();', 1000);
}

function startDownloadForm(_obj) {
	progressDiv.parentNode.removeChild(progressDiv);
	progressDiv = false;
	progressBar = false;
	progressTitle = false;

	getIControl();
	IControl.src = _obj.href;
//	var domain = 'http://sprbuh.' + mainDomain;
//	var link = _obj.href.replace(domain, '');
//	IControl.src = domain + '/downloadForm.php?form=' + link;
}

function showAdInfo() {
	var div = document.getElementById('adInfo');
	if (div) {
		div.style.display = 'block';
	}
}
