var pd4Print=function()
{
	var fio=$('ContactFIO').value;
	var total=$('totalPrice').innerHTML;
	if(fio.length<1){ alert('Введите ФИО!'); return; }
	window.open('pd4/?fio='+fio+'&total='+total);
	return false;
};

var Ab = Class.create();
Ab.prototype = {
	initialize:function(){
		Abacus.ShowHeight();
		Event.observe("height_mm", "change", Abacus.SetHeight);
		data.height=300;
		data.PaspartuSizeUP=0;
		data.PaspartuSizeBOK=0;
		data.PaspartuSizeDOWN=0;
		data.PaspartuMiddleSizeWidth=0;
		data.PaspartuBottomSizeWidth=0;
		$("LoadImage").hide();
		$("LoadTab1").hide();
		$("LoadTab2").hide();
		$("LoadTab3").hide();
		Abacus.LoadData();
	}
}
var data={};

// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	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;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

var Abacus = {
	
	Reset: function() {
		
		if (data.Locked==1) return false;
		
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( {Reset:1} ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					// var obj = eval("("+res.responseText+")");
					
					$('WallForImage').style.background = 'url(img/texture1.gif)';
					
					Abacus.LoadData();
					Abacus.ShowImage();
				}
			}
		);		
	},

	SetImageFromGallery: function(id_gallery) {
		
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( {id_gallery:id_gallery} ).toQueryString(),

				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){

					Abacus.SetHeight($F("height_mm"));

					Abacus.LoadData();
					Abacus.ShowImage();
				}
			}
		);				
	},
	ShowHeight:function(){
		
		var list = $('height_mm');
		var count = 0;
		for (i = 100; i <= 3000; i++){
			
			var el = document.createElement('option');
			el.text  = i;
			el.value = i;
			
			try {
			    list.add(el, null); // standards compliant; doesn't work in IE
			} catch(ex) {
				list.add(el); // IE only
			}
			
			if ( i == 300 ) list.options[count].selected = true;
			i += 9;
			count++;
		}
	},
	
	
	SetHeight:function(){
		height = $F("height_mm");
		data.height = height;
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( {setheight:1, height:height} ).toQueryString(),

				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					var obj = eval("("+res.responseText+")");
					data.width = obj.width;
					$("width_mm").value = data.width;
					//$('debug').innerHTML = res.responseText+" хорошо";
				}
			}
		);
	},
	ShowImage:function(){
		$("LoadImage").style.display="block";
		$("build_image").src="js/new.php?toImage=1&nocache="+Math.floor(Math.random() * (57657+1));
		$("build_image").onload = function(){$("LoadImage").hide();}
	},
	DataContents:function(){
		data.toSession = 1;
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( data ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					var obj = eval("("+res.responseText+")");
					if (data.Locked==1) Abacus.Unlock();
					data.width = obj.width;
					$("width_mm").value = obj.width;
					data.price = obj.price;
					$("TotalPrice").innerHTML = obj.price;
					//$('debug').innerHTML=res.responseText+" хорошо";
					
					Abacus.LoadData();
				}
			}
		);
		data.toSession = 0;
	},
	chk:function(){
		data.chk=1;
		new Ajax.Request(
						 "js/new.php",
						 {
							method:"post",
							postBody:$H( data ).toQueryString(),
							onFailure:function(res){
									$('debug').innerHTML=res.responseText+" фигово";
								},
							onSuccess:function(res){
									$('debug').innerHTML=res.responseText+" хорошо";
									
								}
							}
						 );
		data.chk=0;
	},
	LoadData:function(){
		data.loaddata=1;
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( data ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					//$('debug').innerHTML=res.responseText+" хорошо";
					var obj = eval("("+res.responseText+")");
					if (obj.File) {
						// прячем сообщение о необхомости загрузить файл
						$('default_state').style.display = 'none';
						var text="";
						for (i in obj) data[i]=obj[i];
						if (data.height) {
							$("height_mm").value=data.height;
							$("width_mm").value=data.width;
						}
						
						if ( typeof(data.price) == 'undefined' || data.price == '' ) data.price = 0;
						
						$("TotalPrice").innerHTML = data.price;
						$("ImageName").innerHTML = data.Name;
						if (data.Locked==1){
							data.Locked=0;
							Abacus.Unlock();
						}
					} else {
						// показываем сообщение о необходимости загрузить файл
						$('default_state').style.display = 'block';
					}
					//$('debug').innerHTML=text+" хорошо";
					//this.ShowImage();
				}
			}
			);
		data.loaddata=0;
	},
	SwitchTab:function(id){

		for(i=1;i<=4;i++)
			$('tab'+i+'').className="tab";
		for(i=1;i<=4;i++)
			$('cont'+i+'').style.display="none";
		$('tab'+id).className="tab-act";
		$('cont'+id).style.display="block";
	},
	
	SetPaspartuType:function(){
				
		Paspartu.type = $('PaspartuType').options[$('PaspartuType').selectedIndex].value;
		
		if ( Paspartu.type == 0 ) {
			$('setup_paspartu').hide();
			Paspartu.Unset();
			return;		
		} else {
			$('setup_paspartu').show();
			Paspartu.LoadPaspartu();
		}	
		
		if (Paspartu.type == 3) {
			var tmp_size_width = ( data.PaspartuBottomSizeWidth && data.PaspartuBottomSizeWidth > 0) ? data.PaspartuBottomSizeWidth : '';
			$("PaspartuSizesTR").update("<td>Ширина:</td><td><input class='textfield' size='5' name='PaspartuSizesWidth' id='PaspartuSizesWidth' onChange=\"Abacus.ChangeParameter('PaspartuBottomSizeWidth', this.value, true)\" value='"+tmp_size_width+"' /><br /><br /></td><td></td><td></td><td></td><td></td>");
		}
		
		if (Paspartu.type == 2) {
			var tmp_size_width = ( data.PaspartuMiddleSizeWidth && data.PaspartuMiddleSizeWidth > 0) ? data.PaspartuMiddleSizeWidth : '';
			$("PaspartuSizesTR").update("<td>Ширина:</td><td><input class='textfield' size='5' name='PaspartuSizesWidth' id='PaspartuSizesWidth' onChange=\"Abacus.ChangeParameter('PaspartuMiddleSizeWidth', this.value, true)\" value='"+tmp_size_width+"' /><br /><br /></td><td></td><td></td><td></td><td></td>");
		}
		
		if (Paspartu.type == 1) { 
			$("PaspartuSizesTR").update("<td>Сверху:</td><td><input class='textfield' size='5' name='PaspartuSizesUP' id='PaspartuSizesUP' onChange=\"Abacus.ChangeParameter('PaspartuSizeUP', this.value, true)\" value='"+(data.PaspartuSizeUP != 0 ? data.PaspartuSizeUP : "")+"' /></td><td>Справа<br />(слева):</td><td><input class='textfield' size='5' name='PaspartuSizesBOK' id='PaspartuSizesBOK' onChange=\"Abacus.ChangeParameter('PaspartuSizeBOK', this.value, true)\" value='"+(data.PaspartuSizeBOK!=0 ? data.PaspartuSizeBOK : "")+"' /></td><td>Снизу:</td><td><input class='textfield' size='5' name='PaspartuSizesDOWN' id='PaspartuSizesDOWN' onChange=\"Abacus.ChangeParameter('PaspartuSizeDOWN', this.value, true)\" value='"+(data.PaspartuSizeDOWN!=0 ? data.PaspartuSizeDOWN : "")+"' /></td>");
		}	
		
	},
	ChangeParameter:function(param, val){
		data[param] = val;
		ajax = arguments[2];
		
		if (!ajax) new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( { parameter:param, value:val, ChangeParameter:"1" } ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					//alert(content.substr(content.length-100,100));
					//$('debug').innerHTML=res.responseText+param;
				}
			}
		);
	},
	Unlock:function(){
		Bagets.LoadBagets();
		data.Locked=0;
	},
	CountPrice:function(){
		// не используем. но реализуем.
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( {CountPrice:"1" } ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					var obj = eval("("+res.responseText+")");
					$("TotalPrice").innerHTML = obj.price;
					//alert(content.substr(content.length-100,100));
					//$('debug').innerHTML=res.responseText+param;
				}
			}
		);
	},
	
	HideSelect: function () {
		// прячем список высоты
		$('height_mm').hide();	
		$('type_baget').hide();
		$('ChooseWall').hide();
		$('PaspartuType').hide();
	},
	
	ShowSelect: function() {
		$('height_mm').show();
		$('type_baget').show();
		$('ChooseWall').show();	
		$('PaspartuType').show();
	},
	ShowExImages:function(Genre){
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( { Genre:Genre } ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					Abacus.HideSelect();

					var images = eval("("+res.responseText+")");
					var PageSizes = getPageSize();
					
					overlay=document.createElement("div");
					overlay.id="overlay";
					overlay.style.display = 'none';
					document.body.appendChild(overlay);
					Element.setHeight('overlay',PageSizes[0]);
					
					popup=document.createElement("div");
					
					popup.className="popup";
					popup.id="popup";
					content="<div class=title><a href='javascript:void(0)' onClick='Bagets.HidePopup()'>Закрыть окно</a></div>";
					Length = images.IDs.length;
					content+="<ul class=list>";
					for (i=0; i<Length; i++){
						content+="<li><a class=imgs><img src='netcat_files/395/237/"+images.Smalls[i]+"' bFile='"+images.Bigs[i]+"' caption='"+images.Captions[i]+"' onClick='Abacus.SetExImage(this)' /></a>"+images.Captions[i]+"</li>";
					}
					content+="</ul>";
					
					x = PageSizes[2] / 2 - 300;
					y = PageSizes[3] / 2 - 300;
					// popup.style.top=y+"px";
					popup.style.top="220px";
					popup.style.left=x+"px";
					new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.7, afterFinish:function(o){document.body.appendChild(popup);new Insertion.Bottom("popup",content);} });
					
					//alert(content.substr(content.length-100,100));
					//$('debug').innerHTML=res.responseText+" картинки";
				}
			}
		);
	},
	SetExImage:function(obj){
		data.File="";
		Try.these(
			function() {
				data.File=obj.readAttribute('bFile');
				data.Name=obj.readAttribute('caption');
			},
			function() {	
				data.File=obj.bFile;
				data.Name=obj.caption;
			}
		);
		
		data.path="netcat_files/395/237/";
		$("ImageName").innerHTML=data.Name;
		//data.nocache = "rf"+Math.floor(Math.random() * (57657+1));
		Abacus.DataContents();
		Bagets.HidePopup();
		
	},
	Save:function(){
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( { save:"1" } ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){

					//alert(content.substr(content.length-100,100));
					//$('debug').innerHTML=res.responseText+" сохранено";
				}
			}
		);
	},
	ShowEstimate:function(){
	
		if (data.Locked==1) return false;
	
		Abacus.HideSelect();

		var PageSizes = getPageSize();
		
		overlay=document.createElement("div");
		overlay.id="overlay";
		overlay.style.display = 'none';
		document.body.appendChild(overlay);
		Element.setHeight('overlay',PageSizes[0]);
		
		popup=document.createElement("div");
		
		popup.className="popup";
		popup.id="popup";
		content="<div class=title><a href='javascript:void(0)' onClick='Bagets.HidePopup()'>Закрыть окно</a></div>";
		
		content += '<div id="place_full_smeta">Загрузка полной сметы...</div>';
		content +="<h2>Форма оформления заказа</h2><br /><form action='' method='post' id='ContactForm'><span style='font-size:11px'>Все поля являются обязательными для заполнения</span><br /><br /><table id=ContactTable><tr><td width='130'>Контактное лицо</td><td><input type='text' name='FIO' id='ContactFIO' /></td></tr><tr><td>E-mail</td><td><input type='text' name='email' id='ContactEmail' /></td></tr> <tr> <td>Телефон</td><td><input type='text' name='phone' id='ContactPhone' /></td></tr><tr><td></td><td><img id='contact_loader' src='../images/loader.gif' style='border:0px; display: none;' /><input type='button' onClick='Abacus.Contact()' id='ContactSubmit' value='Заказать' /></td> </tr><tr><td></td><!-- <td><a href=\"#\" onclick=\"return pd4Print();\">Распечатать квитанцию</a></td> --></tr></table></form>";
		popup.innerHTML = content;
		x = PageSizes[2] / 2 - 300;
		y = PageSizes[3] / 2 - 300;
		// popup.style.top=y+"px";
		popup.style.top="220px";
		popup.style.left=x+"px";
		new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.7, afterFinish:function(o){document.body.appendChild(popup);} });

		Abacus.LoadFullSmeta();	

	},
	
	LoadFullSmeta: function() {
	
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( { FullSmeta:"1" } ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					$('place_full_smeta').update(res.responseText);
				}
			}
		);					
	},
	
	Contact:function(pr){
	
		$('ContactSubmit').hide();
		$('contact_loader').style.display = 'block';
		
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				encoding:"WINDOWS-1251",
				postBody:$H( { Contact:"1", fio:$F("ContactFIO"), Email:$F("ContactEmail"), Phone:$F("ContactPhone"), Pr:pr } ).toQueryString(),
				onFailure:function(res){
					$('ContactInfo').innerHTML=res.responseText+" не отправлено";
				},
				onSuccess:function(res){

					try {
						var data = res.responseText.evalJSON();
					} catch (e) {
						$('contact_loader').style.display = 'none';
						$('ContactSubmit').show();

						alert('Ошибка при отправке заказа. Повторите попытку позже.');
					}

					if ( data.Error ) {
						$('contact_loader').style.display = 'none';
						$('ContactSubmit').show();

						alert(data.Error);
						return;
					} else {								
						$('ContactForm').innerHTML = '<span>' + data.Message + '</span>';
					}
				}
			}
		);
	},
	
	DeleteSetupItem: function(typeItem) {
		
		// текст вопроса
		var text_confirm = 'Вы действительно хотите удалить ';
		
		switch ( typeItem ) {
			case 'baget':
				text_confirm += 'Багет';
				break;
			case 'paspartu_top':
				text_confirm += 'Верхнее паспарту';
				break;
			case 'paspartu_middle':
				text_confirm += 'Среднее паспарту';
				break;
			case 'paspartu_bottom':
				text_confirm += 'Нижнее паспарту';
				break;
			case 'glass':
				text_confirm += 'Стекло';
				break;
			case 'substrate':
				text_confirm += 'Задник';
				break;				
			default:
				text_confirm += 'Windows';
				break;	
		}
		text_confirm += '?';	
		if ( !confirm(text_confirm) ) return;
	
		// отправляем на удаление 
		new Ajax.Request(
						 "js/new.php",
						 {
							method:"post",
							postBody:$H( { DeleteSetupItem: 1, typeItem: typeItem } ).toQueryString(),
							onFailure:function(res){
									$('debug').innerHTML=res.responseText+" фигово";
								},
							onSuccess:function(res){
									Abacus.LoadFullSmeta();
									Abacus.LoadData();
									Abacus.ShowImage();
								}
							}
						 );	
	},
	
	SaveImage: function() {
		if (data.Locked==1) return false;
	
		document.forms['dowload_form'].submit();
	},
	
	PrintImage: function() {
		if (data.Locked==1) return false;
			
		window.open('js/new.php?print_image=1','print','top=1,left=1,width=600,height=800,toolbar=0,location=0,directories=0,menubar=1,status=0')
	},
	
	SendImage: function() {
		if (data.Locked==1) return false;	
	
		var PageSizes = getPageSize();
		overlay=document.createElement("div");
		overlay.id="overlay";
		overlay.style.display = 'none';
		document.body.appendChild(overlay);
		Element.setHeight('overlay',PageSizes[0]);
		
		popup=document.createElement("div");
		
		popup.className="popup";
		popup.id="popup";
		content="<div class=title><a href='javascript:void(0)' onClick='Bagets.HidePopup()'>Закрыть окно</a></div>";

		// определяем фон
		var back = '';
		
		if ( $('WallForImage').style.backgroundImage ) {
			back = $('WallForImage').style.backgroundImage;
		} else if ( $('WallForImage').style.backgroundColor ) {
			back = $('WallForImage').style.backgroundColor;
		}	
		
		
		content += '<div><div style="float: left; font: 12px Arial; width:240px; height: 480px; padding: 0px 10px 0px 10px; border: 1px solid #000000"><br />';
		content += '<h2>Форма отправки изображения</h2><br />';
		content += '<span style="font-size:11px;">Все поля являются обязательными для заполнения.</span><br /><br />';
		content += '<form method="post" action="js/new.php" target="frame_hidden_send">';
		content += '<input type="hidden" name="SendImage" value="1">';
		content += 'E-mail получателя:<br /><input type="text" name="email_to" value="" style="width: 98%"><br />';
		content += 'Ваш E-mail:<br /><input type="text" name="email_from" value="" style="width: 98%"><br />';
		content += 'Текст сообщения:<br /><textarea name="text" style="width: 98%; height: 100px;"></textarea><br />';		
		content += '<br /><input type="submit" name="but" value="Отправить">';
		content += '</form>';
		content += '<iframe name="frame_hidden_send" style="display:none;"></iframe></div>';
		content += '<div style="float: left; width: 380px; height: 480px;background:' + back + '; text-align: center;"><img src="js/new.php?toImage=1&big=1&nocache='+Math.floor(Math.random() * (57657+1))+'" id=BigImage style="margin: 20px 0 0 0;  width: 330px;" /></div>';
		content += '<div style="clear: left;"></div></div>';
		popup.innerHTML=content;
		x = PageSizes[0] / 2 - 300;
		y = PageSizes[1] / 2 - 400;
		popup.style.top="220px";
		popup.style.left=x+"px";
		new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.7, afterFinish:function(o){document.body.appendChild(popup);} });
	
	} 
};
Abacus.LoadFile = Class.create();
Abacus.LoadFile.prototype = {
	initialize:function(path, value, param){
		
    	var req = new JsHttpRequest();
    
    	req.onreadystatechange = function() {
        	if (req.readyState == 4) {
            
            	//$('result').innerHTML = req.responseJS.q;
            	data.q = req.responseJS.q;
				data.File = req.responseJS.name;
				data.id = req.responseJS.id;
				data.path = req.responseJS.path;
				data.height = req.responseJS.height;
				data.width = req.responseJS.width;
				data.Name = req.responseJS.ImageName;
				$("width_mm").value = data.width;
				$("ImageName").innerHTML = data.Name;
				Abacus.DataContents();
				data.Locked=0;
				Abacus.Unlock();
            	//$('debug').innerHTML = req.responseText;
        	}
    	}
    
    	req.open(null, path, true);
    
    	req.send( { q: value, height: param.height } );
	}
};
Bagets = {
	Activate:function(){
		if (data.Locked==1) return false;
		Abacus.SwitchTab(1);
		if (!Bagets.loaded) {
			Bagets.LoadBagets();
		}
	},
	MenuSortBagets: function() {
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				encoding:"WINDOWS-1251",
				postBody:$H( {MenuSortBagets:"1"} ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					$('place_select_bagets').update(res.responseText);								
					// событие на сортировку	
					Event.observe("type_baget","change",Bagets.LoadBagets);											
				}
			}
		);									
	},
	LoadBagets:function(){
		$("LoadTab1").style.display = "block";
		
		// значение фильтра
		try {
			var sort_value = $('type_baget').options[$('type_baget').selectedIndex].value;
		} catch(e) {	
			var sort_value = 0;
		}
		
		// alert(sort_value);
		
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				encoding:"WINDOWS-1251",
				postBody:$H( {LoadBagets:"1", sort_value: sort_value} ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					
					// очищаем содержимое багета
					$('BagetsTable').update('');
												
					var images = eval("("+res.responseText+")");
					Length = images.Price.length;
					var content = "";
					var act = "";
					for (i=0; i<Length; i++){
						act="";
						if (Bagets.ID==images.IDs[i]) act = " class='act-img'";
						
						content = content + "<tr><td><img id=bagets_"+images.IDs[i]+""+act+" src=netcat_files/347/170/"+images.File[i]+" width=70 height=70 onClick='Bagets.SetBagets(this)' bagetswidth='"+images.Width[i]+"' style='padding:0px;' /></td><td width='100%'>Арт."+images.Articul[i]+"<br />Ширина: "+images.Width[i]+" мм<br />Высота: "+images.Height[i]+" мм<br /><a href=# onClick='Bagets.ShowPopup("+images.IDs[i]+",{ }); return false;'>Полное описание</a><br /><span class=red>Цена: "+images.Price[i]+" руб</span></td></tr>";
					}
					
					$("BagetsTable").appendChild(document.createTextNode(" "));
					new Insertion.Bottom("BagetsTable","<div id=LoadTab1 class='load load-tab'> </div>");
					new Insertion.Bottom("BagetsTable",content);
					
					Bagets.loaded=1;
					$("LoadTab1").hide();
					//alert(content.substr(content.length-1000,1000));
					//$('debug').innerHTML=res.responseText+" багеты";
				}
			}
		);
	},
	SetBagets:function(obj){
		
		$A(document.getElementsByTagName("img", $("BagetsTable"))).each(function(el){
			el.className="";
		});
		obj.className="act-img";
		var req = /bagets_(\d+)/;
		var ids = req.exec(obj.id);
		id = ids[1];
		data.BagetsID = id;
		data.BagetsWidth = obj.bagetswidth;
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( {SetBagets:"1", BagetsID:data.BagetsID, BagetsWidth:data.BagetsWidth } ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					var images = eval("("+res.responseText+")");

					//alert(content.substr(content.length-100,100));
					//$('debug').innerHTML=res.responseText+" багеты";
				}
			}
		);
	},
	ShowPopup:function(id, params) {
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( {LoadBagetsInfo:"1", BagetsID:id} ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
							
					Abacus.HideSelect();
							
					var images = eval("("+res.responseText+")");
					var PageSizes = getPageSize();
					overlay=document.createElement("div");
					overlay.id="overlay";
					overlay.style.display = 'none';
					document.body.appendChild(overlay);
					Element.setHeight('overlay',PageSizes[0]);
					
					popup=document.createElement("div");
									
					popup.className="popup";
					popup.id="popup";
					content="<div class=title><a href='javascript:void(0)' onClick='Bagets.HidePopup()'>Закрыть окно</a></div>";
					if (!params.Magnify) {
						content+="<table><tr><td class=td1><div style='height:339px'><table border=0 width='100%' height='100%'><tr><td height='100%' valign='middle' align='center' style='vertical-align:middle !important;'><img src=netcat_files/347/170/" + images.File + " id=BigImage align='center' style='max-height:320px;' /></td></tr></table></div><div style='text-align: left; margin: 10px; border-bottom: 1px solid #c0c0c0;padding: 10px;'>Артикул: " + images.Articul + ".<br /> Ширина: " + images.Width + "мм, высота: " + images.Height + "мм.<br />Материал: " + images.filletPropMaterial + "<br />Изготовитель: " + images.filletProducter + "<br />Цена: " + images.Price + "руб.<br /><br />" + images.filletDescription + "</div></td><td class=td2><ul class=right>";
						content+="<li><a class=imgs><img src=js/new.php?toImage=1&BagetsID="+id+"&nocache="+Math.floor(Math.random() * (57657+1))+" onClick=\"$('BigImage').src='js/new.php?toImage=1&BagetsID="+id+"&big=1&nocache="+Math.floor(Math.random() * (57657+1))+"'\" /></a></li>";
						if ( images.Front ) content+="<li><a class=imgs><img style='width:100px' src=netcat_files/347/170/"+images.Front+" onclick=$('BigImage').src='netcat_files/347/170/"+images.Front+"' /></a></li>";
						if ( images.Axo ) content+="<li><a class=imgs><img style='width:100px' src=netcat_files/347/170/"+images.Axo+" onclick=$('BigImage').src='netcat_files/347/170/"+images.Axo+"' /></a></li>";
						content += "</ul></td>";
						
					} else {
					
						// определяем фон
						var back = '';
						if ( $('WallForImage').style.backgroundImage ) {
							back = $('WallForImage').style.backgroundImage;
						} else if ( $('WallForImage').style.backgroundColor ) {
							back = $('WallForImage').style.backgroundColor;
						}	
					
						content+="<table><tr><td class=td1 style='background:" + back + "'><img src='js/new.php?toImage=1&big=1&nocache="+Math.floor(Math.random() * (57657+1))+"' id=BigImage /></td>";
					}
					
					content+="</tr></table>";
					popup.innerHTML=content;
					x = PageSizes[0] / 2 - 300;
					y = PageSizes[1] / 2 - 400;
					popup.style.top="220px";
					popup.style.left=x+"px";
					new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.7, afterFinish:function(o){document.body.appendChild(popup);} });
					
					//alert(content.substr(content.length-100,100));
					//$('debug').innerHTML=res.responseText+" попапы";
				}
			}
		);

	},
	HidePopup:function(){
		Element.remove('popup');
		
		// показываем список высот
		Abacus.ShowSelect();
		
		new Effect.Fade('overlay', { duration: 0.2, from: 0.7, to: 0.0, afterFinish:function(o){Element.remove('overlay');} });
		
	}
};

Wall = {
	
	colors_load: false,	
	Activate:function(){
		if (data.Locked==1) return false;
		Abacus.SwitchTab(2);
		if (!Wall.type) Wall.type=1;
		if (!Wall.loaded) 
			Wall.LoadWall();
		
	},
	LoadPalette: function () {
		$('palette').update("<iframe src='js/palette.html' frameborder='0' height='440' width='100%' scrolling ='no'>");
		this.colors_load = true;
	},	
	LoadWall:function(){

		Wall.type = $('ChooseWall').options[$('ChooseWall').selectedIndex].value;
		
		// прячем предварительный просмотр
		if ( Wall.type == 2 ) {
			$('wall-pview').hide();
			$('block2').addClassName('block2_dop');
		} else {
			$('wall-pview').show();
			$('block2').removeClassName('block2_dop');
		}
		
		if (Wall.type==1){
			
			$('WallColor').update('');
			$('palette').style.display = 'block';
			
			// палитра цветов
			if ( !this.colors_load ) this.LoadPalette();
			
			/*
			new Ajax.Request(
				"js/new.php",
				{
					method:"post",
					encoding:"WINDOWS-1251",
					postBody:$H( {LoadWallColor:"1"} ).toQueryString(),
					onFailure:function(res){
						$('debug').innerHTML=res.responseText+" фигово";
					},
					onSuccess:function(res){
					
						// очищаем содержимое
						$('WallColor').update('');
					
						var colors = eval(res.responseText);
						var wall = $("WallForImage");
						
						var content = "";
						for (i=0; i<colors.length; i++){
							if (i%11==0 && i!=0) content = content + "</tr>";
							if (i%11==0) content = content + "<tr>";
							color = colors[i];
							content = content + "<td><div class=\"color-box\" style=\"background-color:"+color+";\" onmousemove=\"$('wall-pview').style.backgroundColor=this.style.backgroundColor\" onClick=\"Wall.SetWallColor('"+color+"')\"></div></td>";
							
						}
						content = content + "</tr>";
						$("WallColor").appendChild(document.createTextNode(" "));
						new Insertion.Bottom("WallColor","<div id=LoadTab2 class='load load-tab'> </div>");
						new Insertion.Bottom("WallColor",content);
						Wall.loaded=1;
						$("LoadTab2").hide();
						//alert(content.substr(content.length-100,100));
						//$('debug').innerHTML=res.responseText+" цвета";
					}
				}
			);
			*/			 
		}
		if (Wall.type==2){
			
			$('palette').style.display = 'none';
			$("LoadTab2").style.display="block";
			
			new Ajax.Request(
				"js/new.php",
				{
					method:"post",
					encoding:"WINDOWS-1251",
					postBody:$H( {LoadWallImage:"1"} ).toQueryString(),
					onFailure:function(res){
						$('debug').innerHTML=res.responseText+" фигово";
					},
					onSuccess:function(res){

						// очищаем содержимое
						$('WallColor').update('');
					
						var images = eval(res.responseText);
						var wall = $("WallForImage");
						
						var content = "";
						for (i=0; i<images.length; i++){
							if (i%3==0 && i!=0) content = content + "</tr>";
							if (i%3==0) content = content + "<tr>";
							image = images[i];
							content = content + "<td><div class=\"wall-box\" style=\"background-image:url(netcat_files/440/275/"+image+");\"  onClick=\"Wall.SetWallImage('"+image+"')\"></div></td>";
						}
						content = content + "</tr>";
						$("WallColor").appendChild(document.createTextNode(" "));
						new Insertion.Bottom("WallColor","<div id=LoadTab2 class='load load-tab'> </div>");
						new Insertion.Bottom("WallColor",content);
						Wall.loaded=1;
						$("LoadTab2").hide();
						//alert(content.substr(content.length-100,100));
						//$('debug').innerHTML=res.responseText+" картинки";
					}
				}
			);
		}
	},
	SetWallColor:function(color){
		//alert("erger");
		$("WallForImage").style.backgroundImage="";
		$("WallForImage").style.backgroundColor=color;

	},
	SetWallImage:function(image){
		$("WallForImage").style.backgroundImage="url(netcat_files/440/275/"+image+")";
	},
	ChooseWall:function(){
		// if (Wall.type==1) Wall.type=2; else Wall.type=1;
		
		Wall.LoadWall();
	}
};
Paspartu = {
	Activate:function(){
		if (data.Locked==1) return false;
		Abacus.SwitchTab(3);
		if (!Paspartu.type) Paspartu.type=1;
		if (!Paspartu.loaded) 
			Paspartu.LoadPaspartu();
		
	},
	LoadPaspartu:function(){
		
		Paspartu.type = $('PaspartuType').options[$('PaspartuType').selectedIndex].value;
	
		$("LoadTab3").style.display="block";
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				encoding:"WINDOWS-1251",
				postBody:$H( {LoadPaspartu:"1", PaspartuType: Paspartu.type} ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
				
					$('PaspartuTable').update('');	
				
					var images = eval("("+res.responseText+")");
					var Length = images.Price.length;
					
					var content = "";
					var act = "";
					
					for (var i=0; i < Length; i++){
						if (i%3==0 && i!=0) content = content + "</tr>";
						if (i%3==0) content = content + "<tr>";
						act = "";
						if (Paspartu.type==1) if (images.IDs[i] == data.PaspartuTop) { act = " act-img"; scrollto=i;}
						if (Paspartu.type==2) if (images.IDs[i] == data.PaspartuMiddle) { act = " act-img"; scrollto=i;}
						if (Paspartu.type==3) if (images.IDs[i] == data.PaspartuBottom) { act = " act-img"; scrollto=i;}
						content = content + "<td><div id=paspartu_"+images.IDs[i]+" class='pic"+act+"' style=\"background-image:url(netcat_files/348/171/"+images.File[i]+"); width:80px; height:58px\" onClick=Paspartu.SetPaspartu(this)> </div><div>Арт.: "+images.Articul[i]+"<br /><b class=\"red\">"+images.Price[i]+" руб./м2</b></div></td>";										
					}
					content = content + "</tr>";
					$("PaspartuTable").appendChild(document.createTextNode(" "));
					new Insertion.Bottom("PaspartuTable","<div id=LoadTab3 class='load load-tab'> </div>");
					new Insertion.Bottom("PaspartuTable",content);
					//$("PaspartuTable").scroll(0,(scrollto%2==0 ? (scrollto - 1) * 120 : scrollto * 120));
					Paspartu.loaded=1;
					$("LoadTab3").hide();
					//alert(content.substr(content.length-100,100));
					//$('debug').innerHTML=res.responseText+" паспарту";
				}
			}
		);
	},
	SetPaspartu:function(obj){
		if (Paspartu.type==0) return alert("Задайте тип паспарту");
		$A(document.getElementsByClassName("pic", $("PaspartuTable"))).each(function(el){ el.className="pic"; });
		obj.className="pic act-img";
		var req = /paspartu_(\d+)/;
		var ids = req.exec(obj.id);
		id = ids[1];
		data.PaspartuID = id;
		if (Paspartu.type==1) data.PaspartuTop = id;
		if (Paspartu.type==2) data.PaspartuMiddle = id;
		if (Paspartu.type==3) data.PaspartuBottom = id;
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				postBody:$H( {SetPaspartu:"1", PaspartuSizeUP:data.PaspartuSizeUP, PaspartuSizeDOWN:data.PaspartuSizeDOWN, PaspartuSizeBOK:data.PaspartuSizeBOK, PaspartuMiddleSizeWidth:data.PaspartuMiddleSizeWidth, PaspartuBottomSizeWidth:data.PaspartuBottomSizeWidth, PaspartuTop:data.PaspartuTop, PaspartuMiddle:data.PaspartuMiddle, PaspartuBottom:data.PaspartuBottom} ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					var images = eval("("+res.responseText+")");
					
					//alert(content.substr(content.length-100,100));
					//$('debug').innerHTML=res.responseText+" паспарту";
				}
			}
		);
	},
	Unset:function(){
		data.PaspartuTop 				= 0;
		data.PaspartuMiddle				= 0;
		data.PaspartuBottom				= 0;
		data.PaspartuSizeUP				= 0;
		data.PaspartuSizeBOK			= 0;
		data.PaspartuSizeDOWN			= 0;
		data.PaspartuMiddleSizeWidth	= 0;
		data.PaspartuBottomSizeWidth	= 0;
		Abacus.DataContents();
	}
};
Glass = {
	Activate:function(){
		if (data.Locked==1) return false;
		Abacus.SwitchTab(4);
		if (!Glass.loaded) 
			Glass.LoadGlass();
		
	},
	LoadGlass:function(){
		new Ajax.Request(
			"js/new.php",
			{
				method:"post",
				encoding:"WINDOWS-1251",
				postBody:$H( {LoadGlass:"1"} ).toQueryString(),
				onFailure:function(res){
					$('debug').innerHTML=res.responseText+" фигово";
				},
				onSuccess:function(res){
					var images = eval("("+res.responseText+")");
					Length = images.SPrice.length;
					var Scontent = "";
					var act = "";
					for (i=0; i<Length; i++){
						act = "";
						if (data.SubstrateID==images.SIDs[i]) act = " act-img";
																
						Scontent = Scontent + "<tr><td width='50%'><div class='img-div"+act+"' id=Substrate_"+images.SIDs[i]+" style=\"background-color:#"+images.SColor[i]+";\" onClick=Glass.SetSubstrate(this)> </div></td><td width='50%'><b>"+images.STitle[i]+"</b><br />Арт.: "+images.SArticul[i]+"<br /><b class='red'>Цена: "+images.SPrice[i]+" руб.</b></td></tr>";
					}
					$("SubstrateTable").appendChild(document.createTextNode(" "));
					
					new Insertion.Bottom("SubstrateTable",Scontent);
					
					Length = images.GPrice.length;
					var Gcontent = "";
					act = "";
					for (i=0; i<Length; i++){
						act = "";
						if (data.GlassID==images.GIDs[i]) act = "class=act-img ";
																
						Gcontent = Gcontent + "<tr><td width='50%'><img "+act+"id=Glass_"+images.GIDs[i]+" src='netcat_files/349/190/"+images.GImage[i]+"' width=85 height=58 onClick=Glass.SetGlass(this) /></td><td width=50%><b>"+images.GTitle[i]+"</b><br />Толщина: "+images.GThickness[i]+" мм<br />Размер листа: "+images.GList[i]+"см<br />Цена: <b class=red>"+images.GPrice[i]+" р/ м2</b></td></tr>";
						
					}
					$("GlassTable").appendChild(document.createTextNode(" "));
					
					new Insertion.Bottom("GlassTable",Gcontent);
					Glass.loaded=1;
					//alert(content.substr(content.length-100,100));
					//$('debug').innerHTML=res.responseText+" паспарту";
				}
			}
		);
	},
	SetSubstrate:function(obj){
		var req = /Substrate_(\d+)/;
		var ids = req.exec(obj.id);
		
		//data.SubstrateID = ids[1];
		$A($("SubstrateTable").getElementsByTagName("div")).each(function(el){
			el.className="img-div";
		});
		obj.className="act-img";
		Abacus.ChangeParameter("SubstrateID", ids[1]);
	},
	SetGlass:function(obj){
		var req = /Glass_(\d+)/;
		var ids = req.exec(obj.id);
		
		//data.GlassID = ids[1];
		$A(document.getElementsByTagName("img", $("GlassTable"))).each(function(el){
			el.className="";
		});
		obj.className="act-img";
		Abacus.ChangeParameter("GlassID", ids[1]);
	}
};
Event.observe(window,"load",function(){ 
	new Ab();
	Ajax.Responders.register({
		onComplete: function(req, transport) {
		
			try{var json = eval("("+transport.responseText+")"); throw "fr";} catch(e){}
			if (json && json.showImage && data.File) Abacus.ShowImage();
			if (json && json.price) $("TotalPrice").innerHTML=json.price;
			//$('debug').innerHTML=transport.responseText+" resp";
			}});
	data.Locked=1;
	
	
	Event.observe("tab1","click",Bagets.Activate);
	Event.observe("tab2","click",Wall.Activate);
	Event.observe("tab3","click",Paspartu.Activate);
	Event.observe("tab4","click",Glass.Activate);
	Event.observe("ChooseWall","change",Wall.ChooseWall);
	Event.observe("PaspartuType","change",Abacus.SetPaspartuType);

	Event.observe("Ex1","click",function(){ Abacus.ShowExImages(1); });
	Event.observe("Ex2","click",function(){ Abacus.ShowExImages(2); });
	Event.observe("Ex3","click",function(){ Abacus.ShowExImages(3); });
	Event.observe("Ex4","click",function(){ Abacus.ShowExImages(4); });
	Event.observe("Magnify","click", function(){ if (data.Locked==1) return false; var tmp = (data.BagetsID) ? data.BagetsID :0; Bagets.ShowPopup(data.BagetsID, { Magnify:"1" });});
	Event.observe("Estimate","click",Abacus.ShowEstimate);
	// меню сортировки багета
	Bagets.MenuSortBagets();

	// палитра цветов
	// Wall.LoadPalette();
	
	// устанавливаем картинку из галереи
	var gallery_id = queryString("gallery_id");
	if ( gallery_id > 0 ) Abacus.SetImageFromGallery(gallery_id);

	// кнопки
	Event.observe("but_save","click",Abacus.SaveImage);
	Event.observe("but_print","click",Abacus.PrintImage);
	Event.observe("but_send","click",Abacus.SendImage);

	//$("WallForImage").setStyle({ backgroundColor: "#e5e5e5" });
	$("WallForImage").style.backgroundColor="#e5e5e5";
	$("WallForImage").style.backgroundImage="url(img/texture1.gif)";									
	Element.remove("MainLoader");
	$("MainTable").style.top="0px";
});



function preview_color(color) {
	$('wall-pview').style.backgroundColor = "#" + color;
}

function select_color(color) {
	Wall.SetWallColor('#' + color);
}

function PageQuery(q) {
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
	for(var j=0; j < this.keyValuePairs.length; j++) {
		if(this.keyValuePairs[j].split("=")[0] == s)
			return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }
}

function queryString(key){
	var page = new PageQuery(window.location.search);
	return unescape(page.getValue(key));
}
