//resize popUp окна для схемы проезда 

function psPopImg2(obj){
	var w = window.open(obj.href, "", "resizable=1,HEIGHT=100,WIDTH=100,scrollbar=1");
	with(w.document){
		open();
		var c = [
			'<html><head>',
				'<title>',title,'</title>',
				'<script language="javascript">',
					'function fitPic(){',
						'iWidth = document.body.clientWidth;iHeight = document.body.clientHeight;iWidth = document.images[0].width - iWidth;',
						'iHeight = document.images[0].height - iHeight;window.resizeBy(iWidth, iHeight-1);',
						'var sw=(document.body.clientWidth-iWidth)/2;var sh=(document.body.clientHeight-iHeight)/2;',
						'if (sh<0) sh=0; if (sw<0) sw=0;window.moveTo(sw,sh);self.focus();}',
				'</script></head>',
				'<body onload="fitPic();" style="margin:0;padding:0;">',
					'<img src="',obj.href,'" border="0" alt="',title,'" title="',title,'" />',
				'</body>',
			'</html>'].join('');
		write(c);
		close();
	}
  return false;	
}

function psPrint(obj){
  popupWin = window.open(obj.href, '', 'width=700,height=600,toolbar=no,menubar=yes,location=no,status=yes,resizable=yes,scrollbars=yes,left=50,top=50');
  popupWin.focus();
  return false;	
}

// - Корзина --------------------------------------------

function psAddToCart(obj,id){
	var c = gebi('psProdCount'+id), sdata = {'ajax':1}, r;
	if (c){
		sdata.count = c.value;
	}
	
	r = new JsHttpRequest(), sdata;
	r.caching = false;
	r.open('GET',obj.href,true);
	r.send(sdata);
	obj.innerHTML = '<img src="'+psIMG+'_tpl_loader_small.gif" />';	
	r.onreadystatechange = function(){
		if (this.readyState == 4){
			if (this.responseJS){
				var d = this.responseJS, dCost, dCount;
				
				obj.innerHTML = (d.cmd_errors) ? d.cmd_errors.join(' ') : d.cmd_messages.join(' ');
				
				dCost = gebi('psCartCost');
				if (dCost && d.cart_cost){
					dCost.innerHTML = d.cart_cost;
				}
				dCount = gebi('psCartCount');
				if (dCount && d.cart_count){
					dCount.innerHTML = d.cart_count;
				}
				if (c){
					c.value = 1;
				}else{
					obj.href = d.cart_url? d.cart_url : '/cart.html';
					obj.onclick = function(){};					
				}
			}
		}
	};
	return false;	
}

// - Windows --------------------------------------------

var psWindows = {
	current:false,
	bg:false,
	loader:false,
	panel:false,
	//reloadData:0,
	
	popImg:function(url){
		this.loadingOn();
		var i = new Image();
		i.obj = this;
		i.title = url.title;
		this.oldUrl = url;
		
		i.onload = function(){
			if(this.obj.oldUrl == this.src){
				this.obj.createPanel(this);
			}
			//this.obj.oldUrl = this.src;
			this.obj.oldUrl = null;
			this.obj.current = psCreateDiv('psWindow');
			this.obj.current.style.zIndex = 1100;
				
			this.obj.current.appendChild(this.obj.closeButtonCreate());		
			this.obj.current.appendChild(this);
			this.obj.current.className = 'psWindow';		

			this.obj.current.appendChild(this.obj.titleImg(this.title));
			this.obj.position();			
			this.obj.loadingOff();
		}
		i.onclick = function(){
			this.obj.close();		
		}		
		i.style.cursor = 'pointer';
		i.src = url.href;
		return false;		
	},
	
	popDiv:function(id){
		this.loadingOn();
		objSrc = document.getElementById(id);
		if (!objSrc) return false;
		this.current = psCreateDiv('psWindow');
		this.current.className = 'psWindow';
		this.current.innerHTML = objSrc.innerHTML;
		this.current.onclick = stopEvent;
		this.position();
		this.loadingOff();
		return false;
	},
	
	popUrl:function(url){
		if (!url) return false;
		this.loadingOn();

		r = new JsHttpRequest();
		r.obj = this;
		r.caching = false;
		r.open('POST',url,true);
		r.send({ajax:1});
		r.onreadystatechange = function(){
			if (this.readyState == 4){
				if (this.responseJS){
					this.obj.current =	psCreateDiv('psWindow');	
					this.obj.current.className = 'psWindow';
					this.obj.current.innerHTML = this.responseJS.PageContent;
					this.obj.current.onclick = stopEvent;
					this.obj.position();
					this.obj.loadingOff();
				}
			}
		}		

	},

	close:function(){
		if (this.current){
			psDeleteObj(this.current);
			this.current = false;
		}
		if (this.bg){
			psDeleteObj(this.bg);
			this.bg = false;
		}
		if (this.panel){
			psDeleteObj(this.panel);
			this.panel = false;
		}
		if (this.loader){
			psDeleteObj(this.loader);
			this.loader = false;
		}
	},

	position:function(obj){
		var t,l;
		obj = (obj)?obj:this.current;
		psPage.getSize();
		t = (((psPage.windowHeight - obj.offsetHeight)/2) + psGetPageScroll());
		l = ((psPage.windowWidth - obj.offsetWidth)/2);
		obj.style.top = (t <= 0) ? '0px' : t + 'px';
		obj.style.left = (l <= 0) ? '0px' : l + 'px';			
	},

	loadingOn:function(){
		this.closeBackGround();
		this.loader = psCreateDiv('psLoader');
		this.loader.className = 'psLoader';
		this.loader.innerHTML = 'Загрузка';
		this.position(this.loader);
	},
	
	loadingOff:function(){
		if (this.loader){
			psDeleteObj(this.loader);
			this.loader = false;
		}		
	},
	
	closeBackGround:function(){
		if (this.bg){
			return false;
		}
		psPage.getSize();
		
		this.bg = psCreateDiv('closeFonId');
		this.bg.obj = this;
		this.bg.className='psCloseBackGround';
		this.bg.style.height=psPage.pageHeight+100+'px';
		//this.bg.style.width=psPage.pageWidth+'px';
		this.bg.style.width=document.body.scrollWidth+'px';
		this.bg.onclick = function(){
			this.obj.close();		
		}
	},
	createPanel:function(img){
		this.currentImg = img;
		this.panel = psCreateDiv('psPanel');
		this.wrapper = psCreateDiv('psIcoWrapper');
		
		/* левая стрелка */
		this.bleft = psCreateDiv('psbLeft');
		this.bleft.className = 'bLeft';
		this.bleft.a = document.createElement('a');
		this.bleft.a.id = 'lButton';
		this.bleft.a.obj = this;
		this.bleft.a.onclick = function(){
			this.obj.n = 1;
			this.obj.reloadImg();
		}
		this.bleft.appendChild(this.bleft.a);
		
		/* правая стрелка */
		this.bright = psCreateDiv('psbRight');
		this.bright.className = 'bRight';
		this.bright.a = document.createElement('a');
		this.bright.a.id = 'rButton';
		this.bright.a.obj = this;
		this.bright.a.onclick = function(){
			this.obj.n = 2;
			this.obj.reloadImg();
		}
		this.bright.appendChild(this.bright.a);
		
		/* div со скроллом */
		this.divScroll = psCreateDiv('icoScroll');
		this.divScroll.className = 'flexcroll';		
		this.divFix = psCreateDiv('icoFix');
		this.divFix.className = 'fixedwidth';
		this.divScroll.appendChild(this.divFix);
		
		this.divCenter = psCreateDiv('icoCenter');		
		this.divCenter.appendChild(this.divScroll);
		
		/* таблица с иконками */
		this.table = document.createElement('table');
		this.table.id = 'icoTable';
		this.tbody = document.createElement('tbody');
		this.tr = document.createElement('tr');
		this.tr.id = 'listScroll';
		this.tbody.appendChild(this.tr);
		this.table.appendChild(this.tbody);
		this.divFix.appendChild(this.table);
		
		this.wrapper.appendChild(this.bright);
		this.wrapper.appendChild(this.bleft);
		this.wrapper.appendChild(this.divCenter);
		this.panel.appendChild(this.wrapper);
	
		this.list = listImg;
		for(var i=0;i<listImg.length;i++){
			this.td = document.createElement('td');
			this.td.id = 'ImgShow'+i;
			this.td.onmouseover = function(){
				this.className = (this.className == 'icoTdActive') ? this.className : 'icoTdhover';
			}
			this.td.onmouseout = function(){
				this.className = (this.className == 'icoTdActive') ? this.className : 'icoTd';
			}
			this.td.className = 'icoTd';
			this.div = psCreateDiv('DivImgShow'+i);
			this.div.className = 'psIco';
			this.div.listImg = listImg[i];
			this.div.style.background = 'url('+this.div.listImg.ico + this.div.listImg.file+') no-repeat center center';

			if((this.div.listImg.img + this.div.listImg.file) == img.src)	{
				this.td.className = 'icoTdActive';
			}

			this.div.obj = this;
			this.div.td = this.td;
			this.div.onclick = function(){
				this.obj.td = this.td;
				this.obj.div = this;
				this.obj.reloadImg();
			}
			this.td.appendChild(this.div);
			this.tr.appendChild(this.td);
			this.div = null;
			this.td = null;
		}

		this.divFix.style.width = (listImg.length*120+listImg.length*10+50)+'px';
		CSBfleXcroll('icoScroll');
//		#icoScroll_hscrollerbase - скролл


		if(LibBWCheck().ie6)	{		
		  this.panel.style.position = 'absolute';
		  this.panel.style.zIndex = 2000;
		  this.panel.className = 'ie6Panel';
		  this.panel.style.top = (0 - this.panel.offsetHeight + document.documentElement.clientHeight + document.documentElement.scrollTop)+'px';
		}

	},
	closeButtonCreate:function(){
		this.title = '<img src="'+psIMG+'0.gif" width="15" height="15" alt="Закрыть" />';
		this.button = psCreateDiv('psClose');	
		this.button.className = 'psClose';
		this.button.obj = this;
		this.button.onclick = function(){
			this.obj.close();
		}
		this.button.innerHTML = this.title;
		return this.button;
	},
	titleImg:function(title){
		this.title = title;
		this.text = psCreateDiv('psTitle');	
		this.text.className = 'psTitle';
		this.text.obj = this;
		this.text.innerHTML = this.title;
		return this.text;
	},
	reloadImg:function(){
		for(var i=0;i<this.list.length;i++){
			if(this.currentImg.src == (this.list[i].img + this.list[i].file)){
				this.num = i;
				break;
			}
		}
		
		if(this.div)	{
			if(this.currentImg.src != (this.div.listImg.img + this.div.listImg.file))	{
				this.td.className = 'icoTdActive';
				this.currentImg.src = this.div.listImg.img + this.div.listImg.file;
				document.getElementById('ImgShow'+this.num).className = 'icoTd';
				this.div = null;
			}
		}
		else	{
//			if(((this.num != 0)&&(this.n != 1)) && ((this.num !== this.list.length)&&(this.n != 2)))	{
				switch(this.n){
					case 1:{
						document.getElementById('ImgShow'+(this.num-1)).className = 'icoTdActive';
						this.currentImg.src = this.list[this.num-1].img + this.list[this.num-1].file;
						break;
					}
					case 2:{
						document.getElementById('ImgShow'+(this.num+1)).className = 'icoTdActive';
						this.currentImg.src = this.list[this.num+1].img + this.list[this.num+1].file;
						break;
					}
				}
				document.getElementById('ImgShow'+this.num).className = 'icoTd';
//			}	
		}
	}
}


// - Windows --------------------------------------------


// - ToolTips Functions --------------------------------------------

function psDrawTooltips(){
	var tags = Array('a','span','img');	
	psCreateDiv('psTooltip')	
	for (var i = 0; i < tags.length; i++){
		el = document.getElementsByTagName(tags[i]);
		for (var e = 0; e < el.length; e++){
			if (el[e].getAttribute('psTitle'))
				psCreateTooltip(el[e])
		}
	}
}

function psCreateTooltip(obj){
	
	obj.psTitle = obj.title;
	obj.title = '';	

	obj.onmouseover = function(){
		 obj.psShowTooltip();
	}

	obj.onmouseout = function(){
		obj.Tooltip.style.left = '-1000px';
		obj.Tooltip.style.top = '-1000px';
	}
	
	obj.onmousemove = function(e){
		obj.Tooltip.style.left = psMouse.x + 10 + 'px'; //((psBW.ns4 || psBW.ns6)?e.pageX:event.clientX + psBW.ieTrueBody().scrollLeft)+ 10 + 'px';
		obj.Tooltip.style.top = psMouse.y + 10 + 'px';//((psBW.ns4 || psBW.ns6)?e.pageY:event.clientY + psBW.ieTrueBody().scrollTop) + 10 + 'px';		
	}
	
	obj.psShowTooltip = function()
	{
		obj.Tooltip = document.getElementById('psTooltip');
		obj.Tooltip.innerHTML = obj.psTitle;		
	}
	
	obj.psHideTooltip = function(){
		psDeleteObj('psTooltip');	
	}
}

function psDeleteTooltip(obj){
	
	
}
// - ToolTips Functions --------------------------------------------

// - Base Functions --------------------------------------------

function addEvent(el, evname, func) {
	if (el.attachEvent) { // IE
		el.attachEvent("on" + evname, func);
	} else if (el.addEventListener) { // Gecko / W3C
		el.addEventListener(evname, func, true);
	} else {
		el["on" + evname] = func;
	}
};
//--------------------------------------------------------------------------
function removeEvent(el, evname, func) {
	if (el.detachEvent) { // IE
		el.detachEvent("on" + evname, func);
	} else if (el.removeEventListener) { // Gecko / W3C
		el.removeEventListener(evname, func, true);
	} else {
		el["on" + evname] = null;
	}
};

function stopEvent(ev) {
	ev || (ev = window.event);
	if (Calendar.is_ie) {
		ev.cancelBubble = true;
		ev.returnValue = false;
	} else {
		ev.preventDefault();
		ev.stopPropagation();
	}
	return false;
};

function psCreateDiv(idName){
	var obj = document.createElement('div');
	document.getElementsByTagName("body")[0].appendChild(obj);
	obj.id=idName;
	return document.getElementById(idName);
}

function psDeleteObj(obj){
	if (typeof(obj) == 'string'){
		obj = document.getElementById(obj);
	}
	if (obj){
		document.body.removeChild(obj);
	}
}

function psPreloadImg(url){
    var image = new Image();
    image.src = url;    
}

function gebi(n){
 return	document.getElementById(n);
}


var psPage = {
	pageWidth:0,
	pageHeight:0,
	windowWidth:0,
	windowHeight:0,
	
	getSize:function(){
		var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		if (self.innerHeight) {	// all except Explorer
			this.windowWidth = self.innerWidth;
			this.windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			this.windowWidth = document.documentElement.clientWidth;
			this.windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			this.windowWidth = document.body.clientWidth;
			this.windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < this.windowHeight){
			this.pageHeight = this.windowHeight;
		} else { 
			this.pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < this.windowWidth){	
			this.pageWidth = this.windowWidth;
		} else {
			this.pageWidth = xScroll;
		}
	}
//	
//	return arrayPageSize;
}

// временная функция
function psGetPageSize(){
	return [psPage.pageWidth,psPage.pageHeight,psPage.windowWidth,psPage.windowHeight];
}

function psGetPageScroll(){
	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	return yScroll;
}
//--------------------------------------------------------------------------
// Browser Check
//--------------------------------------------------------------------------
function LibBWCheck(){ //Browsercheck (needed)
	this.ver=navigator.appVersion
	this.agent=navigator.userAgent
	this.dom=document.getElementById?1:0
	this.opera5=this.agent.indexOf("Opera 5")>-1
	this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0; 
	this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
	this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
	this.ie=this.ie4||this.ie5||this.ie6
	this.mac=this.agent.indexOf("Mac")>-1
	this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0; 
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
	this.ieTrueBody = function(){
		return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
	}
	
	return this
}

//--------------------------------------------------------------------------
// Mouse
//--------------------------------------------------------------------------
function _psMouse(){
	this.move = function(e){
		psMouse.x=(psBW.ns4 || psBW.ns6)?e.pageX:event.clientX + psBW.ieTrueBody().scrollLeft;
		psMouse.y=(psBW.ns4 || psBW.ns6)?e.pageY:event.clientY + psBW.ieTrueBody().scrollTop;
	}
}

//--- Flash --------------------------------------------------
function Flash( ) {

    this.transparent = true;
    this.needFlashVerion = 8;          
    this.flashvars = "xml_source=/ixml/&menuselid=0";
    this.BrowserInfo( );

}


Flash.prototype.BrowserInfo = function( ) { 
 
    var userAgent = navigator.userAgent.toLowerCase( );
       this.browserIE = ( userAgent.indexOf( 'msie' ) != -1 );

}

Flash.prototype.CheckVersionFlash = function( needVersion ) {
 
    if ( navigator.plugins[ 'Shockwave Flash' ] ) {
        matchStr = new RegExp ( '^[A-Za-z ]*(.*) .*$' );
        this.flashVerion = parseInt( navigator.plugins[ 'Shockwave Flash' ].description.replace( matchStr, '$1' ) );
        return ( needVersion <= this.flashVerion );
    }
    else if ( this.browserIE ) {
        for( var i = needVersion; i < needVersion + 10; i++ ) {
            try {
                    flashPlayer = new ActiveXObject( 'ShockwaveFlash.ShockwaveFlash.' + i );
                    this.flashVerion = i;
                    return true;
            }
            catch( e ) {
                continue;
            }
        }
        return false;     
    }
    else {
        this.flashVerion = 0;
        return false;
    }
 
}

Flash.prototype.Insert = function( ) {
	if ( this.CheckVersionFlash( this.needFlashVerion ) ) { 
		document.write( this.GenerateHtmlFlash( ) );
	}else{
		document.write( this.GenerateHtmlImage( ) );
	}
}

Flash.prototype.GenerateHtmlFlash = function( ) {
 
    var flashCode = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
    flashCode += 'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version= ' + this.flashVerion + ',0,0,0"' + ' width="' + this.width + '" height="' + this.height + '" align="middle">';
    flashCode += '<param name="allowScriptAccess" value="always"/>';
    flashCode += '<param name="movie" value="' + this.srcFlash + '"/>';
    flashCode += '<param name="quality" value="high"/>';
    if ( this.base ) {
        flashCode += '<param name="base" value="' + this.base + '"/>';
    }
    if ( this.background ) {
        flashCode += '<param name="bgcolor" value="' + this.background + '"/>';
    }
    if ( this.transparent ) {
        flashCode += '<param name="wmode" value="transparent"/>';
    }
    if ( this.flashvars ) {
        flashCode += '<param name="flashvars" value="' + this.flashvars + '"/>';
    }
 
    flashCode += '<embed quality="high" allowScriptAccess="always" type="application/x-shockwave-flash"' + ' pluginspage="http://www.macromedia.com/go/getflashplayer" ';
    flashCode += 'src="' + this.srcFlash+'" ' + '" width="' + this.width + '" height="' + this.height + '" ';
    if ( this.base ){
        flashCode += ' base="' + this.base + '"';
    }
    if ( this.background ){
        flashCode += ' bgcolor="' + this.background + '"';
    }
    if ( this.transparent ){
        flashCode += ' wmode="transparent"'
    }
    if ( this.flashvars ){
        flashCode += ' flashvars="' + this.flashvars + '"';
    }
    flashCode += '></embed>';
 
    flashCode += '</object>';
    return flashCode;
 
}

Flash.prototype.GenerateHtmlImage = function( ) {
 
    var imageCode = '<img src="' + this.srcImage + '"/>';
    return imageCode;
 
}
//--- Flash --------------------------------------------------


//-- скроллинг на главной странице ------------------------------------
var locd=false;
var state = 0;
var cacheIndex = new Array();
var linkIndex = new Array();
var namesIndex  = new Array();
function switch_top(cmd){
	if(locd==true) return false;
	locd=true; 
	(cmd=="prev")?state--:state++;
	if(!document.getElementById("loading"))
	$("#carou").css({position:'relative'}).append("<div id='loading'></div>");
	$("#loading").css({background:'url('+psIMG+'ajax-loader.gif) 50% 50% no-repeat',height:'258px',width:'918px',position:'absolute',top:95,left:40}).css("opacity",0.5);

	$("#topview").fadeTo("slow",0.5,function(){loadIndex() });	
	
	return false;
}

function loadIndex(){
	
	if(cacheIndex)
		for(x in cacheIndex)
		{
			var tmpS = '_'+state;
			if(x===tmpS)
				return setNewIndex(cacheIndex[x],x);
		}
	
	var sdata = new Array();
	sdata['ajax'] = 1;
	r = new JsHttpRequest();
	r.caching = false;
	r.open('GET',psTPL+"&cmd=get_templates&step="+state,true);
	r.send(sdata);
	r.onreadystatechange = function(){
		if (this.readyState == 4){
			if(this.responseJS.data){
				var tpl='';
				for(x in this.responseJS.data) tpl += parseTpl(this.responseJS.data[x]);
				cacheIndex['_'+state] = tpl;
			}
			setNewIndex(tpl,'_'+state);
		}
	}		
}

function setNewIndex(tpl,key){
	$("#topview").fadeTo("slow",0, function(){$("#topview").empty();$(tpl).appendTo("#topview")} ).fadeTo("slow",1);	
	$("#loading").remove();
	locd=false;
	
	if(key)
	{
		$("#bigIndex").attr("href",linkIndex[key]);
		$("#bigIndex > img").attr("alt",namesIndex[key]).attr("title",namesIndex[key]);
	}
}

function parseTpl(obj){
	if(!obj) return false;
	var tpl = '<div class="cont"><div class="navigator"><a href="'+obj.cartUrl+'" target="_blank"><img src="'+obj.img+'" alt="Выбрать шаблон '+obj.tplName+'" title="Выбрать шаблон '+obj.tplName+'"></a>	</div><div class="nav-txt"><a href="'+obj.viewUrl+'" title="Показать шаблон'+obj.tplName+'" target="_blank">Увеличить</a><a href="'+obj.cartUrl+'" title="Заказать">Заказать</a></div></div>';
	
	if(obj.pos==2) {
		linkIndex['_'+state] = obj.cartUrl;
		namesIndex['_'+state] = "Выбрать шаблон "+obj.tplName;
	}
	
	return tpl;
}
//-- end скроллинг на главной странице ------------------------------------




//-- Заказ --------------------------
//проверка верхнего доменного имени на dixar.by
function checkDomainBy(obj){
	if(!(get("mform").doc_subdomen.value)) {alert("Вы не ввели имя сайта"); return;}
	
	loadingOrder(document.getElementById("mform").doc_subdomen,1);

	var domainInfo = [{'name':get("mform").doc_subdomen.value + 'dixar','domain':'by'}];
	loadDomains(domainInfo,obj,"setDomainStatus");	
	//jse(domainInfo);
	return false;	
}



//проверка верхнего доменного имени
function checkDomain(obj){
	if(!(get("mform").doc_subdomen) || !(get("mform").doc_domen)) return false;
	if(!(get("mform").doc_subdomen.value)) {alert("Вы не ввели имя сайта"); return;}
	
	loadingOrder(document.getElementById("mform").doc_subdomen,1);

	var domainInfo = [{'name':get("mform").doc_subdomen.value,'domain':get("mform").doc_domen[get("mform").doc_domen.selectedIndex].value}];
	loadDomains(domainInfo,obj,"setDomainStatus");	
	//jse(domainInfo);
	return false;	
}

//при смене домена сброс статуса верхнего имени
function checkSub(obj){
	
	var S = document.getElementById("mform").doc_subdomen;
	$("#topcheck").empty();
	$("#doc_subdomen_state").attr({className:"state_required"});
	if( S.value != '' )
		checkDomain( get('topcheck') );
}

//проверка нижних имен
function checkSubDomain(id,domain){
	obj=get("check"+id);
	
	if(domain != 'by') $("#domainsDescLink").css({display:"block"});
	if(!obj || !trimS(domain).length) return false;
	if(!trimS(obj.value).length) {alert("Введите имя сайта"); return;}

	loadingOrder(obj,1);
	
	var domainInfo = [{'name':trimS(obj.value),'domain':trimS(domain)}];
	loadDomains(domainInfo,obj,"setSubDomainStatus");
	//jse(domainInfo);
	return false;	
}

//показывает поле с проверкой домена
function selectDomain(obj,id)
{
	if(isNaN(id) || id<0) return;
	if(obj.checked==true){ $.each( $("#domainDiv"+id) , function(i , n) { $(n).css({visibility:"visible"}) } ); $("#check"+id).css({visibility:"visible"});  }
	else { $.each( $("#domainDiv"+id) , function(i , n) { $(n).css({visibility:"hidden"}) } ); $("#check"+id).css({visibility:"hidden"}); }
	
	checkInvalid("check"+id);
	checkdomainsDescLink();//проверяет скрывать ли ссылку
}

//проверка полей при отправке данных
function checkSubmit(){
	var deny = false;
	//if($("div.state_invalid",document).length) deny = 1;
	
	//проверка юр лиц
	var code = false;
	var el = document.getElementById("mform");//if( this.attr("value") =='' ){ deny = 1;alert('ok');}
		$.each( el.doc_type_order , function(){ if(this.checked==true) code = this.value; });
			if(code==153) $.each( $(".bizness > td > input") , function(){ 
														   		if( this.value == '' && this.name != 'doc_fax' ) deny = 1;
														   } );
	//проверка на незаполненные поля и на неправильно заполненные
	if(code==153) if($("div.state_required",document).length || $("div.state_invalid",document).length) deny = 1;
	if(code==154)
	{ 
		if($( "div.state_required", $( "tr:not(.bizness)" , document ) ).length || $( "div.state_invalid", $( "tr:not(.bizness)" , document ) ).length)
			deny = 1;
	}
			
	if(el.soglasen.checked != true ) 
	{
		if( deny == false )
		{
		alert("Для заключения договора необходимо согласиться с нашими условиями предоставления услуг.");
		el.soglasen.focus();
		return false;
		}
	}
	if(deny){alert("Пожалуйста, проверьте правильность введенных данных."); return false; }
	else return true;
}

//request check domain
function loadDomains(domainInfo,obj,callback){
		
	var sdata = new Array();
	sdata['ajax'] = 1;
	sdata['domain'] = domainInfo;
	r = new JsHttpRequest();
	r.caching = false;
	r.open('GET',HTTP+'?mod=889',true);
	r.send(sdata);
	r.onreadystatechange = function(){
		if (this.readyState == 4){
			if(this.responseJS){
				eval(callback+"(this.responseJS.status,obj)");	
				return false;
			}
			eval(callback+"(false,obj)");
		}
	}		
}

function loadingOrder(obj,status){
	if(!obj) return false;;
	pr = obj.parentNode;
	with(pr){
	  if(status){
		if(obj.name=="doc_subdomen") {
			obj.style.display="none";
			style.background="url("+psIMG+"ajax-loader_line.gif) 50% 50% no-repeat";
		}
		else {
			obj.style.visibility="hidden";
			style.background="url("+psIMG+"ajax-loader_line.gif) 7px 4px no-repeat";
		}
	  }
	  else{
		 if(obj.name=="doc_subdomen") {
			obj.style.display="";
		}
		else {
			obj.style.visibility="visible";
		}
		style.background = "";
	  }
	}
	
	
}

//внрхняя проверка
function setDomainStatus(status,obj){
	if(!obj) obj=get("topcheck");
	loadingOrder(document.getElementById("mform").doc_subdomen,0);
	switch(parseInt(status)){
		case 1:
			obj.innerHTML = 'Свободен';
			obj.style.color='#0F7F1F';
			//obj.style.textDecoration='underline';
			$("#doc_subdomen_state").attr("class","state_validated");
		break;
		case 0:
			obj.innerHTML = 'Занят';
			obj.style.color='#FF6F6F';
			//obj.style.textDecoration='underline';
			$("#doc_subdomen_state").attr("class","state_invalid");
		break;
		default:
			obj.innerHTML = 'Не удалось проверить';
			obj.style.color='#CF6A19';
			//obj.style.textDecoration='underline';
			$("#doc_subdomen_state").attr("class","state_invalid");
		break;
	}
}

//дополнительные услуги
function setSubDomainStatus(status,el){
	loadingOrder(el,0);
	if(!el) return false;
	var obj=get("b"+el.id);
	switch(parseInt(status)){
		case 0:
			obj.innerHTML = 'Домен занят';
			obj.style.color='#FF6F6F';
			checkInvalid(el.id,2);
		break;
		case 1:
			obj.innerHTML = 'Свободен';
			obj.style.color='#0F7F1F';
			checkInvalid(el.id,1);
		break;
		default:
			obj.innerHTML = 'Не удалось проверить';
			obj.style.color='#CF6A19';
			checkInvalid(el.id,2);
		break;
	}	
}

function checkInvalid(id_name,free){
	var VRegExp = new RegExp(/check/);
    var VResult = id_name.replace(VRegExp, ""); 
	
	eval( " var status = get(\"checkbox"+VResult+"\").checked" );
	
	if( status ) $("#invalid"+VResult).attr("class","state_invalid");
	else $("#invalid"+VResult).attr("class","free");
	
	if( free==1 ) $("#invalid"+VResult).attr("class","free");
	if( free==2 ) $("#invalid"+VResult).attr("class","state_invalid");
	
	//alert( $("#invalid"+VResult).attr("class") );
}

//проверяет скрывать ли ссылку
function checkdomainsDescLink(){
	
	if( $(".doms:checked").length < 1 ) $("#domainsDescLink").css({display:"none"});
	//alert( $("#invalid"+VResult).attr("class") );
}


function getTemplate(obj){

$.ajaxSetup({
   url: "/order",
   dataType: "json",
   global: false,
   type: "POST"
});
$.ajax({data: $("#mform").serialize()+'&ajax=1&cmd=save_post_data',
   success: function(ResponseJS){
	 //jse(ResponseJS.js);
	 window.location = obj.href;
   }
 });
	
}

function switchs(id){
	get('doc_type_order').className='state_validated';
	$(".bizness").css({display: (id==153)?'':'none' });
	$(".alertFace").css({display: (id==153)?'none':'' });
}

function get(name){// функция захвата объекта, используется при инициализации
		if (document.getElementById) return document.getElementById(name);
		else if (document.all) return document.all[name];
		else if (document.layers) return document.layers[name];
		else return false;
}

//-- End Заказ -------------------------------------------



//--- misc ---------------------------------------------------

function trimS(sInString){
sInString = sInString.replace(/ /g,"");
return sInString.replace(/(^\s+)|(\s+$)/g, "");
}

//echo
function jse(input)
{
	switch(typeof(input)){
		
		case 'object':
		for(x in input)
		{
			if(typeof(input[x])=='object') jse(input[x]);
			else alert('obj{ '+x+' =>  '+input[x]+' }');
		}	
		break;
		case 'string':
		alert('string: '+input);	
		break;
		default:
		break;
	}

}