//===========================================
//  Подсветка поиска
//===========================================
function searchWithinNode(node, te, len){
//===========================================
	var pos, skip, spannode, middlebit, endbit, middleclone;
	skip=0;
	if( node.nodeType==3 ){
		pos=node.data.toUpperCase().indexOf(te);
		if(pos>=0){
			spannode=document.createElement("SPAN");
			spannode.style.backgroundColor="#bb5d01";
			spannode.style.color="white";
			middlebit=node.splitText(pos);
			endbit=middlebit.splitText(len);
			middleclone=middlebit.cloneNode(true);
			spannode.appendChild(middleclone);
			middlebit.parentNode.replaceChild(spannode,middlebit);
			skip=1;
		}
	}else if( node.nodeType==1&& node.childNodes && node.tagName.toUpperCase()!="SCRIPT" && node.tagName.toUpperCase!="STYLE"){
		for (var child=0; child < node.childNodes.length; ++child){
			child=child+searchWithinNode(node.childNodes[child], te, len);
		}
	}
	return skip;
}

function showFlash(path,width,height){ 
	var str='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+width+'" height="'+height+'" id="blik" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="'+path+'" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#666666" /><embed src="'+path+'" quality="high" wmode="transparent" bgcolor="#666666" width="'+width+'" height="'+height+'" name="blik" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
	document.writeln(str); 
}

function fillTables(contentBlockId,headerNeed,reCellBordered) {
	
	if(document.getElementsByTagName){
		var items = document.getElementById(contentBlockId).getElementsByTagName("TABLE");
		for(var i=0;i<items.length; i++){
			if (!reCellBordered || (items[i].getAttribute(classFix)).indexOf("reCellBordered")>0){
				var nodes = items[i].getElementsByTagName("TR");
				var start = 0;
				if (headerNeed && (nodes[0].getAttribute(classFix)==""  || nodes[0].getAttribute(classFix)==null)){
					nodes[0].setAttribute(classFix,"color_2");
					start = 1;
				}
				for(var j=start;j<nodes.length; j++){
					if (nodes[j].getAttribute(classFix)=="" || nodes[j].getAttribute(classFix)==null){
						nodes[j].setAttribute(classFix,"color_"+(j%2));
					}
				}
			}
		}
	}
}	
/*
Функция удаления значения cookie
Принцип работы этой функции заключается в том, что cookie устанавливается с заведомо устаревшим параметром expires, в данном случае 1 января 1970 года.
name - имя cookie
path - путь, для которого cookie действительно
domain - домен, для которого cookie действительно
*/
function deleteCookie(name, path, domain) {
        if (getCookie(name)) {
                document.cookie = name + "=" +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT"
        }
}
/* .......................................................
	Функция установки значения cookie
		name - имя cookie
		value - значение cookie
		expires - дата окончания действия cookie (по умолчанию 0 - до конца сессии)
		path - путь, для которого cookie действительно (по умолчанию - документ, в котором значение было установлено)
		domain - домен, для которого cookie действительно (по умолчанию - домен, в котором значение было установлено)
		secure - логическое значение, показывающее требуется ли защищенная передача значения cookie
....................................................... */
	function setCookie(name, value, expires, path, domain, secure) {
		document.cookie = name + "=" + escape(value) +
			((expires) ? "; expires=" + expires : "") +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			((secure) ? "; secure" : "");
	}
/* .......................................................
	Функция чтения значения cookie
		Возвращает установленное значение или пустую строку, если cookie не существует
		name - имя считываемого cookie
....................................................... */
	function getCookie(name) {
		var prefix = name + "="
		var cookieStartIndex = document.cookie.indexOf(prefix)
		if (cookieStartIndex == -1)	return null
		var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
		if (cookieEndIndex == -1)	cookieEndIndex = document.cookie.length
		return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
	}
/* .......................................................
	Функция чтения значения масива из cookie
		Возвращает установленное значение или пустую строку, если cookie не существует
		aname - имя считываемого масива
		akey	- ключ
....................................................... */
	function getCookieArrayValue(aname,akey) {
		var result = null;
		var string = getCookie(aname);
		if(string){
			prefix = akey+":";
			cookieStartIndex = string.indexOf(prefix)
			if (cookieStartIndex == -1)	return null
			cookieEndIndex = string.indexOf(",", cookieStartIndex)
			if (cookieEndIndex == -1)	cookieEndIndex = string.length
			result = string.substring(cookieStartIndex + prefix.length, cookieEndIndex)
		}
		return result;
	}
/* .......................................................
	Функция установки значения масива в cookie
		name - имя cookie
		value - значение cookie
		expires - дата окончания действия cookie (по умолчанию 0 - до конца сессии)
		path - путь, для которого cookie действительно (по умолчанию - документ, в котором значение было установлено)
		domain - домен, для которого cookie действительно (по умолчанию - домен, в котором значение было установлено)
		secure - логическое значение, показывающее требуется ли защищенная передача значения cookie
....................................................... */
	function setCookieArrayValue(aname, akey, value, expires, path, domain, secure) {
		var result = akey+":"+value+",";
		var string = getCookie(aname);
		if(string){
			prefix = akey+":";
			cookieStartIndex = string.indexOf(prefix)
			if (cookieStartIndex == -1){
				result = string + result
			}else{
				cookieEndIndex = string.indexOf(",", cookieStartIndex)
				if (cookieEndIndex == -1)	cookieEndIndex = string.length
				result = string.substring(0,cookieStartIndex) + result + string.substring(cookieEndIndex+1,string.length) 
			}
		}
		setCookie(aname, result, expires, path, domain, secure)
	}

//===========================================
//  контроль длины вводимого текста
//===========================================
function cnter(MaxLen,idText) {
//===========================================
	var Otext = document.getElementById(idText);
	if (Otext){
		if(Otext.value.length > MaxLen) {
			Otext.value = Otext.value.substring(0,MaxLen);
			alert("Это поле не может быть длиннее "+MaxLen+" символов.");
			Otext.focus();
		}
	}
}


function chekSum(checkValue,map){
  out = 0;
  for(c=0;c<map.length;c++){out+=map[c]*checkValue[c];}
  return ((cn=out%11)>9)?cn%10:cn;
}
//===========================================
function isEmpty(str) {
//===========================================
// проверка элемента формы на заполненность
//===========================================
	for (var i = 0; i < str.length; i++)
		if (" " != str.charAt(i))
			return false;
	return true;
}
 
// ........................................................
// Проверка введенных данных
	function checkInputValue(idInput,type){
		var oInput = document.getElementById(idInput);
		if (oInput){
			var iclass = oInput.getAttribute(classFix);
			if (iclass){
				var pos = iclass.indexOf("errorfield");
				if(pos>=0){ 
					if(pos==0) oInput.removeAttribute(classFix);
					else oInput.setAttribute(classFix,iclass.substr(0,pos-1));
				}
			}
			switch(type){
				case "int": // положительное целое
					if(oInput.value != oInput.value*1 || !(oInput.value>=0)){
						alert("Ошибка заполнения: Введите положительное целое число!");
						oInput.value = 0;
						oInput.focus();
						if(oInput.getAttribute(classFix) && oInput.getAttribute(classFix).length>0){
							oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
						}else{
							oInput.setAttribute(classFix,"errorfield");
						}
						return false;
					}else{
						oInput.value = Math.abs(Math.round(oInput.value));
						return true;
					}
				break;
				case "price":
					if(oInput.value.match(new RegExp("^[0-9]+\.[0-9][0-9]$","i"))) {
						return true;
					} else {
						alert("Ошибка заполнения: Введите цену!");
						oInput.focus();
						if(oInput.getAttribute(classFix) && oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
						else oInput.setAttribute(classFix,"errorfield");
						return false;
					}
				break;
				case "kpp":
					if(oInput.value.length!=9 || !oInput.value.match(new RegExp("^[0-9]+$","i"))) {
						alert("Ошибка заполнения: Введите КПП!");
						oInput.focus();
						if(oInput.getAttribute(classFix) && oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
						else oInput.setAttribute(classFix,"errorfield");
						return false;
					}
					return true;
				break;
				case "zip":
					if(oInput.value.length!=6 || !oInput.value.match(new RegExp("^[0-9]+$","i"))) {
						alert("Ошибка заполнения: Введите почтовый индекс!");
						oInput.focus();
						if(oInput.getAttribute(classFix) && oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
						else oInput.setAttribute(classFix,"errorfield");
						return false;
					}
					return true;
				case "rs":
					if(oInput.value.length!=20 || !oInput.value.match(new RegExp("^[0-9]+$","i"))) {
						alert("Ошибка заполнения: Введите номер расчетного счета!");
						oInput.focus();
						if(oInput.getAttribute(classFix) && oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
						else oInput.setAttribute(classFix,"errorfield");
						return false;
					}
					return true;
				break;
				///////////////////////
				/*
						case "inn":
							var checkValueArray = Value.split("");
							if(checkValueArray.length==10) {
								cn = chekSum(checkValueArray, [2,4,10,3,5,9,4,6,8,0]);
								if(cn!=checkValueArray[9]){
									return false;
								}
							} else if(checkValueArray.length==12) {
								cn1 = chekSum(checkValueArray, [7,2,4,10,3,5,9,4,6,8,0]);
								cn2 = chekSum(checkValueArray, [3,7,2,4,10,3,5,9,4,6,8,0]);
								if(cn1!=checkValueArray[10]&&cn2!=checkValueArray[11]){
									return false;
								}
							} else {
							  return false;
							}
							return true;
						break;
				*/
				////////////////////////
				case "email": // email
					var re_mail = /([\w\.\-_]+@[\w\.\-_]+)/;
					if(oInput.value.match(re_mail)!=null){
						return true;
					}else{
						alert("Ошибка заполнения: Введите e-mail!");
						oInput.focus();
						if(oInput.getAttribute(classFix) && oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
						else oInput.setAttribute(classFix,"errorfield");
						return false;
					}
				break;
				case "pwd": // пароли
					var oReInput = document.getElementById("re"+idInput);
					if (oReInput){
						var iclass = oReInput.getAttribute(classFix);
						if (iclass){
							var pos = iclass.indexOf("errorfield");
							if(pos>=0){ 
								if(pos==0) oReInput.removeAttribute(classFix);
								else oReInput.setAttribute(classFix,iclass.substr(0,pos-1));
							}
						}
						if(oInput.value.length>=3 && oReInput.value==oInput.value){
							return true;
						}else if(oInput.value.length<3){
							alert("Ошибка заполнения: Слишком короткий пароль");
							oInput.value = ""; 
							oReInput.value = "";
							oInput.focus();
							if(oInput.getAttribute(classFix) && oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
							else oInput.setAttribute(classFix,"errorfield");
							if(oReInput.getAttribute(classFix) && oReInput.getAttribute(classFix).length>0) oReInput.setAttribute(classFix,oReInput.getAttribute(classFix)+" errorfield");
							else oReInput.setAttribute(classFix,"errorfield");
							return false;
						}else{
							alert("Ошибка заполнения: Введенные пароли не совпадают!");
							oInput.value = ""; 
							oReInput.value = "";
							oInput.focus();
							if(oInput.getAttribute(classFix) && oInput.getAttribute(classFix).length>0) oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
							else oInput.setAttribute(classFix,"errorfield");
							if(oReInput.getAttribute(classFix) && oReInput.getAttribute(classFix).length>0) oReInput.setAttribute(classFix,oReInput.getAttribute(classFix)+" errorfield");
							else oReInput.setAttribute(classFix,"errorfield");
							return false;
						}
					}else{
						alert("Ошибка: Отсутствует поле подтверждения пароля");
					}

				break;
				case "short": // не пустое короткое
					if(oInput.value.length>=1){
						return true;
					}else{
						alert("Ошибка заполнения: Введите текст!");
						oInput.focus();
						if(oInput.getAttribute(classFix) && oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
						else oInput.setAttribute(classFix,"errorfield");
						return false;
					}
				break;
				default: // не пустое
					if(oInput.value.length>=3){
						return true;
					}else{
						alert("Ошибка заполнения: Введите текст!");
						oInput.focus();
						if(oInput.getAttribute(classFix) && oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
						else oInput.setAttribute(classFix,"errorfield");
						return false;
					}
				break;
			}
		}else{
			return true;
		}
	} 


/* .......................................................
	Функция для получения времени в формате GMT
....................................................... */
	function getTimeGMT(hours) {
		var exp = new Date();
		exp.setTime(exp.getTime() + 3600000*hours);
		return exp.toGMTString();
	}

//===========================================
function showPic(w,h,pic,alt,prn) {
//===========================================
	w1 = w + 50;
	h1 = h + 110;
	if (typeof(tz)=='object') tz.close();
	tz=window.open("","wnd","width="+w1+",height="+h1+",status=no,left="+(screen.width-w1)/2+",top="+(screen.height-h1)/2+",toolbar=no,menubar=no,resizable=no,scrollbars=no")
	tz.document.open();
	tz.document.write('<html><title>'+alt+'</title><BASE href="'+base+'"><link rel=stylesheet type="text/css" href="./data/styles/style.css"><body onload="self.focus();" class=popup><P align=center style="padding-top:7px" class=small><a href="javascript:window.close();"><img src="'+base+pic+'" width='+w+' height='+h+' border=0 alt="Закрыть" style="margin-bottom:5px;"></a><br>'+alt);
	tz.document.write('<br><br><a href="javascript: self.');
	if (prn==1) {tz.document.write('print();">Распечатать');}
	else {tz.document.write('close();">Закрыть окно')}
	tz.document.write("</a></P>");
	tz.document.write("</body></html>");
	tz.document.close();
	return false;
} 

