var base ="";
function SetBase(b) {base = b;}

	function fillTables(contentBlockId,headerNeed) {
		if(document.getElementsByTagName){
			var items = document.getElementById(contentBlockId).getElementsByTagName("TABLE");
			for(var i=0;i<items.length; i++){
				var nodes = items[i].getElementsByTagName("TR");
				var start = 0;
				if (headerNeed){
					nodes[0].setAttribute(classFix,"color_2");
					start = 1;
				}
				for(var j=start;j<nodes.length; j++){
					if (nodes[j].getAttribute(classFix)==""){
						nodes[j].setAttribute(classFix,"color_"+(j%2));
					}
				}
			}
		}
	}	
//===========================================
function ElementClick(id,folder,server,refresh){
//===========================================
// Установка Cookie для раскрытия подразделов {0,1}
// 0 - цепочка закрыта
// 1 - цепочка открыта
//===========================================
	var classFix = (document.all)?"className":"class";
	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
name - имя cookie
value - значение cookie
expires - дата окончания действия cookie (по умолчанию - до конца сессии)
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 устанавливается с заведомо устаревшим параметром 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"
        }
}

//===========================================
//  контроль длины вводимого текста
//===========================================
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 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;
		}
	}
	
function showFlash(w, h, path) {
//===========================================
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="'+w+'" height="'+h+'" id="flash_map3" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="'+path+'" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><embed src="'+path+'" quality="high" bgcolor="#ffffff" width="'+w+'" height="'+h+'" name="flash_map3" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
document.write (str);
} 
function showFlashtrans(w, h, path) {
//===========================================
var str='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'+w+'" height="'+h+'" id="flash_logo" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="'+path+'" /><param name="wmode" value="transparent" /><param name="quality" value="high" /><param name="bgcolor" value="#666666" /><embed src="'+path+'" quality="high" wmode="transparent" bgcolor="#666666" width="'+w+'" height="'+h+'" name="'+path+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
document.write (str);
} 

