	function bookRegister() {
		var email = document.getElementById('email');
		var notice = document.getElementById('notice');
		if (! checkEmail(email.value)) {
			setNotice(notice, true, "Проверьте правильность адреса, как-то он не очень... :) " +
				"Хочется чего-то вроде email@server.com");
			email.select(); email.focus();
		} else {
			if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
			setNotice(notice, false, "Обрабатываем...");
			xmlHttp.onreadystatechange = handleBookRegister;
			xmlHttp.open("GET", www+"ajax.php?xml=true&bookregister=" + email.value, true);
			xmlHttp.send(null);
		}

		return false;
	}

	function handleBookRegister () {
		if(xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			xml = xmlHttp.responseXML;                     
			if (xml.getElementsByTagName("sent").length > 0) {
				setNotice(notice, false, "На ваш e-mail отправлено письмо! Большое спасибо за внимание к моему проекту!");
			} else {
				setNotice(notice, true, "Почему-то не удалось связаться... " +
			  		"Если с e-mail все в порядке (проверьте на всякий случай еще раз?), значит глюки на " +
			  		"нашей стороне. Мы будем над этим работать. Извините :о)");
				email.select(); email.focus();
			}
		}
	}

	var paymethod = null;

	function validatePrice(val) {
		return val.match(/^\s*\d*\.?\d+\s*$/) && ! val.match(/^0+$/);
	}

	var wmnotice;
	var ymnotice;
	var sbernotice;
	var ccnotice;
	var cashnotice;
	var ppnotice;
	var mbnotice;
	var smsnotice;
	var ownnotice;

	function buy() {
		var price = document.getElementById('price');
		var notice = document.getElementById('notice');

		if (! validatePrice(price.value)) {
			setNotice(notice, true, "Какая-то странная цена. Хочется числа > 0, например 50 или 234.12");
			price.focus();
			price.select();
		} else {
		 	removeChildren(notice);
		 	document.getElementById('originalbuy').disabled = "disabled";
		 	document.getElementById('paymethod').style.display = "block";

			if (paymethod == null)  {
				var defaultPayMethod = 1;
//				choosePayMethod(defaultPayMethod);
//				document.getElementById('paymethod' + defaultPayMethod).focus();
			} else if (validate(paymethod)) {
			 	// todo: buy it!

			 	switch(paymethod) {
					case 0: 	// Own
						ownnotice = document.getElementById('ownnotice');
						var ownway = document.getElementById('ownway');

						if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
						else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
						setNotice(ownnotice, false, "Обрабатываем...");
						xmlHttp.onreadystatechange = handleOwn;
						xmlHttp.open("POST", 
							www+"ajax.php?xml=true&buy=" + paymethod + 
							"&price=" + price.value +
							"&currency=RUB" + 
							"&ts=" + new Date().getTime(), false);
						xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
						xmlHttp.send("ownway=" + encodeURIComponent(ownway.value));
						break;

					case 1: 	// WM
						var wmid = document.getElementById('wmid');
						wmnotice = document.getElementById('wmnotice');
			
						if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
						else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
						setNotice(wmnotice, false, "Обрабатываем...");
						xmlHttp.onreadystatechange = handleWM;
						xmlHttp.open("GET", 
							www+"ajax.php?xml=true&buy=" + paymethod + 
							"&price=" + price.value +
							"&currency=RUB" + 
							"&wmid=" + wmid.value + 
							"&ts=" + new Date().getTime(), false);
						xmlHttp.send(null);
						break;

					case 2:		// Y.Money
						ymnotice = document.getElementById('ymnotice');
						document.getElementById('CompanySum').value = price.value;

						if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
						else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
						setNotice(ymnotice, false, "Обрабатываем...");
						xmlHttp.onreadystatechange = handleYM;
						xmlHttp.open("GET", 
							www+"ajax.php?xml=true&buy=" + paymethod + 
							"&price=" + price.value +
							"&currency=RUB" + 
							"&ts=" + new Date().getTime(), false);
						xmlHttp.send(null);
						return true;

					case 3: 	// Sberbank
						sbernotice = document.getElementById('sbernotice');

						if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
						else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
						setNotice(sbernotice, false, "Обрабатываем...");
						xmlHttp.onreadystatechange = handleSber;
						xmlHttp.open("GET", 
							www+"ajax.php?xml=true&buy=" + paymethod + 
							"&price=" + price.value +
							"&currency=RUB" + 
							"&ts=" + new Date().getTime(), false);
						xmlHttp.send(null);

						var w = window.open("", "sberbank", 'width=640,height=480');
						var rub = price.value.indexOf('.') > 0 
							? price.value.substring(0, price.value.indexOf('.')) 
							: price.value;
						var kop = price.value.indexOf('.') > 0 
							? price.value.substring(price.value.indexOf('.') + 1, price.value.indexOf('.') + 3) 
							: '0';

						w.document.write(
							'<html><head><title>Спасибо за книгу &laquo;Не мешайте мне работать!&raquo;</title>' +
							'<meta http-equiv="Content-Type" content="text/html; charset=windows-1251"/>' + 
							'<style type="text/css">body{font:0.5cm/0.7cm Arial;}</style>'+
							'</head><body>'+
							'<h1>Спасибо за книгу &laquo;Не мешайте мне работать!&raquo;</h1>' +
							'<p>Красногвардейское отделение Сбербанка России №&nbsp;8074/098<br/>' +
							'Р/сч 30301810855000605513 в Филиале АК СБ РФ<br/>'+
							'Северо-Западного банка<br/>' +
							'К/сч 30101810500000000653, БИК 044030653,<br/>' +
							'ИНН 7707083893, КПП 780632001<br/>' +
							'Лицевой счет 42307810255130350265<br/>' +
							'Давыдов Станислав Валерьевич</p>' +
							'<p>Сумма: <strong>' + rub + ' рублей ' + kop + ' копеек</strong></p>' +
							'<p><a href="javascript: print();">Распечатать</a></p>'+
							'</body></html>');
						break;
					case 4:		// Cach
						cashnotice = document.getElementById('cashnotice');

						if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
						else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
						setNotice(cashnotice, false, "Обрабатываем...");
						xmlHttp.onreadystatechange = handleCash;
						xmlHttp.open("GET", 
							www+"ajax.php?xml=true&buy=" + paymethod + 
							"&price=" + price.value +
							"&currency=RUB" + 
							"&ts=" + new Date().getTime(), true);
						xmlHttp.send(null);
						break;

					case 5:		// CC
						ccnotice = document.getElementById('ccnotice');
						var ccPrice = document.getElementById('ccPrice');
						var bCur = document.getElementById('bCur');

						if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
						else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
						setNotice(ccnotice, false, "Обрабатываем...");
						xmlHttp.onreadystatechange = handleCC;
						xmlHttp.open("GET", 
							www+"ajax.php?xml=true&buy=" + paymethod + 
							"&price=" + ccPrice.value +
							"&currency=" + bCur.value + 
							"&ts=" + new Date().getTime(), false);
						xmlHttp.send(null);
						return true;

					case 6:		// Moneybookers
						mbnotice = document.getElementById('mbnotice');
						var moneybookersAmount = document.getElementById('moneybookersAmount');

						if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
						else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
						setNotice(mbnotice, false, "Обрабатываем...");
						xmlHttp.onreadystatechange = handleMoneybookers;
						xmlHttp.open("GET", 
							www+"ajax.php?xml=true&buy=" + paymethod + 
							"&price=" + moneybookersAmount.value +
							"&currency=USD" + 
							"&ts=" + new Date().getTime(), false);
						xmlHttp.send(null);
						return true;

					case 7:		// PayPal
						ppnotice = document.getElementById('ppnotice');
						var paypalprice = document.getElementById('paypalprice');
						if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
						else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
						setNotice(ppnotice, false, "Обрабатываем...");
						xmlHttp.onreadystatechange = handlePayPal;
						xmlHttp.open("GET", 
							www+"ajax.php?xml=true&buy=" + paymethod + 
							"&price=" + paypalprice.value +
							"&currency=USD" + 
							"&ts=" + new Date().getTime(), false);
						xmlHttp.send(null);
						break;
					case 8:		// SMS
						smsnotice = document.getElementById('smsnotice');
						if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
						else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
						setNotice(smsnotice, false, "Обрабатываем...");
						var smsamount = document.getElementById('smsamount');
						xmlHttp.onreadystatechange = handleSMS;
						xmlHttp.open("GET", 
							www+"ajax.php?xml=true&buy=" + paymethod + 
							"&price=" + smsamount.value +
							"&currency=USD" + 
							"&ts=" + new Date().getTime(), false);
						xmlHttp.send(null);

						if (navigator.userAgent.indexOf('Firefox/3') != -1)
							handleSMSBody();

						if (smsOrderId != null) {
							var smsorderid = document.getElementById('smsorderid');
							smsorderid.value = smsOrderId;
							var smssign = document.getElementById('smssign');
							smssign.value = smsSign;
					
							return true;
						}
			 	}
			}
		}
		return false;
	}

	function handleOwn() {
		if(xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			xml = xmlHttp.responseXML;

			var wrong = xml.getElementsByTagName('wrong');
			if (wrong.length > 0) {
				setNotice(ownnotice, true, 
					"Возникли какие-то проблемы: " + wrong[0].firstChild.nodeValue + 
					". Наша служба поддержки уже получила письмо об этом. " +
					"На всякий случай, попробуйте предложить еще раз.");
			} else {
				setNotice(ownnotice, false, 
					"Спасибо за предложение! Я отвечу вам настолько быстро, насколько смогу.");
			}
		}
	}

	function handleWM() {
		if(xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			xml = xmlHttp.responseXML;

			var wrong = xml.getElementsByTagName('wrong');
			if (wrong.length > 0) {
				setNotice(wmnotice, true, 
					"Возникли какие-то проблемы: " + wrong[0].firstChild.nodeValue + 
					". Наша служба поддержки уже получила письмо об этом. " +
					"На всякий случай, попробуйте выписать счет еще раз.");
			} else {
				setNotice(wmnotice, false, 
					"Счет выписан. Спасибо вам больше за интерес к моему проекту!");
			}
		}
	}

	function handleYM() {
		if(xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			xml = xmlHttp.responseXML;

			var wrong = xml.getElementsByTagName('wrong');
			if (wrong.length > 0) {
				setNotice(ymnotice, true, 
					"Возникли какие-то проблемы: " + wrong[0].firstChild.nodeValue + 
					". Наша служба поддержки уже получила письмо об этом. " +
					"На всякий случай, попробуйте перечислить еще раз.");
			} else {
				setNotice(ymnotice, false, 
					"Спасибо за желание купить мою книгу! Форма оплаты должна открыться в новом окне.");
			}
		}
	}

	function handleSber() {
		if(xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			xml = xmlHttp.responseXML;

			var wrong = xml.getElementsByTagName('wrong');
			if (wrong.length > 0) {
				setNotice(sbernotice, true, 
					"Возникли какие-то проблемы: " + wrong[0].firstChild.nodeValue + 
					". Наша служба поддержки уже получила письмо об этом. " +
					"На всякий случай, попробуйте распечатать еще раз.");
			} else {
				setNotice(sbernotice, false, 
					"Спасибо за желание купить мою книгу! Квитанция на оплату должна открыться в новом окне.");
			}
		}
	}

	function handleCash() {
		if(xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			xml = xmlHttp.responseXML;

			var wrong = xml.getElementsByTagName('wrong');
			if (wrong.length > 0) {
				setNotice(cashnotice, true, 
					"Возникли какие-то проблемы: " + wrong[0].firstChild.nodeValue + 
					". Наша служба поддержки уже получила письмо об этом. " +
					"На всякий случай, давайте попробуем встретиться еще раз :)");
			} else {
				setNotice(cashnotice, false, 
					"Спасибо большое за покупку!");
			}
		}
	}

	function handleCC() {
		if(xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			xml = xmlHttp.responseXML;

			var wrong = xml.getElementsByTagName('wrong');
			if (wrong.length > 0) {
				setNotice(ccnotice, true, 
					"Возникли какие-то проблемы: " + wrong[0].firstChild.nodeValue + 
					". Наша служба поддержки уже получила письмо об этом. " +
					"На всякий случай, попробуйте нажать на кнопку еще раз.");
			} else {
				setNotice(ccnotice, false, 
					"Спасибо за покупку!");
			}
		}
	}

	function handleMoneybookers() {
		if(xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			xml = xmlHttp.responseXML;

			var wrong = xml.getElementsByTagName('wrong');
			if (wrong.length > 0) {
				setNotice(mbnotice, true, 
					"Возникли какие-то проблемы: " + wrong[0].firstChild.nodeValue + 
					". Наша служба поддержки уже получила письмо об этом. " +
					"На всякий случай, попробуйте нажать на кнопку еще раз.");
			} else {
				setNotice(mbnotice, false, 
					"Спасибо за желание купить мою книгу! Форма оплаты должна открыться в новом окне.");
			}
		}
	}

	function handlePayPal() {
		if(xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			xml = xmlHttp.responseXML;

			var wrong = xml.getElementsByTagName('wrong');
			if (wrong.length > 0) {
				setNotice(ppnotice, true, 
					"Возникли какие-то проблемы: " + wrong[0].firstChild.nodeValue + 
					". Наша служба поддержки уже получила письмо об этом. " +
					"На всякий случай, попробуйте нажать на кнопку еще раз.");
			} else {
				setNotice(ppnotice, false, 
					"Спасибо за покупку! Я дам вам занть, что деньги пришли, настолько быстро, насколько смогу.");
			}
		}
	}

	var smsOrderId;
	var smsSign;

	function handleSMSBody() {
		xml = xmlHttp.responseXML;

		var wrong = xml.getElementsByTagName('wrong');
		if (wrong.length > 0) {
			setNotice(smsnotice, true, 
				"Возникли какие-то проблемы: " + wrong[0].firstChild.nodeValue + 
				". Наша служба поддержки уже получила письмо об этом. " +
				"На всякий случай, попробуйте нажать кнопку еще раз.");
			smsOrderId = null;
		} else {
			var result = xml.getElementsByTagName('done')[0];
			smsOrderId = result.getAttribute('id');
			smsSign = result.getAttribute('sign');
			setNotice(smsnotice, false, 
				"Спасибо за покупку! Я дам вам занть, что деньги пришли, настолько быстро, насколько смогу.");
		}
	}

	function handleSMS() {
		if(xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			handleSMSBody();
		}
	}

	function showPayMethod(m) {
		var notice = document.getElementById('subnotice');
		removeChildren(notice);
		for(var i = 0; i <= 8; i++) {
			var el = document.getElementById('paymethod' + i + 'details');
			if (el) {
				el.style.display = i==m ? "block" : "none";
			}

			var el = document.getElementById('paymethod' + i);
			if (el) {
				setElClass(el, i==m ? 'selected' : 'case');
			}
		}
	}

	function validate(m) {
	 	switch(m) {
	 		case 1: 	// WebMoney
				var wmid = document.getElementById('wmid');
				var wmnotice = document.getElementById('wmnotice');
				removeChildren(wmnotice);
				if (wmid.value.match(/([^\d]|^\s*$)/)) {
					setNotice(wmnotice, true, 
						"Какой-то странный WM ID, всегда считал, что он состоит из цифр. Проверьте?");
					wmid.focus();
					wmid.select();
					return false;					
				}
				break;
			case 4:
				break;
			case 5:
				var ccPrice = document.getElementById('ccPrice');
				var ccnotice = document.getElementById('ccnotice');
				removeChildren(ccnotice);
				if (! validatePrice(ccPrice.value)) {
					setNotice(ccnotice, true, "Какая-то странная цена. Хочется числа > 0, например 0.50 или 15.49");
					ccPrice.focus();
					ccPrice.select();
					return false;				
				}
				break;
			case 6:
				var moneybookersAmount = document.getElementById('moneybookersAmount');
				var mbnotice = document.getElementById('mbnotice');
				removeChildren(mbnotice);
				if (! validatePrice(moneybookersAmount.value)) {
					setNotice(mbnotice, true, "Какая-то странная цена. Хочется числа > 0, например 0.50 или 15.49");
					moneybookersAmount.focus();
					moneybookersAmount.select();
					return false;				
				}
				break;
			case 8:
				var smsAmount = document.getElementById('smsamount');
				var smsnotice = document.getElementById('smsnotice');
				removeChildren(smsnotice);
				if (! validatePrice(smsAmount.value)) {
					setNotice(smsnotice, true, "Какая-то странная цена. Хочется числа > 0, например 0.50 или 15.49");
					smsAmount.focus();
					smsAmount.select();
					return false;				
				}
				break;
	 	}
	 	return true;
	}

	function getParams(m) {
		var params = '';
	 	switch(m) {
	 		case 1: 	// WebMoney
				var wmid = document.getElementById('wmid');
				params += 'wmid=' + encodeURIComponent(wmid.value);
				break;
			case 4:
				var name = document.getElementById('name');
				var email = document.getElementById('email');
				params += 
					'name=' + encodeURIComponent(name.value) +  
					'&email=' + encodeURIComponent(email.value);
				break;
		}
		return params;
	}

	function RUR2USD(rur) {
		var usd = "";
		if (rur != "")
			usd = "" + rur / 24.5;
		var pos = usd.indexOf('.');
		if (pos > 0)
			usd = usd.substring(0, pos + 3 < usd.length ? pos + 3 : usd.length);
		return usd;
	}

	var methoddetails;
	function choosePayMethod(m) {
		document.getElementById('cases').style.display = "none";
		paymethod = m;
		showPayMethod(m);
	 	switch(m) {
	 		case 0:	// own way
	 			document.getElementById('paymethod0').style.display = "block";
	 			break;
	 		case 1: 	// WebMoney
				break;
			case 4:
				break;
			case 5: 	// CC
				var ccPrice = document.getElementById('ccPrice');
				if (ccPrice.value == "") {
					ccPrice.value = document.getElementById('price').value;
				}
				break;
			case 6:		// Moneybookers
				var moneybookersAmount = document.getElementById('moneybookersAmount');
				if (moneybookersAmount.value == "") {
					moneybookersAmount.value = RUR2USD(document.getElementById('price').value);
				}
				break;
			case 7:		// PayPal
//				var paypalprice = document.getElementById('paypalprice');
//				if (paypalprice.value == "") {
//					paypalprice.value = RUR2USD(document.getElementById('price').value);
//				}
			case 8:
				var smsamount = document.getElementById('smsamount');
				if(smsamount.value == "")
					smsamount.value = RUR2USD(document.getElementById('price').value);
				break;
	 	}
	}

	var emailnotice;

	function getByEmail() {
		emailnotice = document.getElementById('emailnotice');
		removeChildren(emailnotice);
		if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
		setNotice(emailnotice, false, "Отправляем...");
		xmlHttp.onreadystatechange = handleGetByEmail;
		xmlHttp.open("GET", 
			www+"ajax.php?xml=true&getbyemail=" +
			"&ts=" + new Date().getTime(), true);
		xmlHttp.send(null);
	}
	function handleGetByEmail() {
		if(xmlHttp && xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			xml = xmlHttp.responseXML;

			var wrong = xml.getElementsByTagName('wrong');
			if (wrong.length > 0) {
				setNotice(emailnotice, true, "Возникли проблемы при отправке. Вероятно, проблемы "+
					"на нашей стороне. Наша служба поддержки уже читает письмо об этом, так что " +
					"вам не нужно ничего с этим делать. Если хотите, попробуйте еще раз запросить " +
					"прислать книгу по e-mail, вдруг это плавающий глюк");
			} else {
				setNotice(emailnotice, false, "Файл с книгой отправлен на ваш e-mail, который " +
					"вы использовали при регистрации. Спасибо за интерес к моему проекту!");
			}
		}
	}
