function ge(id){return document.getElementById(id);}
function cutpx(str){
	strout=str.replace('px','');
	strout=strout.replace('NaN','');
	return strout;
}
/* function absPosition(obj) выдает позицию html элемента
 *
*/
function absPosition(obj) {
	this.x = 0;
	this.y = 0;
    while(obj!=null) {
		this.x += (obj.offsetLeft)?obj.offsetLeft:0;
		this.y += (obj.offsetTop)?obj.offsetTop:0;
		obj = (obj.offsetParent)?obj.offsetParent:null;
	}
	return {x:this.x,y:this.y};
}
// newImage(path) прогружает картинку по адресу
function newImage(path) {
	var image = new Image();
	image.src = path;
	return image;
}
// prepareRequest() подготовка для Ajax запроса
function prepareRequest() {
	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
	http_request = new XMLHttpRequest();
	if (http_request.overrideMimeType) {
		// See note below about this line
	}
	} else if (window.ActiveXObject) { // IE
	try {
		http_request = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			http_request = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {}
	}
	}
	if (!http_request) {
		alert('Error! Connot create XMLHTTP'); return false;
	}
	return http_request;
}

// переводит из десятичного в HEX
function decToHex(dec){
	var hexStr = "0123456789ABCDEF";
	var low = dec % 16;
	var high = (dec - low)/16;
	hex = "" + hexStr.charAt(high) + hexStr.charAt(low);
	return hex;
}
//нужна для кодирования post для Ajax
function kotUrlEncode(s) {
	n=s.length;
	tmpst='';
	for(i=0;i<n;i++){
		if((s.charCodeAt(i)>=1040)&&(s.charCodeAt(i)<=1103)){
			tmpst+='%'+decToHex(s.charCodeAt(i)-1040+192);
		}else if(s.charCodeAt(i)==1025){
			tmpst+='%'+decToHex(168);
		}else if(s.charCodeAt(i)==1105){
			tmpst+='%'+decToHex(184);
		}else if((s.charAt(i)=='%')||(s.charAt(i)=='&')||(s.charAt(i)=='+')||(s.charAt(i)=='?')){
			tmpst+='%'+decToHex(s.charCodeAt(i));
		}else{
			tmpst+=s.charAt(i);
		}
	}
	return tmpst;
}

var loadedtext='';
var HelpHintNode=false;
var ua = navigator.userAgent;
isMSIE = (navigator.appName == "Microsoft Internet Explorer");
isMSIE5 = isMSIE && (ua.indexOf('MSIE 5') != -1);
isMSIE5_0 = isMSIE && (ua.indexOf('MSIE 5.0') != -1);
isGecko = ua.indexOf('Gecko') != -1;
isSafari = ua.indexOf('Safari') != -1;
isOpera = ua.indexOf('Opera') != -1;
isMac = ua.indexOf('Mac') != -1;
isNS7 = ua.indexOf('Netscape/7') != -1;
isNS71 = ua.indexOf('Netscape/7.1') != -1;
if(isMSIE){
	sp='<BR>';
}else{
	sp='<br>';
}
// Удаляет подсказку
function KillHelpHint(){
	document.body.removeChild(HelpHintNode);
	HelpHintNode=false;
}
// показывает подсказку над html элементом
function ShowHelpHint(obj,text){
	//debugger;
	if(HelpHintNode!=false){
	KillHelpHint();
	}
	if(typeof(obj)!=='object'){
	  obj=ge(obj);
	}
	this.hlp=document.createElement('div');
	this.hlp.id='help_hint';
	pos=absPosition(obj);
	posoff=absPosition(document.body.firstChild);
	if(document.body.firstChild.style){
	posoff.x=posoff.x-cutpx(document.body.firstChild.style.marginLeft);
	}
	if(document.body.firstChild.style){
	posoff.y=posoff.y-cutpx(document.body.firstChild.style.marginTop);
	}
	text=text+' pos{x:'+pos.x+',y:'+pos.y+'} first{x:'+posoff.x+',y:'+posoff.y+'}';
	//this.hlp.innerHTML='help x:'+pos.x+' y:'+pos.y;
	this.hlp.style.position='absolute';
	this.hlp.style.zIndex='2';
	divtext=document.createElement('div');
	divtext.innerHTML=text;
	divtext.style.border='1px solid #000000';
	divtext.style.backgroundColor='#FFFFE1';
	divtext.style.fontSize='9px';
	divtext.style.fontFamily='Verdana, Geneva, Arial, Helvetica, sans-serif';
	divtext.style.fontWeight='bold';
	divtext.style.color='#FF0000';
	divtext.style.width='100px';
	divtext.style.opacity='0.5';
	divtext.style.mozOpacity='0.5';
	divtext.style.filter='alpha(opacity=50)';
	this.hlp.onclick=function() {KillHelpHint();};
	divtext.style.padding='5px';
	this.hlp.appendChild(divtext);
	this.hlp.style.marginLeft=pos.x-posoff.x+5;
	this.hlp.style.marginTop=pos.y-posoff.y;//-divtext.clientHeight
	document.body.insertBefore(this.hlp,document.body.firstChild);
	this.hlp.style.marginTop=pos.y-posoff.y-divtext.clientHeight-5;
	HelpHintNode=this.hlp;
}
//for Ajax
function changestate(http_request, prevDiv){
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			prevDiv.innerHTML = http_request.responseText;
		} else {
			prevDiv.innerHTML = 'There was a problem with the request.';
		}
		//prevDiv.innerHTML=loadedtext;
	}
}
// осуществляет запрос для ajax 
// пример: myrequest('http://mysite.com', Array('var1','var2'), Array('value1','value2'),'текстовое id html элемента')
// после запроса впишет в элемент полученое значение
function RequestHTML(url, vars, req_values, htmlhref){
	var http_request = prepareRequest();
	prevDiv = ge(htmlhref);
	prevDiv.innerHTML = '<img src="/system/admin_img/loading.gif">';
	http_request.onreadystatechange = function() { changestate(http_request, prevDiv); }
	http_request.open('POST', url)
	http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=windows-1251');
	myreq='';
	for(i in vars){
		if(i>0){
			myreq+='&';
		}
		myreq+=vars[i]+'='+kotUrlEncode(req_values[i]);

	}
	http_request.send(myreq);
}

function changestate2(http_request, func){
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			func(http_request.responseText);
		} else {
			func('Error: no response. ');
		}
	}
}
// осуществляет запрос для ajax 
// пример: myrequest('http://mysite.com', Array('var1','var2'), Array('value1','value2'),
//         function(e) {javasript фукция где e полученое значение по http})
function RequestFunc(url, vars, req_values, func){
	var http_req = prepareRequest();
	http_req.onreadystatechange = function() { changestate2(http_req, func); }
	http_req.open('POST', url)
	http_req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=windows-1251');
	myreq='';
	for(i in vars){
		if(i>0){
			myreq+='&';
		}
		myreq+=vars[i]+'='+kotUrlEncode(req_values[i]);

	}
	http_req.send(myreq);

}

function addEvent(o,ev,h){
	if(o.attachEvent){
		o.attachEvent('on'+ev,h);
	}else{
		o.addEventListener(ev,h,false);
	}
}
var now_active=null;
//делает видимым/невидимым поле для ввода
//visibleEditor(obj,true) покажет поле для ввода
function visibleEditor(obj,show){
	if(obj.id){
		str=obj.id;
		par_name=str.substr(0,str.length -4);
		(show?ge(par_name+'_val').style.display='none':ge(par_name+'_div').style.display='none');
		(show?ge(par_name+'_div').style.display='':ge(par_name+'_val').style.display='');
		now_active=show?obj:null;
	}
}
//показывает поле для ввода
function ShowEditor(obj){
	if(now_active==null){
	ge(obj.id.substr(0,obj.id.length -4)+'_div').value=ge(obj.id.substr(0,obj.id.length -4)+'_val').innerHTML;
	visibleEditor(obj,true);
	//ShowHelpHint(obj,'txt');
	ShowHelpHint(obj.id.substr(0,obj.id.length -4),'txt');
	ge(obj.id.substr(0,obj.id.length -4)).focus();
	}
}
//скрывает поле для ввода, и сохраняет введенные данные используя urlsave, после чего загружает данные из urlload
function EditorButtOK(obj,urlsave,urlload){
	str=obj.id;
	st=urlsave.substr(0,urlsave.length-1);
	st=st.substr(0,st.lastIndexOf('/'));
	par_name=st.substr(st.lastIndexOf('/')+1);
	myrequest2(urlsave,Array(par_name),Array(ge(obj.id.substr(0,obj.id.length -4)).value),function(e) {myrequest(urlload,Array(),Array(),obj.id.substr(0,obj.id.length -4)+'_val');});
	visibleEditor(obj,false);
}
//
function print_r(arr, level) {
    var dumped_text = "";
    if(!level) level = 0;

    var level_padding = "";
    for(var j=0; j<level+1; j++) level_padding += "    ";

    if(typeof(arr) == 'object') {
        for(var item in arr) {
            var value = arr[item];
 
            if(typeof(value) == 'object') {
                dumped_text += level_padding + "’" + item + "’ …\n";
                dumped_text += dump(value,level+1);
            }
            else {
                dumped_text += level_padding + "’" + item + "’ => \"" + value + "\"\n";
            }
        }
    }
    else {
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}
//function for CheckAll
function clickCheckAll(obj){
	if((obj.disabled)&&(obj.checked)){
		obj.checked=true;
	}
	obj.disabled=false;
	for(var i=0;i<obj.form.elements.length;i++){
		if(obj.form.elements[i].name.indexOf('p_id')!==-1){
			obj.form.elements[i].checked=obj.checked;
		}
	}
}
//function test CheckAll, or not
function clickOneCheck(obj){
	diff=false;
	prev_val=null;
	for(var i=0;i<obj.form.elements.length;i++){
		if(obj.form.elements[i].name.indexOf('p_id')!==-1){
			if(prev_val!==null){
				diff=diff || (obj.form.elements[i].checked!==prev_val);
			}
			prev_val=obj.form.elements[i].checked;
		}
	}
	//obj.form.maincheck.disabled=diff;
	//obj.form.maincheck.checked=(diff)?true:prev_val;
	obj.form.maincheck.checked=(diff)?false:prev_val;
	obj.form.maincheck.indeterminate=true;
}