var baseUrl = document.getElementsByTagName("base")[0].href;
var isMOZ=(typeof(document.addEventListener)!="undefined")?true:false;
var isIE = (isMOZ)?false:true;
var imgPath = "images";
var popupWinWidth = 770;
var popupWinHeight = 650;
//var ballr = new Image(10,9);ballr.src ="/"+imgPath+'/ballr.gif';
//var ballc = new Image(10,9);ballc.src ="/"+imgPath+'/ballc.gif';


function $(id){
	return (id==null)?null:document.getElementById(id);
}

function bindEvent(evName,func,obj) {
	if (typeof(func)!="function") return;
	var root = window.addEventListener || window.attachEvent ? window : document.addEventListener ? document : null;
	if (obj && typeof(obj)=="object") {
		root=obj;
	}
	if (root) {
		try {
			if (root.addEventListener) root.addEventListener(evName, func, false);
			else if (root.attachEvent) root.attachEvent("on"+evName, func);
		}
		catch (err) {}
	}
}

function setPopupWinWidth(val) {
	popupWinWidth = val;
}
function setPopupWinHeight(val) {
	popupWinHeight = val;
}
function getPopupWinWidth() {
	return (popupWinWidth || popupWinWidth == 0) ? popupWinWidth : 750;
}
function getPopupWinHeight() {
	return (popupWinHeight || popupWinHeight == 0) ? popupWinHeight : 550;
}

function url(newUrl, target, flag, winName) {
	var newUrl = baseUrl + newUrl;
	var targetFrame = null;
	if (winName==null || winName=="") winName="_blank";
	if (target == "_blank") {
		var oWin =null;
		oWin = window.open(newUrl, winName, "height=" + getPopupWinHeight() + ",width=" + getPopupWinWidth() + ",status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,resizable=yes,channelmode=no");
		return oWin;
	} else if (!target || target == "_self") {
		targetFrame = self;
	} else if (self.frames[target]) {
		targetFrame = getFrame(self, target);
	} else {
		alert("Frame " + target + " does not exists.");
	}
	if (targetFrame) {
		if (flag != null && flag) targetFrame.location.replace(newUrl);
		else  targetFrame.location.href = newUrl;
	}
	return targetFrame;
}

function stopEvent(e) {
	var e = window.event ? window.event : (e == null)?null:e;
	if (e != null) {
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	}
	return false;
}

var myWinOpened=0;
function OpenImgWin(name,w,h,comm) {
	if (myWinOpened) { if (!myWin.closed) myWin.close();} 
	if (w==null) w=getPopupWinWidth();
	if (h==null) h=getPopupWinHeight();
	var flag=true;
	if (comm==null || comm=="") { comm="Просмотр изображения"; flag=false;}
	myWin = open("", "imgwin","width="+(parseInt(w)+80)+", height="+(parseInt(h)+100)+", toolbar=no,status=no,scrollbars=yes,resizable=yes, directories=no, location=no");
	myWin.document.open();
	myWin.document.write("<html><head><title>"+comm);
	myWin.document.write("</title></head><body style='overflow:auto' bgcolor=white >");
	if (flag) myWin.document.write("<br><center><table><caption style='color:#022EC5;'>"+comm+"</caption>");
	else myWin.document.write("<br><center><table>");
	myWin.document.write("<tr><th><img src='"+baseUrl+name+"'></th><tr>");
	myWin.document.write("<tr><td align=center><br><a href='javascript:close()' style='color:#0053C5;font-size: 12px;'>Закрыть это окно.</a></td></tr>");
	myWin.document.write("</table></center></body></html>");
	myWin.document.close();
	myWinOpened=1;
}

function getFrame(win, target) {
	for (var i = 0; i < win.frames.length; i++) {
		if (win.frames[i].name == target) {
			return win.frames[i];
		}
	}
	return null;
}

function getObj(obj) {
	var o=null;
	if(obj==null || obj=="") return o;
	if (typeof(obj)=="object") o=obj;
	else o=$(obj);
	return o;
}
function show_hide(obj,mode) {
	var o=getObj(obj);
	if(o == null) return;
	var act="";
	if (mode==1) act="";
	else act="none";
	o.style.display=act;
}

function enable(obj) {
	var o=getObj(obj);
	if(o == null) return;
	o.removeAttribute("disabled");
}

function disable(obj) {
	var o=getObj(obj);
	if(o == null) return;
	o.setAttribute("disabled",true);
}

function getPrevSiblingTag(obj,depth) { // depth -  show the number of object to find in hierarchy
	var d=(depth!=null && typeof(depth)!="undefined")?parseInt(depth):0;
	if (isNaN(d)) d=0;
	if (d<0) d=0;
	var tmpObj = obj;
	while (tmpObj) {
		tmpObj = tmpObj.previousSibling;
		if (tmpObj && tmpObj.tagName) {
			if (d==0) {
				return tmpObj;
			}
			d=d-1;
		}
	}
	return null;
}

function getNextSiblingTag(obj) {
  var tmpObj = obj;
  while (tmpObj) {
    tmpObj = tmpObj.nextSibling;
    if (tmpObj && tmpObj.tagName) {
      return tmpObj;
    }
  }
  return null;
}

function show_flash(src, w, h, loop){
	loop=(loop==null)? true:loop;
	str = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="'+w+'" HEIGHT="'+h+'" >\n ';
	str += '<PARAM NAME=movie VALUE="'+src+'.swf"> <PARAM NAME=menu VALUE="false"> <PARAM NAME=quality VALUE="high"> <PARAM NAME=play VALUE="true"> <PARAM NAME=LOOP VALUE="'+loop+'"> <PARAM NAME=scale VALUE="exactfit">\n';
	str += '<EMBED src="'+src+'.swf" menu=false quality=high loop='+loop+' WIDTH="'+w+'" HEIGHT="'+h+'" scale=exactfit  TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED> \n'; 
	str += '</OBJECT>';
	document.write(str);
}

function checkmail(str) {
	var i2;
	if (str == '') return true;
	i1 = str.lastIndexOf("@",str.length-1);
	i2 = str.lastIndexOf(".",str.length-1);
	if (i2 >i1) return true; else return false;
}

function checknumber(object_value) {
  //Returns true if value is a number or is NULL
  //otherwise returns false
  if (object_value.length == 0) {
    return true;
  }
	var arr = object_value.split(",");
	object_value=arr.join(".");
  return object_value.match('^([\-]){0,1}([0-9]+)([\.]){0,1}([0-9]*)$');
}

function check(form,len,useCaptcha) {
	var f=form;
	var l= (len==null) ? 2:len;
	var fieldName= "";
	var elem=null;
	var reqField=null;
	for (var i=0; i < f.elements.length; i++ ) {
		elem=f.elements[i];
		reqField=elem.getAttribute("requied");
	//	alert(i+") "+elem.name+"["+elem.type+"]="+elem.value+" -> "+reqField+"{"+(reqField==null)+"}");
		if (reqField==null) continue;

		if (elem.name.indexOf("date")>=0) {
			if (elem.type!="hidden") { continue;}
 			selName=elem.name.substring(0,elem.name.length-2);
			//alert(selName);
			Yf=f.elements[selName+"Year"].options[f.elements[selName+"Year"].selectedIndex]; 
			Mf=f.elements[selName+"Month"].options[f.elements[selName+"Month"].selectedIndex]; 
			Df=f.elements[selName+"Day"].options[f.elements[selName+"Day"].selectedIndex]; 
			//   alert(Yf.text+"\n"+Mf.text+"\n"+Df.text+"\n");   
			if  ( (Mf.text==2 || Mf.text==4 || Mf.text==6 || Mf.text==9 || Mf.text==11) && Df.text==31 ) {Df.text=30;}
			elem.value=Yf.text+"-"+Mf.text+"-"+Df.text+" 00:00:00";
			continue;
		}

		var requiedLength=(isNaN(parseInt(reqField)))?l:reqField;
		fieldName= (elem.getAttribute("title")==null) ? elem.name : '  "'+elem.getAttribute("title")+'"  ';
//				alert(elem.type+" ["+elem.name+"]->"+elem.value+"  ["+elem.value.length+"] =" +requiedLength);
		if ( (elem.type == "text" || elem.type == "textarea") && elem.value.length < requiedLength) {
			alert("Проверьте, правильность ввода поля "+fieldName+" формы!\nПоле не должно быть пустым или содержать меньше "+requiedLength+" символов(а)");
			if (useCaptcha && refreshCaptcha) refreshCaptcha();
			return false;
		}
		if (elem.type == "text" && elem.name.indexOf("mail")!=-1 && !checkmail(elem.value)) {
			alert("Проверьте, пожалуйста, правильность ввода поля:  "+fieldName+" ! ");
			if (useCaptcha && refreshCaptcha) refreshCaptcha();
			return false;
		}
		if (elem.type == "select-one" && elem.options[elem.selectedIndex].value == "-1") {
			alert("Не выбран ни один элемент в выпадающем списке "+fieldName);
			if (useCaptcha && refreshCaptcha) refreshCaptcha();
			return false;
		}
	 }
	return true;
}

function openFull (link,w,h) {
	if (w!=null && !isNaN(parseInt(w))) {
		setPopupWinWidth(w);
	}
	if (h!=null && !isNaN(parseInt(h))) {
		setPopupWinHeight(h);
	}
	url(link,"_blank",null,"miscwin");
}

function replaceUrlSubstringByPattern(str,p,r) {
	if (str==null || p==null || p=="") return false;
	if (r==null) r="";
	var ind1 = (str.indexOf("?"+p) != -1 ) ? str.indexOf("?"+p) : str.indexOf("&"+p);
	if (ind1 < 0 ) return false;
	ind1++;
	var ind2=str.indexOf("&",ind1);
	if (ind2<0) ind2=str.length;
	var newUrl = str.substring(0,((r=="")?(ind1-1):ind1))+r+str.substring(ind2,str.length);
	return newUrl;
}

function refreshCaptcha() {
	var img=document.getElementById('captcha');
	if (img) {
		var src= ((img.src.indexOf("?")!=-1)?img.src.substring(0, img.src.indexOf("?")):img.src)+"?"+Math.random();
		img.src=src;
	}
}

function showRegName(sel) {
	if (!sel || sel.tagName.toLowerCase()!="select") {
		sel=$('register');
		if(!sel) return;
	}
	var o=$("compname");
	var o1=$("fio");
	if (!o || !o1) return;
	var fc=$("company");
	var ff=$("f");
	var fi=$("i");
	switch(sel.value) {
		case "1":show_hide(o,0);show_hide(o1,1);
					if (fc) fc.removeAttribute("requied");
					if (ff) ff.setAttribute("requied",true);
					if (fi) fi.setAttribute("requied",true);
					break;
		case "2":
		case "3":show_hide(o,1);show_hide(o1,0);
					if (fc) fc.setAttribute("requied",true);
					if (ff) ff.removeAttribute("requied");
					if (fi) fi.removeAttribute("requied");
					break;
	}
	return true;
}

function throwMess(mess,span) {
	if(!mess) return;
	if(span) {
		span.innerHTML=mess;
		span.style.display="";
	}
	else alert(mess.replace(/<br>/gi,"\n"));
}

function displaypswd(obj,mode) {
	if (!obj) return;
	var f=null;
	obj.style.display="none";
	if (mode) {
		f=getNextSiblingTag(obj);
	}
	else {
		f=getPrevSiblingTag(obj);
	}
	if (f) f.style.display="";
	if (mode) f.focus();
}

function getIframeBody() {
	var iframeWin = getFrame(self,"someframe");
	var tag = $("displayFormHere");
	if (!iframeWin || !tag || self.parent!=self) return;
	var ifrDoc,ifrTag,ifrHelpTag;
	try {
		ifrDoc=iframeWin.document;
/*		if (oFrame.contentDocument ) 
			ifrDoc=oFrame.contentDocument;
		else 
			ifrDoc=oFrame.contentWindow.document;*/
		ifrHelpTag=ifrDoc.getElementById("formDivLoaded");
	}
	catch(e) {setTimeout("getIframeBody()",200);}

	if (!ifrHelpTag) setTimeout("getIframeBody()",200);
	else {
		ifrTag = ifrDoc.getElementById("editFormBody");
		tag.innerHTML=ifrTag.innerHTML;
		iframeWin.location.href = "about:blank";
		var button=$("go");
		if (ifrHelpTag.getAttribute("result")==1) {
			if(button) button.removeAttribute("disabled");
		}
		else {
			if(button) button.setAttribute("disabled",true);
		}
	}
}

function _getForm() {
	var obj=$("sfera");
	var ifr=$("someframe");
	if (!obj || !ifr) return;
	var id=obj.value;
	ifr.src=baseUrl+"catalog/getform.php?lid="+id;
	getIframeBody();
	obj.blur();
}

function counttext(obj,max) {
	if (!obj) return;
	var f=obj.form;
	if(!f) return;
	var c=obj.getAttribute("count");
	if (c){
		var cf=f.elements[c];
		if (cf) cf.value=obj.value.length;
	}
	if (obj.value.length>max) {
		obj.value=obj.value.substring(0,max);
	}
}

function checkNumbers(pole) {
	pole.value=trim(pole.value);
	if (pole.value=="") return true;
	number= parseInt(pole.value,10); 
	if ( isNaN(number) == true) {
		number="";
		alert("Некорректно введено значение поля! Это поле может содержать только цифры и символ минуса.");
	}
	pole.value = number;
}

function checkFloat(pole) {
	var flag=true;
	pole.value=trim(pole.value);
	if (pole.value=="") return true;
	var arr = pole.value.split(",");
	pole.value=arr.join(".");
	floatnumber= parseFloat(pole.value,10); 
	if ( isNaN(floatnumber) == true) {floatnumber=0; flag=false;}
	pole.value = floatnumber;
	if (!flag) alert("Некорректно введено значение поля.\nЭто поле может содержат только цифры, символ точки и и символ минуса.\nПример воода: 15.40");
	return flag;
}

function onlyDigits(obj) {
	return checkFormat(obj,"0-9-");
}

function onlyFloat(obj) {
	return checkFormat(obj,"0-9.-");
}

function auth() {
	var obj=$("authButton");
	if (obj && obj.onclick) obj.onclick();
}
