var base ="";
function SetBase(b) {base = b;}

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));
						}
					}
				}
			}
		}
	}	
	function fillTables1(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,"line_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,"line_"+(j%2));
						}
					}
				}
			}
		}
	}	
//===========================================
function ElementClick(id,folder,server,refresh){
//===========================================
// Установка Cookie для раскрытия подразделов {0,1}
// 0 - цепочка закрыта
// 1 - цепочка открыта
//===========================================
	var oLink = document.getElementById("childs_"+id);	
	var oSign = document.getElementById("sign_"+id);	
	var str;
	var expiryDate = new Date();
	expiryDate.setTime(expiryDate.getTime() + 24*60*60*1000);
	setCookie("element["+id+"]", 1 - getCookie("element["+id+"]"),expiryDate.toGMTString(),folder,server);
	if (refresh) return true;
	if(getCookie("element["+id+"]")==1){
		if(oLink){oLink.setAttribute(classFix,"in");}
		if(oSign){
			str=oSign.innerHTML;
			str=str.replace("plus","minus");
			str=str.replace("Раскрыть","Закрыть");
			oSign.innerHTML=str;
		}
	}else{
		if(oLink){oLink.setAttribute(classFix,"hidden");}
		if(oSign){
			str=oSign.innerHTML;
			str=str.replace("minus","plus");
			str=str.replace("Закрыть","Раскрыть");
			oSign.innerHTML=str;
		}
	}
	return false;
} 

/*
Функция удаления значения 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 changeImages() {
//===========================================
	d = document;
	if (d.images) {
		var img;
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			img = null;
			img = document.getElementById(changeImages.arguments[i]);
			if (img) {img.src = base+changeImages.arguments[i+1];}
		}
	}
}
//===========================================
//  Проверка заполненности полей формы
//===========================================
function check(content) {
//===========================================
	check_fld = new Array ();
	if(content=="menu") {
		check_fld=new Array ("name","url");
		check_hdr=new Array ("Название","Путь");
	}
	if(content=="order") {
		check_fld=new Array ("person");
		check_hdr=new Array ("ФИО");
	}
	if(content=="price") {
		check_fld=new Array ("cname","cphone","cmail","сaddress");
		check_hdr=new Array ("Контактное лицо","Телефон","Email","Адрес");
	}
  // проверка заполнения полей формы 
	for ( i = 0; i <= check_fld.length-1; i++) {
		if (isEmpty(document.getElementById(check_fld[i]).value)) {
			alert('Не заполнено обязательное поле "'+check_hdr[i]+'".');
			document.getElementById(check_fld[i]).focus();
			return false;
		}
	}
	return true;
}

//===========================================
function CheckForm111(form) {
//===========================================
//  Проверка заполненности полей формы
//===========================================
	var errMSG = "";
	var errFLD = -1;
	for (var i = 0; i < form.elements.length; i++) { 
	  if (null!=form.elements[i].getAttribute("required")) { 
		if (isEmpty(form.elements[i].value)) {
		  errMSG += form.elements[i].getAttribute("info") + "\n";
						if (errFLD==-1) errFLD=i;
		 }
	   }
	}
	if ("" != errMSG) {
	   alert("Не заполнены обязательные поля:\n\n" + errMSG);
	   form.elements[errFLD].focus();
	   return false;
	}
	return true;
  }

function CheckForm(form) {
    var Message = "Необходимо заполнить поля \n\n";
    var focus = null;
    var result = true;
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].getAttribute("require") == "true") {
            var doc = document.getElementById(form.elements[i].name);
            var match = "";
            if(null != form.elements[i].getAttribute("match")) {
                match = form.elements[i].getAttribute("match");
            }
            if(!CheckValue(form.elements[i].value, match)) {
                if(focus == null) {
                      form.elements[i].focus();
                      focus = true;
                }
                Message += form.elements[i].getAttribute("info") + "\n";
                result = false;
           }
       }
    }
    if(!result) {
        alert(Message);
    }
    return result;
}


function CheckValue(Value, Match) {
    switch(Match) {
        case "email":
            if(!(Value.length>0&&Value.match(new RegExp("^[a-z0-9_]+@([a-z0-9_]+\.)+[a-z]+$","i")))){
                return false;
            }
            return true;
        break;

        case "kpp":
          if(Value.length!=9) return false;
          if(!Value.match(new RegExp("^[0-9]+$","i"))) {
              return false;
          }
          return true;
        break;

        case "zip":
          if(Value.length!=6) return false;
          if(!Value.match(new RegExp("^[0-9]+$","i"))) {
              return false;
          }
          return true;
        break;

        case "rs":
            if(Value.length < 20) {
                if(Value.match(new RegExp("^[0-9]+$", "i"))) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        break;

        case "phone":
            if(!Value.match(new RegExp("^[0-9 \(\)\+\-]+$","i"))) {
                return false;
            }
        return true
        break;

        case "digit":
            if(!Value.match(new RegExp("^[0-9]+$","i"))) {
                return false;
            } else {
                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;

        default:
            if(Value == "") {
                return false;
            } else {
                return true;
            }
        break;
    }
}

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 showPic(w, h, pic, alt, prn) {
//===========================================
	w1 = w + 30;
	h1 = h + 70;
	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=photo><div class=all align=center style="margin:10px;"><P><a href="javascript:window.close();"><img src="./'+pic+'" width='+w+' height='+h+' border=0 alt="Закрыть" class=bordered></a></P><P>'+alt+'</P><a href="javascript: self.');
	if (prn==1) {tz.document.write('print();">Распечатать');}
	else {tz.document.write('close();">Закрыть окно')}
	tz.document.write("</a>");
	tz.document.write("</body></html>");
	tz.document.close();
} 
//===========================================
function showMore(url, w1, h1) {
//===========================================
	window.open(url,"","width="+w1+",height="+h1+",status=no,left="+(screen.width-w1)/2+",top="+(screen.height-h1)/2+",toolbar=no,menubar=no,scrollbars=yes");
	return false;
} 


function setCookie111 (name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "")
}

  // ........................................................
// Проверка введенных данных
	function checkInputValue(idInput,type){
		var oInput = document.getElementById(idInput);
		var iclass = oInput.getAttribute(classFix);
		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 0: // положительное целое
				if(oInput.value != oInput.value*1 || !(oInput.value>=0)){
					alert("Ошибка заполнения:\nВведите положительное целое число!");
					oInput.value = 0;
					oInput.focus();
					if(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 1: // email
				var re_mail = /([\w\.\-_]+@[\w\.\-_]+)/;
				if(oInput.value.match(re_mail)!=null){
					return true;
				}else{
					alert("Ошибка заполнения:\nВведите email адрес!");
					oInput.focus();
					if(oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
					else																				oInput.setAttribute(classFix,"errorfield");
					return false;
				}
			break;
			case 2: // пароли
				var oReInput = document.getElementById("re"+idInput);
				iclass = oReInput.getAttribute(classFix);
				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("Ошибка заполнения:\nСлишком короткий пароль");
					oInput.value = ""; 
					oReInput.value = "";
					oInput.focus();
					if(oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
					else																				oInput.setAttribute(classFix,"errorfield");
					if(oReInput.getAttribute(classFix).length>0)	oReInput.setAttribute(classFix,oReInput.getAttribute(classFix)+" errorfield");
					else																				oReInput.setAttribute(classFix,"errorfield");
					return false;
				}else{
					alert("Ошибка заполнения:\nВведенные пароли не совпадают!");
					oInput.value = ""; 
					oReInput.value = "";
					oInput.focus();
					if(oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
					else																				oInput.setAttribute(classFix,"errorfield");
					if(oReInput.getAttribute(classFix).length>0)	oReInput.setAttribute(classFix,oReInput.getAttribute(classFix)+" errorfield");
					else																				oReInput.setAttribute(classFix,"errorfield");
					return false;
				}
			break;
			default: // не пустое
				if(oInput.value.length>=3){
					return true;
				}else{
					alert("Ошибка заполнения:\nВведите текст!");
					oInput.focus();
					if(oInput.getAttribute(classFix).length>0)	oInput.setAttribute(classFix,oInput.getAttribute(classFix)+" errorfield");
					else																				oInput.setAttribute(classFix,"errorfield");
					return false;
				}
			break;
		}
	} 


/* .......................................................
	Версия для печати
....................................................... */
var cmsPrintObject = null;
var cmsHideObject = null;
function PrintVersion(){
	if(cmsPrintObject==null){

		cmsPrintObject = document.createElement("div");
		cmsPrintObject.setAttribute(classFix,"printversion");

		var cmsPrintHeader = document.createElement("div");
		cmsPrintHeader.innerHTML = "<p align=right><small><a href='javascript:self.print();'>печать | print</a></small></p><h1>"+document.title+"</h1><small>url: <a href='javascript:PrintVersion();'>"+self.location.href+"</small></a><br><br>";
		
		cmsPrintObject.appendChild(cmsPrintHeader);
		cmsPrintObject.appendChild(document.getElementById("nodecontent").cloneNode(1));
		
		cmsHideObject = document.createElement("div");
		cmsHideObject.innerHTML = document.body.innerHTML;
		document.body.innerHTML = "";
		cmsHideObject.style.display = "none";
		
		document.body.appendChild(cmsPrintObject);
		document.body.appendChild(cmsHideObject);
	}else{
		document.body.innerHTML = cmsHideObject.innerHTML;
		cmsPrintObject = null;
		cmsHideObject = null;
	}
}
/* .......................................................
	Функция для получения времени в формате GMT
....................................................... */
	function getTimeGMT(hours) {
		var exp = new Date();
		exp.setTime(exp.getTime() + 3600000*hours);
		return exp.toGMTString();
	}

/* .......................................................
	Открытия картинки в новом окне
....................................................... */
	var imageWindow;
	function openimage(src,title){ 
		var wWidth = 510;
		var wHeight = 400;
		imageWindow=window.open("","blankImageWindow", 'status=no,scrollbars=no,resizable=yes,width='+(wWidth)+',height='+(wHeight)+'');
			imageWindow.document.write("<html><head><title>"+title+"</title>");
			imageWindow.document.write("<body topmargin=0 marginheight=0 leftmargin=0 marginwidth=0 bgcolor=white text=black link=black alink=black vlink=black "); 
			imageWindow.document.write("onload=\"self.resizeTo(document.getElementById('image').width+25,document.getElementById('image').height+40);\">");
			imageWindow.document.write("<table border=0 cellspacing=0 cellpadding=0 width=100% height=100%><tr><td align=center>");
			imageWindow.document.write("<a href='javascript:self.close();' title='закрыть окно'><img src='"+src+"' border=0 id=image style='padding:1px;border:#365591 solid 1px;'></a>");
			imageWindow.document.write("</td></tr></table>");
			imageWindow.document.write("</body></html>");
			imageWindow.document.close();
		imageWindow.focus();
	}

	function get_position(obj,pos){
		if(obj.tagName!="TR" && obj.tagName!="FORM"){
			pos[0] += obj.offsetLeft;
			pos[1] += obj.offsetTop;
			pos[2] = obj.tagName + " ("+ obj.offsetLeft+", "+obj.offsetTop+")\n" + pos[2];
		}
		if(obj.parentNode.tagName != "HTML") pos = get_position(obj.parentNode,pos);
		return pos;
	}

	function overimage(oImage,visible){ 
		var oiLink = document.getElementById("ilink");
		if(visible){
			oiLink.setAttribute(classFix,"visible");
			var pos = new Array(0,0,"");
			get_position(oImage,pos);
			//alert(pos[2]);
			oiLink.style.left = pos[0]-oiLink.offsetWidth-25+oImage.offsetWidth;
			oiLink.style.top = pos[1]-oiLink.offsetHeight-25+oImage.offsetHeight;
		}else{
			oiLink.setAttribute(classFix,"hidden");	
		}
	}
