function ifChn(b,id,html){
        if (b){
                 var obj=document.getElementById(id);
                 if(obj){
                  var parent=obj.parentNode;
                  var odiv=document.createElement('span');
                  parent.replaceChild(odiv, obj);
                  odiv.innerHTML=html;
                 }
        }
}

function getCookieVal (offset){
         var endstr = document.cookie.indexOf (";", offset);
         if (endstr == -1)
         endstr = document.cookie.length;
         return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
        return getCookieVal (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0)
        break;
        }
        return null;
}

function SetCookie (name, value, period) {
        var argv = SetCookie.arguments;
        var argc = SetCookie.arguments.length;
        now= new Date();
        var expires = (period==null) ? "" : new Date(now.getMonth()+1+'-'+(now.getDate()+period)+'-'+now.getYear()+" "+now.getHours()+":"+now.getMinutes()+":"+now.getSeconds());
        var path = (3 < argc) ? argv[3] : null;
        var domain = (4 < argc) ? argv[4] : null;
        var secure = (5 < argc) ? argv[5] : false;


        document.cookie = name + "=" + escape (value) +
        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +

        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
        ((path == null) ? "" : ("; path=" + path)) +
        ((domain == null) ? "" : ("; domain=" + domain)) +
        ((secure == true) ? "; secure" : "");
}

function CheckForm (Frm) {
        var i;
        for (i=0; i<Frm.length; i++) {
                 k=Frm.elements[i].value;
                 if ((Frm.elements[i].value == "" )&&(Frm.elements[i].id!="")&&(Frm.elements[i].id.indexOf('!!')==-1)) {
                          alert('Пожалуйста, введите ' + Frm.elements[i].id);
                          Frm.elements[i].focus();
                          return false;
                  }else
                         if ((k.length<2)&&(Frm.elements[i].id!="")&&(Frm.elements[i].id.indexOf('!!')==-1)){
                          alert(Frm.elements[i].id + ' введено некорректно.');
                          Frm.elements[i].focus();
                          return false;
                  }
        }
        return true;
}

function openPopupS(url,w,h) {
         w=(w)?w:550;
         h=(h)?h:550;

         pl=(document.all)?top.screenLeft:top.screenX;
         pt=(document.all)?top.screenTop:top.screenY;
         ph=(document.all)?document.body.offsetHeight:top.outerHeight;
         pw=(document.all)?document.body.offsetWidth:top.outerWidth;
         l=pl+(pw/2)-(w/2);
         t=pt+(ph/2)-(h/2);

         var posy= (document.body.offsetWidth)/2-275;
         var posx=(document.body.offsetHeight)/2-215;
         window.open(url,'','width='+w+',height='+h+', toolbar=0,location=0,status=1,menubar=0,scrollbars=1,resizable=0,left='+l+',top='+t);
}

var site_new_popup

function openImagePopup(url,title,w,h) {
        if (site_new_popup) site_new_popup.close();
         pl=(document.all)?top.screenLeft:top.screenX;
         pt=(document.all)?top.screenTop:top.screenY;
         ph=(document.all)?document.body.offsetHeight:top.outerHeight;
         pw=(document.all)?document.body.offsetWidth:top.outerWidth;
         l=pl+(pw/2)-(w/2);
         t=pt+(ph/2)-(h/2);

        w=(w)?w:550;
        h=(h)?h:550;

        if (w>pw) w=pw;
        if (h>ph) h=ph;

        var posy= (document.body.offsetWidth)/2-275;
        var posx=(document.body.offsetHeight)/2-215;
        var site_new_popup=window.open(url,'big','width='+w+',height='+h+', toolbar=0,location=0,status=1,menubar=0,scrollbars=1,resizable=0,left='+l+',top='+t)

         popuphtml='<html><head><title>';
         popuphtml+=title;
         popuphtml+='</title><meta http-equiv="Content-Type" content="text/html; charset=windows-1251"></head><body style="padding:0px; margin:0px;" onclick="self.close()" style="overflow:auto">';
         popuphtml+='<img alt="'+title+'" src="'+url+'">';
         popuphtml+='</body></html>';

         site_new_popup.document.open();
         site_new_popup.document.write(popuphtml);
         site_new_popup.document.close();

        site_new_popup.focus();
}

var IE = (navigator.userAgent && (navigator.userAgent.indexOf("MSIE") != -1));
var FF = (navigator.userAgent && (navigator.userAgent.indexOf("Firefox") != -1));
var OP = (navigator.userAgent && (navigator.userAgent.indexOf("Opera") != -1));

if (IE || OP){
           document.attachEvent("onkeydown",globalKeyCatch);
}else{
           document.addEventListener("keypress",globalKeyCatch,true);
}

var key_process={ //Функция для захвата событий кнопок и передаче в функцию
	func_array:new Array(),
	event:function(e){
	
	},
	assign:function(func){
		func_array[func_array.length]=func;
	}

}

function globalKeyCatch(e) {
        var code;
        elem = (!e)?window.event.srcElement:e.target;
        if (!e) e = window.event;

        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;

        if (!elem || (elem.tagName!="INPUT" && elem.tagName!="TEXTAREA")){

                if ((code == 37) && (e.ctrlKey == true)) {
                        var destination = document.getElementById('previous_page');
                        if (destination) location.href = destination.href;
                }
                if ((code == 39) && (e.ctrlKey == true)) {
                        var destination = document.getElementById('next_page');
                        if (destination) location.href = destination.href;
                }
        }
}

function insertFlash(bnFlash,bnW,bnH,flashV,params,nocashe,transp){
        var rnd = Math.round(Math.random()*1048576);
        var flashID=bnFlash;
        if (bnFlash.indexOf('/')!=-1){
                flashID=bnFlash.split('/');
                flashID=flashID[flashID.length-1];
        }
        flashID=flashID.split('.');
        flashID=flashID[0];

        var flashHtm='';
        flashHtm+='<object codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'+bnW+'" height="'+bnH+'" id="'+flashID+'" align="middle">';
        flashHtm+='<param name="allowScriptAccess" value="sameDomain" />';
        flashHtm+=(nocashe)?'<param name="movie" value="'+bnFlash+'?rnd='+rnd+'" />':'<param name="movie" value="'+bnFlash+'" />';
        flashHtm+='<param name="quality" value="high" />';
        flashHtm+='<param name="flashVars" value="'+params+'" />';
        flashHtm+='<param name="bgcolor" value="#ffffff" />';
        if (!transp) flashHtm+='<param name="wmode" value="transparent" />';
        if (!transp)
        flashHtm+='<embed src="'+bnFlash+'" wmode="transparent" flashVars="'+params+'" quality="high" width="'+bnW+'" height="'+bnH+'" name="'+flashID+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
        else
        flashHtm+='<embed src="'+bnFlash+'" flashVars="'+params+'" quality="high" width="'+bnW+'" height="'+bnH+'" name="'+flashID+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
        flashHtm+='</object>';
        document.write(flashHtm);
}

function insertFlash2(bnFlash,bnW,bnH,flashV,params,nocashe,bgcolor){
        var rnd = Math.round(Math.random()*1048576);
        var flashID=bnFlash;
        if (bnFlash.indexOf('/')!=-1){
                flashID=bnFlash.split('/');
                flashID=flashID[flashID.length-1];
        }
        flashID=flashID.split('.');
        flashID=flashID[0];

        var flashHtm='';
        flashHtm+='<object codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'+bnW+'" height="'+bnH+'" id="'+flashID+'" align="middle">';
        flashHtm+='<param name="allowScriptAccess" value="sameDomain" />';
        flashHtm+=(nocashe)?'<param name="movie" value="'+bnFlash+'?rnd='+rnd+'" />':'<param name="movie" value="'+bnFlash+'" />';
        flashHtm+='<param name="quality" value="high" />';
        flashHtm+='<param name="flashVars" value="'+params+'" />';
        if (!bgcolor){
             flashHtm+='<param name="wmode" value="transparent" />';
             flashHtm+='<embed src="'+bnFlash+'" wmode="transparent" flashVars="'+params+'" quality="high" width="'+bnW+'" height="'+bnH+'" name="'+flashID+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
        }else{
             flashHtm+='<param name="bgcolor" value="'+bgcolor+'" />';
             flashHtm+='<embed src="'+bnFlash+'" flashVars="'+params+'" quality="high" bgcolor="'+bgcolor+'" width="'+bnW+'" height="'+bnH+'" name="'+flashID+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
        }
        flashHtm+='</object>';
        document.write(flashHtm);
}


//Функция отправки запроса на удаленный URL методом GET. 2й параметр - ф-ия после выполнения запроса

var ajaxReq=false;

function loadXMLDoc(url,func,params) {
        ajaxReq = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
        ajaxReq.onreadystatechange = func;
        ajaxReq.open("POST",url, true);
        ajaxReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        ajaxReq.setRequestHeader("Accept-Charset", "windows-1251");
        ajaxReq.setRequestHeader("Content-Length",params.length);
        ajaxReq.send(params);
}

function processReqChange() {
        if (ajaxReq){
            abort = window.setTimeout("ajaxReq.abort();", 10000);
            if (ajaxReq.readyState == 4) {
                clearTimeout(abort);
                if (ajaxReq.status == 200) {
                                alert(ajaxReq.responseText);
                } else {
                    alert("Неудачный запрос серверу:n" + ajaxReq.statusText);
                }
            }
    }
}

//------Упрощенная функция отправки запроса (Адрес, ID контейнера, Параметры)

//------Упрощенная функция отправки запроса (Адрес, ID контейнера, Параметры)

function sXMLSendReq(url,id,params){
        var sajaxReqz = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
        //sajaxReqz.sajaxReqHTMLid=id;
        sajaxReqz.onreadystatechange = function(){sXMLgetReq(sajaxReqz,id)};
        sajaxReqz.open("POST",url, true);
        if (params){
                sajaxReqz.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                sajaxReqz.setRequestHeader("Accept-Charset", "windows-1251");
                sajaxReqz.setRequestHeader("Content-Length",params.length);
        }
        sajaxReqz.send(params);
}

function sXMLgetReq(sajaxReq,sajaxReqHTMLid){

     if (sajaxReq){
                if (sajaxReq.readyState == 4){
                     if (sajaxReq.status == 200 && sajaxReqHTMLid && document.getElementById(sajaxReqHTMLid)){
                          document.getElementById(sajaxReqHTMLid).className="";
                                document.getElementById(sajaxReqHTMLid).innerHTML=sajaxReq.responseText;
                  }else{
                          //   alert("К сожалению, сервер не вернул ответа на посланный запрос. Повторите попутку позднее. " + sajaxReq.statusText);
                    }
             }
     }
}

function objectHTMLById(objectHTMLByIdid,objectHTMLByIdtext){
        if ((objectHTMLByIdobj=document.getElementById(objectHTMLByIdid)) && (objectHTMLByIdtext))
                objectHTMLByIdobj.innerHTML=objectHTMLByIdtext;
}

function getObjectHTML(wid){
        if (getObjectHTMLobj=document.getElementById(wid))
                return (getObjectHTMLobj.innerHTML);
        else
             return false;
}

function objectById(objectByIdid){
        return document.getElementById(objectByIdid);
}

//*------------Крнец функций AJAX



function cfm(prt,url) { //v2.0
  if (confirm(prt))
  {
        location.href=url;

  };
}

var but={
        over:function(obj,width){
                //obj.onmouseover=function(){obj.style.backgroundPosition='-'+width;};
                obj.onmousedown=function(){obj.style.backgroundPosition='-'+width*2;};
                obj.onmouseout=function(){obj.style.backgroundPosition='0';};
                obj.onmouseup=function(){obj.style.backgroundPosition='-'+width;};
                obj.style.backgroundPosition='-'+width;
        }
}

/*
Объект для работы с аяксом 1.3m
url-Адрес
params - пераметры передачи в пост
func - функция которая выполнится при удачном выполнении запроса
die - функция которая выполнится при ошибке!doctype
args - аргументы которые передадуться двум предыдущим функциям в виде {asdsad:'sads',asdasd:true}
*/  

var ajax={ //Объект работы с аяксом
	toid:function (url,id,params){ //Возвращает результат в элемент с идентификатором
		if (id && document.getElementById(id))
			ajax.get(url,params,ajax.toid_return,'',{id:id});	
	},
	toid_return:function(args){//Функция возврата в элемент с идентификатором
		if (args.id && document.getElementById(args.id))
			document.getElementById(args.id).innerHTML=args.text;
	},
	get:function (url,params,func,die,args){ //Делает запрос и выполняет функции
		var sajaxReqz = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
		sajaxReqz.onreadystatechange = function(){
			ajax.process(sajaxReqz,func,die,args);
		};
		params=params?params:'params=get';
		sajaxReqz.open("POST",url, true);
		sajaxReqz.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		sajaxReqz.setRequestHeader("Accept-Charset", "windows-1251");
		sajaxReqz.setRequestHeader("Content-Length",params.length);
		sajaxReqz.send(params); 
	},
	process:function (sajaxReq,func,die,args){ //функция возврата
		if (sajaxReq && sajaxReq.readyState == 4 && sajaxReq.status == 200)
			if (func){ 
				if (args!=null){
					args["text"]=sajaxReq.responseText;
				}else{
					args={
						text:sajaxReq.responseText
					}
				}
				func(args);
			}
		else
			if (die) die(sajaxReq);
	}
}

var globalAjaxReqz;

var ajax2={
        get:function(url,params,func,die,args){
                globalAjaxReqz = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
                globalAjaxReqz.onreadystatechange = function(){
                        ajax2.process(func,die,args);
                };
                globalAjaxReqz.open("POST",url, true);
                if (params){
                        globalAjaxReqz.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                        globalAjaxReqz.setRequestHeader("Accept-Charset", "windows-1251");
                        globalAjaxReqz.setRequestHeader("Content-Length",params.length);
                }
                globalAjaxReqz.send(params);
        },
        process:function (func,die,args){
//                window.setTimeout("if (globalAjaxReqz) globalAjaxReqz.abort();", 2000);
                if (globalAjaxReqz && globalAjaxReqz.readyState == 4 && globalAjaxReqz.status == 200)
                        if (func){
                                if (args!=null){
                                        args["text"]=globalAjaxReqz.responseText;
                                }else{
                                        args={
                                                text:globalAjaxReqz.responseText
                                        }
                                }
                                func(args);
                        }
                else
                        if (die) die(globalAjaxReqz);
        }
}

var slider={
	block:false, //Блокируем слайдер
	ff:true, //направление прибавления
	slide:function(objid,param,from,to,ms,step){ 
		if (slider.block) return;
		slider.step=(step)?step:50;
		obj=document.getElementById(objid);
		if (from==''){ 
			from=0;
			slider.now=(slider.now!=null)?slider.now:from; 
			from=slider.now;
		}
		
		slider.ff=(to<from)?false:true;
		
		if (obj){
			slider.block=true;
			slider.interval=setInterval(function(){slider.process(obj,param,from,to);},ms);  
		}
	},
	
	process:function (obj,param,from,to){
		d=Math.abs((slider.ff)?(from-to):(to-from));
		p=(d==0)?100:Math.abs(slider.now-from)/d*100;
		slider.slidestep=slider.step; 
		if (p>80) slider.slidestep=slider.step*((100-p)/20)+0.6; 
		if (slider.ff)
			slider.now=Math.round(slider.now+slider.slidestep);
		else
			slider.now=Math.round(slider.now-slider.slidestep);
		if ( (slider.now>=to && slider.ff) || (slider.now<=to && !slider.ff) ){
			eval("obj."+param+'=to;');
			slider.now=to;
			slider.stop();
		}
		eval("obj."+param+'=slider.now;');
	},
	
	stop:function(){
		clearInterval(slider.interval);
		slider.block=false;
	}
}

function doBet(url,obj){
        if (eval('flag'+obj.id)==false){
			 if (obj.id.indexOf('bsut')!=-1)
				obj.style.backgroundPosition='-270';
			else
				obj.style.backgroundPosition='-429';
                eval('flag'+obj.id+"=true;");
                ajax.get(url,'',betProcess,'',{
                        obj:obj
                });
        }
}

function betProcess(args){
        args.obj.style.backgroundPosition='0';
        var ret=false;
        eval(args.text);
        if (ret && ret.ecode) alert(ret.emessage);
        if (ret && ret.redirect) location=ret.redirect;
        if (ret && ret.balance){
                obj=document.getElementById("balance");
                if (obj) obj.innerHTML=ret.balance;
        }
        eval('flag'+args.obj.id+"=false;");
}


/*
Класс бегущей строки
Версия 1.0 (27.05.2009)

Внедрение:
*/

Function.prototype.tlbind=function(object){
  var method=this;
  var arg=arguments;
  return function(arg){return method.apply(object,arguments);}
}

function tTextLine(){
	this.speed=20;
	this.def_step=1; //Предустановленый
	this.step=this.def_step; //Изменяемый шаг
	this.text='';
	
	document.write('<DIV ID="textouter"><span ID="textinner"></span></DIV>');
	
	this.setText=function(text){
		this.text+=text;
	};
		
	this.run=function(){
		if (navigator.userAgent && (navigator.userAgent.indexOf("MSIE") != -1))
			    window.attachEvent("onload",function(){this.start()}.bind(this));
		else
			    window.addEventListener("load",function(){this.start()}.bind(this),true);	
	};
	
	this.start=function(){
		this.inner=document.getElementById('textinner');  
		this.outer=document.getElementById('textouter');  
		this.inner.innerHTML=this.text;
		this.width = this.outer.offsetWidth;
		this.pos = this.inner.offsetWidth;	
		
		//defLeft=GetCookie("tTextLine_left");
		//this.left= (defLeft)?defLeft:this.width; 
		
		this.inner.style.left = this.width + "px";
		this.left=this.inner.style.left; //Реальное смещение
		this.left=this.left.replace('px','');
		this.left=this.left.replace('pt','');	
		
		this.inter=setInterval(function(){this.onTimer()}.tlbind(this), this.speed); //Запускаем
		//this.inter=setInterval(function(){this.save()}.tlbind(this), 200); //Запускаем
		this.outer.onmouseover=function(){this.step=this.step/3}.tlbind(this);
		this.outer.onmouseout=function(){this.step=this.def_step}.tlbind(this);
	}
	
	this.onTimer=function(){
		this.left=this.left-this.step;
		if (this.left < -this.pos)
			this.left = this.width;	
		this.inner.style.left = Math.round(this.left) + "px";
	};	
	
	this.save=function(){//Сохраняем смещение в кук;
		SetCookie("tTextLine_left", this.left, 1);
	}
	
	
} 


function onLoad(func){ //1.1 Срабатывает при загрузке окна
if (IE)
         window.attachEvent("onload",func)
else
         window.addEventListener("load",func,true)
}


function error(t){
	alert(t);
	return false;
}
/*	w:$('body').width()-50,
	h:$('body').height()-50,*/
	
	
	
popup={
	w:900,
	h:500,
	open_url:function(url,pars){ 	

		this.url=url;
		//alert(pars.w);
		if (!pars) pars={};
		this.add_func=pars.f;//Функция обработки
		this.ret_input_name=pars.ret_input_name;//Названия генерируемых инпутов
		this.ret_txt_c=pars.ret_txt_c;//Класс текстового блока для возврата результата
		this.w=pars.w?pars.w:($('body').width()-300); //Высота попапа
		this.h=pars.h?pars.h:($('body').height()-100);//Ширина попапа
		
		if (!this.url) return error('popup::open_url Не передан URL для открытия');
		$('.dialog').stop(); 
		$('.dialog_shadow').stop(); 	 	
		$('body').append('<div class=dialog_shadow onclick="popup.close()"></div>');
		$('body').append('<div class=dialog></div>');
		$('.dialog_shadow').css({position:'absolute',display:'none',top:document.body.scrollTop,width:$(window).width(), height:$(window).height()});		
		$('.dialog_shadow').show();

		$('.dialog').css({position:'absolute',width:popup.w, height:popup.h}); 
	//	$('.dialog .dialog_content').css({width:popup.w, height:22}); 
		
		$('.dialog').css({top:Math.floor(($(window).height()-popup.h)/2)+document.body.scrollTop});
		$('.dialog').css({left:Math.floor(($(window).width()-popup.w)/2)});
		$('.dialog').show();
		
		
		$('body').css({overflow:'hidden'});
		$('.dialog_shadow').css({width:$(window).width(), height:$(window).height()});		
		
		$('.dialog').load(popup.url,function(){
		
			$('.dialog').append('<div class="close hand" title="Закрыть окно" onclick="popup.close()"><div class="button_transp"><div class=btn_close></div></div>');

	$('.button_transp').hover(function(){
		w=$(this).find('div').width();
		$(this).find('div').css({marginLeft:-Math.floor(w/3)});
	},function(){
		w=$(this).find('div').width();
		$(this).find('div').css({marginLeft:0});
	}).mousedown(function(){
		w=$(this).find('div').width();
		$(this).find('div').css({marginLeft:-Math.floor(w/3)*2});
	}).mouseup(function(){
		w=$(this).find('div').width();		
		$(this).find('div').css({marginLeft:-Math.floor(w/3)});
		location=$(this).attr('rel');
	})

			});	

		
		$(window).scroll(function() {
			$('.dialog').css({top:Math.floor(($(window).height()-popup.h)/2)+document.body.scrollTop});
		});
			
			
		

	},
	close:function(){
		$('.dialog_shadow').remove();
		$('.dialog').remove();		
		$('body').css({overflow:'auto'});
	},
	add:function(p){
		p.popup=popup;
		if (this.add_func) this.add_func(p);
		this.close();
	}


}


search={
	ta:false,
	sent:function(qo){
		if (this.ta) clearTimeout(this.ta);
		this.ta=setTimeout(function(){
			var s=escape($(qo).attr('value')); 
			$('.results').load($(qo).attr('rel')+s);
		},150);
	},
	init:function(url){
			$('.results').load(url);		 
	}

}

//Обработка формы
onLoad(function(){
	jform.init();
	setTimeout(function(){$('.formtpl :input:first[type!=hidden][disabled!=disabled][readonly!=readonly]').focus();},200);
})

jform={
	bclass:'',
	init:function(){
		$('.search_delete').each(function(){
			$(this).click(function(){
				$(this).parent().hide("slow");	
			});
		})	
	},
	addblock:function(p){
		if (!jform.bclass) return;
		$("<div class='searchblock'><span class='search_text'>"+p.title+"</span><div class='search_delete'></div><input class='search_hidden' type=hidden value='"+p.value+"' name='"+p.name+"}'></div>").appendTo("."+jform.bclass);
		
		jform.init();
	}

}


form_pat={ //Функции управления полем добавления пациентов в форме
		ta:false, 
		visible:false,
		data:false,
		lastvalue:'',
		init:function(p){
			form_pat.url=p.url;
			form_pat.$res=p.$res; //jQ Контейнер результата
			form_pat.$ret=p.$ret; //jQ возврат в хиднполе
			form_pat.$this=p.$this; //Вернуть валую		
			
			form_pat.$res.hide();

			form_pat.$this.keyup(function (){form_pat.get()});
			form_pat.$this.focus(function(){form_pat.data?form_pat.show():form_pat.get(); form_pat.lastvalue=form_pat.$this.attr('value'); form_pat.$this.attr('value','');});
			form_pat.$this.blur(function(){form_pat.hide();form_pat.$this.attr('value',form_pat.lastvalue);});
		},
		show:function(){
			if (!form_pat.visible){
				form_pat.$res.show('slow');
				form_pat.visible=true;
			}
		},
		hide:function(){
			if (form_pat.visible){
				form_pat.$res.hide('slow');
				form_pat.visible=false;
			}		
		},
		get:function(){		
			form_pat.data=true;
			if (form_pat.ta) clearTimeout(form_pat.ta);
			form_pat.ta=setTimeout(function(){
				var s=escape(form_pat.$this.attr('value')); 
				form_pat.$res.load(form_pat.url+s,function(){form_pat.show()});
			},150);
		},
		ret:function(p){ 
			form_pat.$ret.attr('value',p.val);
			form_pat.$this.attr('value',p.name);
			form_pat.hide();
		}
}   


//ВКЛАДКИ ################################################################################################
onLoad(function(){
	$('.tabs .tabs_block .tab').click(function(){	
	
		if ($(this).attr('rel_href')!=='' && location.href!=$(this).attr('rel_href')){ location.href=$(this).attr('rel_href'); return;	 }
		$('.'+$(this).parent().find('.active1').attr('rel')).hide();	
		$('.'+$(this).attr('rel')).show();	
		$(this).parent().find('.active1').removeClass('active1');
		$(this).addClass('active1');	
	});
	
	$('.tabs .tabs_block .tab.active1').click();
	
	$('.tabs_1').each(function(){
		$(this).find('.tab_content').css({display:'none'});
		$(this).find('.tab_head').attr('nheight',$(this).height()).css({height:30}).addClass('hand').attr('title','Открыть вкладку').click(function(){

			if ($(this).parent().parent().attr('opened')!=1){
				$(this).parent().parent().find('.tab_content').show();
				$(this).css({height:$(this).attr('nheight')});
				$(this).parent().parent().attr('opened',1);
			}else{
				$(this).parent().parent().find('.tab_content').hide();
				$(this).css({height:30});
				$(this).parent().parent().attr('opened',0);
			
			}
		
		});
	});
	
	
	
	if ($('.tab_content_scroll').height()==0) $('.tab_content_scroll').height('100');
});

//Работа со справочниками #######################################################################################
spr={
	$res:false,
	ta:false,
	start_url:false,
	sent:function(qo){
		if (this.ta) clearTimeout(this.ta);
		this.ta=setTimeout(function(){
			var s=escape($(qo).attr('value')); 
			spr.$res.load($(qo).attr('rel')+s,function(){
				spr.result_hover_events();		
			});
		},150);
	},
	load:function(url){
		spr.$res.load(url,function(){spr.form_replace(url);});			
	},
	init:function(res,url){
		spr.$res=res;
		if (!spr.$res) {return error('spr::init Не указан объект загрузки адресов.');}
		spr.$res.load(url,function(){
			spr.result_hover_events();		
		});	
		spr.start_url=url;		
	},
	result_hover_events:function(){
		$('.spr_result_table .item').hover(function(){
			$(this).parent().addClass('alitem');
		},function(){
			$(this).parent().removeClass('alitem');
		})		
		$('.dialog_content_search INPUT').focus();
		$('.dialog_content_search INPUT').keyup(function(e){
			if(27==e.keyCode){popup.close();}
//			if(107==e.keyCode){popup.close();}

		});
	
		
	
	},
	form_replace:function(url){	

		spr.$res.find('.buttons input').hide();
		spr.$res.find('.buttons').append('<div class="spacer"></div><input type=button value="Сохранить" id=ajaxformsubmit>');
		$('#ajaxformsubmit').click(function(){
			$qs='';
			spr.$res.find('input').each(function(){
				if ($(this).attr('name'))
					$qs+=(($qs)?'&':'')+$(this).attr('name')+'='+escape($(this).attr('value'));
			});
		
			$.post(url+'?'+$qs,{ajax:'yes'},function(data){
				spr.load(spr.start_url);
			});
		
		});
		

	},
	callback:function(p){
		html=p.title;
		html+="<input  type=hidden value='"+p.value+"' name='"+p.popup.ret_input_name+"'>";
		$('.'+p.popup.ret_txt_c).html(html);
	}
}


//DropDown в форме #######################################################################################
dropdown={
	init:function(){
		$('.dropdown .dropdown_block .dropdown_block_item[active=1]').each(function(){
			dobj=$(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().parent();
			if (dobj.find('.dropdown_title .title').html()==''){
				dobj.find('.dropdown_title .title').html($(this).html());	
			}else{
				dobj.attr('no_return',1);
			}
		});
		
		$('.dropdown .dropdown_click').hover(function(){
			p=$(this).parent();
			dropdown.open(p);
		},function(){	
		});
		
		$('.dropdown .dropdown_block').hover(function(){},function(){
			p=$(this).parent().parent();  
			dropdown.close(p);
		});
		

		
		$('.dropdown .dropdown_block .dropdown_block_item').hover(function(){
			$(this).addClass('active');
		},function(){
			$(this).removeClass('active');
		}).click(function(){
			dobj=$(this).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().parent();
			if (dobj.attr('no_return')!=1){
				dobj.find('.dropdown_title .title').html($(this).html());	
			}
			//$(this).parent().slideUp('fast');
			//$(this).parent().parent().parent().attr('opened',0);
			
			if (u=$(this).attr('rel')) location=u;
			dropdown.widths();
		
		});
		
		dropdown.widths();
	},
	open:function(p){
		if (p.attr('block')==1) return false;
		pop=p.find('.dropdown_block');
		pop.fadeIn(300); 
		if (pop.offset().left+pop.width()>$(window).width())
			pop.css({right:0});
		p.attr('opened',1);	
	},
	close:function(obj){
		obj.attr('block',1);
		obj.find('.dropdown_block').fadeOut(300,function(){$('.dropdown').attr('block',0);});
		obj.attr('opened',0);
	
	},
	widths:function(){
		$('.dropdown .dropdown_title').each(function(){
			
			$(this).parent().width($(this).width()+26);
		})		
	}
}

onLoad(function(){dropdown.init();});

//Обработка меню actions во вкладках #######################################################################################
onLoad(function(){
	$('a.action_a').each(function(){
		if (pars=$(this).attr('rel')){
			eval("pars="+pars);
			if (pars.act=='popup;')
				$(this).attr('href','javascript:openPopupS("'+$(this).attr('href')+'",'+pars.w+','+pars.h+')');
			if (pars.act=='blank;')
				$(this).attr('href','javascript:location="'+$(this).attr('href')+'"');	
			if (pars.act=='print;'){
				$(this).attr('href','javascript:print_href("'+$(this).attr('href')+'")');
				$(this).click(function(){

					$('body').append('<iframe class=print_iframe onload="self_print(this)" src="'+$(this).attr('href')+'"></iframe>');
				});
			}						
		}
	});
});

//Обработка тулбара в хедблоке #######################################################################################
onLoad(function(){
	$('.button_toolbar').each(function(){
		if (pars=$(this).attr('rel')){
			eval("pars="+pars);
			if (pars.act=='popup;')
				$(this).click(function(){openPopupS($(this).attr('href'),pars.w,pars.h)});
			if (pars.act=='blank;')
				$(this).click(function(){window.open($(this).attr('href'))});
			if (pars.act=='print;'){
				$(this).click(function(){
					print_href($(this).attr('href'));
					$('body').append('<iframe class=print_iframe onload="self_print(this)" src="'+$(this).attr('href')+'"></iframe>');
				});
			}						
		}else{
			$(this).click(function(){location=$(this).attr('href')});
		}
	});
});

function print_href(href){
	//alert(href);
	$('body').append('<iframe class=print_iframe src="'+href+'"></iframe>');
	$('.print_iframe').load(function(){
	(IE)?this.print():this.contentWindow.print();
	});
}

// Кнопки ##################################################################################
onLoad(function(){
	$('.button_transp').hover(function(){
		w=$(this).find('div').width();
		$(this).find('div').css({marginLeft:-Math.floor(w/3)});
	},function(){
		w=$(this).find('div').width();
		$(this).find('div').css({marginLeft:0});
	}).mousedown(function(){
		w=$(this).find('div').width();
		$(this).find('div').css({marginLeft:-Math.floor(w/3)*2});
	}).mouseup(function(){
		w=$(this).find('div').width();		
		$(this).find('div').css({marginLeft:-Math.floor(w/3)});
		if ($(this).attr('rel')) location=$(this).attr('rel');
	}).each(function(){
		d=$(this).find('div');
		$(this).css({width:Math.floor(d.width()/3),height:Math.floor(d.height())});	
	})

});

// Активный список ##################################################################################

onLoad(function(){
	$('.active_list .alitem').hover(function(){
		
		$(this).parent().addClass('active_list_hover');
	},function(){
		$(this).parent().removeClass('active_list_hover');
	})
})

