function roundTwo(num) {
	// Make a string 3 characters by adding zeros
	// or truncating
	function str3(x) {
		while (x.length < 3) {
			x += '0';
		}
		return x.substring(0, 3);
	}

	// Split number into integer and decimal bits
	var bits = (num + '').split('.');

	// Get the decimal part
	var frac = bits[1] || '';

	// Make the number all digits with no decimal place
	// as if had done num*1000 and truncated decimal places
	// Split into an array of single digits
	var digits = (bits[0] + str3(frac)).split('');

	// Round the second last digit up if the last digit
	// is 5 or greater
	var i = digits.length;
	if (digits[--i] > 4) { 
		digits[--i] = +digits[i] + 1;
	}

	// While the last number is 10, make it a zero and
	// carry 1 to left
	while (i && digits[i] > 9) {
		digits[i] = 0;
		digits[--i] = +digits[i] + 1;
	}

	// Make the digits a string again
	digits = digits.join('');

	// Put the decimal place back in and return a string
	// Leave off the last digit
	i = digits.length - 3;
	
	return digits.substring(0, i) + '.' + digits.substring(i, i + 2);
}

function number_Delimit(n, sSep) {
	//n = n.toString();
	n = roundTwo(n);
	
	var p1, p2, p3;
	var sSep = (sSep == null) ? ' ' : sSep;

	n = n.split('.');
	p1 = n[0];
	p2 = (n[1] == null) ? ',00' : ',' + n[1].substr(0, 2);
	p3 = '';

	for (var i = p1.length - 1; i >= 0; i--) {
		p3 += p1.charAt(p1.length - i - 1);
		if (i % 3 == 0 && i != 0) p3 += sSep;
	}

	return p3 + p2;
}

function callBack() {
	if ($F("name").strip() == "") {
		$("name").focus();
		return false;
	}
	if ($F("phone").strip() == "") {
		$("phone").focus();
		return false;
	}

	new Ajax.Request("/ajax/callback/", {
		parameters: {
			name: $F("name"),
			phone: $F("phone"),
			comments: $F("comments")
		},
		onSuccess: function(transport) {
			alert(transport.responseText);
		},
		onComplete: function() {
			$('callbackoverlay').hide();
			$('callback').hide();
		}
	});

	return false;
}

function addToBasket(aguid, adiscount) {

	new Ajax.Updater('basket', '/ajax/basket/?action=add', {
		method: 'post',
		parameters: {
			guid: aguid,
			tariff: '',
			discount: adiscount
		}
	});

	return false;
}

function addToBasketFromDesc(adiscount) {
	mguid = $('guid') ? $('guid').value : false;
	tguid = $('tariff') ? $('tariff').value : '';
	
	if (!mguid) return false;
	
	new Ajax.Updater('basket', '/ajax/basket/?action=add', {
		method: 'post',
		parameters: {
			guid: mguid,
			tariff: tguid,
			discount: adiscount
		}
	});
	
	return false;
}

function addToBasketWithCredit(cguid) {
	mguid = $('guid') ? $('guid').value : cguid;
	tguid = $('tariff') ? $('tariff').value : '';
	
	if (!mguid) return false;
	
	new Ajax.Updater('basket', '/ajax/basket/?action=add', {
		method: 'post',
		parameters: {
			guid: mguid,
			tariff: tguid
		},
		onSuccess: function(transport) {
			location.href = "/cabinet/basket/?credit=yes";
		}
	});
	
	return false;
}

function addToBasketFromCompare() {
	
}

function removeFromBasket(abid) {
	if (!abid) return false;

	new Ajax.Request('/ajax/basket/?action=remove', {
		method: 'post',
		parameters: {
			bid: abid
		},
		onSuccess: function(transport) {
			$(abid).remove();
			updateBasket();
		}
	});
	
	return false;
}

function chooseColor(aguid, photo, discount) {
	guid2 = $('guid');
	if (guid2) {
		if (guid2.value == aguid) return false;

		guid2.value = aguid;
		$('big_photo').src = '/images/' + photo;

		showPresence(aguid, discount);
	}

	return false;
}

/*function showPrice(aguid) {
	new Ajax.Updater('price', '/ajax/price/', {
		method: 'get',
		parameters: {
			guid: aguid
		}
	});
}*/

function showPresence(aguid, adiscount) {
	new Ajax.Updater('presence', '/ajax/salones/', {
		method: 'get',
		parameters: {
			action: 'presence',
			guid: aguid,
			discount: adiscount
		}
	});
	new Ajax.Updater('shipping', '/ajax/salones/', {
		method: 'get',
		parameters: {
			action: 'shipping',
			guid: aguid,
			discount: adiscount
		}
	});
}

function updateBasket() {
	abids = '';
	$$('.sum').each(function(item) {
		abids += (abids.length != 0 ? ',' : '') + item.id.substring(6) + ':' + item.value;
		if (item.value == 0) $(item.id.substring(6)).remove();
	});
	//alert(abids);
	new Ajax.Request('/ajax/basket/?action=update', {
		method: 'post',
		parameters: {
			bids: abids
		},
		onSuccess: function(transport) {
			$('rawprice').value = Number(transport.responseText);
			$('total_summ').innerHTML = Number(transport.responseText) + Number($('deliveryprice').value) + Number($('insuranceprice').value) + ' руб';
			recalcDelivery();
			//makeTotalPrice();
		}
	});
	
	return false;
}

function nodeText(parentnode, nodename) {
	node = parentnode.getElementsByTagName(nodename)[0];
	return (node.firstChild) ? node.firstChild.nodeValue : '';
}

function loginBasket() {
	new Ajax.Request('/ajax/login/', {
		method: 'post',
		parameters: {
			login: $('login').value,
			password: $('password').value
		},
		onSuccess: function(transport) {
			//alert(transport.responseText);
			var xml = transport.responseXML.documentElement;
			switch (xml.getAttribute('result')) {
				case 'ok': {
					$('loginblock').hide();
					$('regblock').hide();
					//alert((xml.getElementsByTagName('lastname')[0]).nodeValue);
					$('lastname'		).value = nodeText(xml, 'lastname'		);
					$('firstname'		).value	= nodeText(xml, 'firstname'		);
					$('secondname'		).value	= nodeText(xml, 'secondname'	);
					$('clientemail'		).value	= nodeText(xml, 'email'			);
					$('clientphone'		).value	= nodeText(xml, 'phone'			);
					$('birthday'		).value	= nodeText(xml, 'birthday'		);
					$('passport'		).value	= nodeText(xml, 'passport'		);
					$('passportissue'	).value	= nodeText(xml, 'passportissue'	);
					$('address'			).value	= nodeText(xml, 'address'		);
					break;
				}
				case 'error': {
					$('loginresult').innerHTML = '<span class="red">Такого пользователя не существует или указан неверный пароль.</span>';
					break;
				}
			}
		}
	});
	
	return false;
}

function addToCompareTable(aid) {
	new Ajax.Request('/ajax/compare/', {
		method: 'post',
		parameters: {
			action: 'add',
			id: aid
		},
		onSuccess: function() {
			window.open('/compare/', 'altcompare', 'toolbar=0, location=0, directories=0, status=0, menubar=0, scrollbars=1, resizable=1,width=820');
		}
	});
	
	return false;
}

function removeFromCompareTable(aid) {
	new Ajax.Request('/ajax/compare/', {
		method: 'post',
		parameters: {
			action: 'remove',
			id: aid
		},
		onSuccess: function() {
			window.location.reload();
		}
	});
	
	return false;
}

function showHidePhotoes(el) {
	if (photoes = $('photoes')) {
		if (photoes.visible()) {
			photoes.hide();
			el.innerHTML = 'Показать фото товаров';
		} else {
			photoes.show();
			el.innerHTML = 'Скрыть фото товаров';
		}
	}
}

function checkQuestionAnswer(questionId, answerText, resultDiv) {
	new Ajax.Request('/ajax/answer/', {
		method: 'post',
		parameters: {
			question: questionId,
			answer: answerText
		},
		onSuccess: function(transport) {
			resultDiv = $(resultDiv);
			for (i = 0; i < resultDiv.childCount; i++) {
				v = resultDiv.item(i);
				v.style.display = (i == transport.responseText) ? 'block' : 'none';
			}
		}
	});
	
	return response;
}

function addComment() {
	new Ajax.Request('/ajax/comments/?action=add', {
		method: 'post',
		parameters: {
			good: $('opinion_good').value,
			name: $('opinion_name').value,
			body: $('opinion_text').value
		},
		onSuccess: function(transport) {
			alert('Ваш отзыв отправлен. После подтверждения администратора он будет отображен на этой странице.');
			opinionnoactive();
			hideOpinion();
		}
	});
	return false;
}

function subscribeForNews() {
	var emailfield = $('emailforsubscribe');
	new Ajax.Request('/ajax/subscribe/', {
		method: 'post',
		parameters: {
			email: emailfield.value,
			action: 'subscribe'
		},
		onSuccess: function(transport) {
			if (subdiv = $('subscription')) {
				subdiv.innerHTML = transport.responseText;
			} else {
				alert(transport.responseText);
			}
		}
	});
	
	return false;
}

function subscribeForChanges() {
	var emailfield = $('email');
	var guidfield = $('guid');
	new Ajax.Request('/ajax/subscribe/', {
		method: 'post',
		parameters: {
			action: 'changes',
			guid: guidfield.value,
			email: emailfield.value
		},
		onSuccess: function(transport) {
			alert('Адрес ' + emailfield.value + ' подписан на уведомление о снижении цены на этот товар.');
		}
	});
	
	return false;
}

function getVendors() {
	new Ajax.Request('/ajax/uplink/', {
		method: 'get',
		parameters: {
			action: 'vendors',
			category: $('uplink-category').value
		},
		onSuccess: function(transport) {
			$('select_uplink-vendor').innerHTML = '<select id="uplink-vendor" name="vendor" onchange="getModels();">' + transport.responseText + '</select>';
		},
		onComplete: function() {
			getModels();
		}
	});
}

function getModels() {
	new Ajax.Request('/ajax/uplink/', {
		method: 'get',
		parameters: {
			action: 'models',
			category: $('uplink-category').value,
			vendor: $('uplink-vendor').value
		},
		onSuccess: function(transport) {
			$('select_uplink-model').innerHTML = '<select id="uplink-model" name="alias">' + transport.responseText + '</select>';
		}
	});
}

function showColor(agood, acolor) {
	new Ajax.Request('/ajax/photo/', {
		method: 'get',
		parameters: {
			action: 'showcolor',
			good: agood,
			color: acolor
		},
		onSuccess: function(transport) {
			if (img = $('big_photo')) {
				img.src = '/images/' + transport.responseText;
			}
		}
	});
}

function switchToComments(agood) {
	new Ajax.Request('/ajax/comments/', {
		method: 'get',
		parameters: {
			action: 'showcomments',
			good: agood
		},
		onSuccess: function(transport) {
			$('block_properties').style.display = 'none';
			$('block_comments').innerHTML = transport.responseText;
			$('block_comments').style.display = 'block';
		}
	});
	
	return false;
}

function switchToProperties() {
	// No AJAX here actually
	$('block_comments').style.display = 'none';
	$('block_properties').style.display = 'block';
	
	return false;
}

function checkLogin() {
	new Ajax.Updater('checkresult', '/ajax/registration/', {
		method: 'post',
		parameters: {
			newlogin: $('newlogin').value
		}
	});
}

function saveUser() {
	new Ajax.Request('/ajax/profile/', {
		method: 'post',
		parameters: {
			lastname: $('lastname').value,
			firstname: $('firstname').value,
			secondname: $('secondname').value,
			email: $('clientemail').value,
			phone: $('clientphone').value,
			birthday: $('birthday').value,
			passport: $('passport').value,
			passportissue: $('passportissue').value,
			address: $('address').value
		},
		onSuccess: function(transport) {
			
		}
	});
}

function getValue(input) {
//	if (!$(input)) alert(input);
	return ($(input)) ? $(input).value : null;
}

function makeOrder() {
	if (br = $('basketrows')) {
		n = br.getElementsByTagName('tr');
		if (n.length <= 7) {
			alert('Корзина пуста!');
			return false;
		}
	}

	apaytype = adelivery = '';
	
	if ($('pay_self').checked) {
		apaytype = 'self';
		adelivery = 'self';
	}
	if ($('pay_cash').checked) {
		apaytype = 'cash';
		adelivery = $('cash_type').value;
	}	
	if ($('pay_company').checked) {
		apaytype = 'company';
		adelivery = $('company_type').value;
	}
	if ($('pay_credit').checked) {
		apaytype = 'credit';
		adelivery = $('credit_type').value;
	}
	if ($('pay_region').checked) {
		apaytype = 'region';
		adelivery = 'region';
	}
	
	if (apaytype == '') {
		alert('Не выбран способ оплаты и доставки!');
		return false;
	}

	if ($('lastname').value.strip() == '' || 
		$('firstname').value.strip() == '' || 
		$('secondname').value.strip() == '' || 
		$('clientphone').value.strip() == '' || 
		$('clientemail').value.strip() == '') {
		alert('Не заполнены данные о пользователе');
		return false;
	}
	
	if (!isEmail($('clientemail').value)) {
		alert('Указан некорректный email.');
		$('clientemail').focus();
		return false;
	}

	/*if ($('pay_self').checked || $('pay_cash').checked) {
		if (Number($('rawprice').value) >= 8000) {
			if ($('birthday').value.strip() == '' || $('passport').value.strip() == '' || $('passportissue').value.strip() == '') {
				alert('При сумме заказа на сумму более 8000 рублей паспортные данные обязательны к заполнению.');
				if ($('passportissue').value.strip() == '') $('passportissue').focus();
				if ($('passport').value.strip() == '') $('passport').focus();
				if ($('birthday').value.strip() == '') $('birthday').focus();
				return false;
			}
		}
	}*/
	
	src = $('source');
	if (src) {
		if ($('regblock').visible() && src.value == '') {
			alert('Не заполнено поле "Откуда вы о нас узнали"');
			src.focus();
			return false;
		}
	}

	//alert($('additionalinfo').value);
	switch (apaytype) {
		case 'self':
			p = {
				lastname: getValue('lastname'),
				firstname: getValue('firstname'),
				secondname: getValue('secondname'),
				email: getValue('clientemail'),
				phone: getValue('clientphone'),
				birthday: getValue('birthday'),
				passport: getValue('passport'),
				passportissue: getValue('passportissue'),
				address: getValue('address'),
				additionalinfo: getValue('additionalinfo') ? getValue('additionalinfo') : null,
				source: getValue('source') ? getValue('source') : null,
				newlogin: getValue('newlogin') ? getValue('newlogin') : null,
				deliveryaddress: getValue('delivery_address'),
				deliverydate: getValue('delivery_date'),
				deliverytime: getValue('delivery_time'),
				paytype: apaytype,
				insuranceprice: getValue('insuranceprice')
			};
			break;
		case 'cash':
			p = {
				lastname: getValue('lastname'),
				firstname: getValue('firstname'),
				secondname: getValue('secondname'),
				email: getValue('clientemail'),
				phone: getValue('clientphone'),
				birthday: getValue('birthday'),
				passport: getValue('passport'),
				passportissue: getValue('passportissue'),
				address: getValue('address'),
				additionalinfo: getValue('additionalinfo') ? getValue('additionalinfo') : null,
				source: getValue('source') ? getValue('source') : null,
				newlogin: getValue('newlogin') ? getValue('newlogin') : null,
				deliveryaddress: getValue('delivery_address'),
				deliverydate: getValue('delivery_date'),
				deliverytime: getValue('delivery_time'),
				deliveryprice: getValue('deliveryprice'),
				paytype: apaytype,
				insuranceprice: getValue('insuranceprice'),
				d_type: getValue('cash_type'),
				d_location: getValue('cash_locations'),
				d_address: getValue('cash_delivery_address')
			};
			break;
		case 'company':
			p = {
				lastname: getValue('lastname'),
				firstname: getValue('firstname'),
				secondname: getValue('secondname'),
				email: getValue('clientemail'),
				phone: getValue('clientphone'),
				birthday: getValue('birthday'),
				passport: getValue('passport'),
				passportissue: getValue('passportissue'),
				address: getValue('address'),
				additionalinfo: getValue('additionalinfo') ? getValue('additionalinfo') : null,
				source: getValue('source') ? getValue('source') : null,
				newlogin: getValue('newlogin') ? getValue('newlogin') : null,
				deliveryaddress: getValue('delivery_address'),
				deliverydate: getValue('delivery_date'),
				deliverytime: getValue('delivery_time'),
				paytype: apaytype,
				deliveryprice: getValue('deliveryprice'),
				co_company: getValue('co_company'),
				co_regaddress: getValue('co_regaddress'),
				co_factaddress: getValue('co_factaddress'),
				co_boss: getValue('co_boss'),
				co_accounter: getValue('co_accounter'),
				co_inn: getValue('co_inn'),
				co_acc1: getValue('co_acc1'),
				co_acc2: getValue('co_acc2'),
				co_bank: getValue('co_bank'),
				co_bik: getValue('co_bik'),
				co_bankaddress: getValue('co_bankaddress'),
				co_phone: getValue('co_phone'),
				co_okpo: getValue('co_okpo'),
				co_kpp: getValue('co_kpp'),
				insuranceprice: getValue('insuranceprice'),
				d_type: getValue('company_type'),
				d_location: getValue('company_locations'),
				d_address: getValue('company_delivery_address')
			};
			break;
		case 'credit':
			p = {
				lastname: getValue('lastname'),
				firstname: getValue('firstname'),
				secondname: getValue('secondname'),
				email: getValue('clientemail'),
				phone: getValue('clientphone'),
				birthday: getValue('birthday'),
				passport: getValue('passport'),
				passportissue: getValue('passportissue'),
				address: getValue('address'),
				additionalinfo: getValue('additionalinfo') ? getValue('additionalinfo') : null,
				source: getValue('source') ? getValue('source') : null,
				newlogin: getValue('newlogin') ? getValue('newlogin') : null,
				deliveryaddress: getValue('delivery_address'),
				deliverydate: getValue('delivery_date'),
				deliverytime: getValue('delivery_time'),
				paytype: apaytype,
				deliveryprice: getValue('deliveryprice'),
				c_loantime: getValue('c_loantime'),
				c_fio: getValue('c_fio'),
				c_birthday: getValue('c_birthday'),
				c_birthplace: getValue('c_birthplace'),
				c_citizenship: getValue('c_citizenship'),
				c_citizenshipchanged: getValue('c_citizenshipchanged'),
				c_passport: getValue('c_passport'),
				c_ppissuer: getValue('c_ppissuer'),
				c_ppissued: getValue('c_ppissued'),
				c_secondid: getValue('c_secondid'),
				c_siserie: getValue('c_siserie'),
				c_sinumber: getValue('c_sinumber'),
				c_siissued: getValue('c_siissued'),
				c_siissuer: getValue('c_siissuer'),
				c_homephone: getValue('c_homephone'),
				c_mobilephone: getValue('c_mobilephone'),
				c_workphone: getValue('c_workphone'),
				c_email: getValue('c_email'),
				c_regregion: getValue('c_regregion'),
				c_regcity: getValue('c_regcity'),
				c_regstreet: getValue('c_regstreet'),
				c_reghouse: getValue('c_reghouse'),
				c_regflat: getValue('c_regflat'),
				c_regindex: getValue('c_regindex'),
				c_regdate: getValue('c_regdate'),
				c_family: getValue('c_family'),
				c_kids: getValue('c_kids'),
				c_income: getValue('c_income'),
				c_actregion: getValue('c_actregion'),
				c_actcity: getValue('c_actcity'),
				c_actstreet: getValue('c_actstreet'),
				c_acthouse: getValue('c_acthouse'),
				c_actflat: getValue('c_actflat'),
				c_actindex: getValue('c_actindex'),
				c_appowned: $('c_appowned').checked ? "Да" : "Нет",
				c_carowned: $('c_carowned').checked ? "Да" : "Нет",
				c_workname: getValue('c_workname'),
				c_workboss: getValue('c_workboss'),
				c_workcompanyphone: getValue('c_workcompanyphone'),
				c_workregion: getValue('c_workregion'),
				c_workcity: getValue('c_workcity'),
				c_workstreet: getValue('c_workstreet'),
				c_workhouse: getValue('c_workhouse'),
				c_workoffice: getValue('c_workoffice'),
				c_workindex: getValue('c_workindex'),
				c_worktype: getValue('c_worktype'),
				c_worktypetime: getValue('c_worktypetime'),
				c_workgeneraltype: getValue('c_workgeneraltype'),
				c_workposition: getValue('c_workposition'),
				c_worktime: getValue('c_worktime'),
				c_comments: getValue('c_comments'),
				insuranceprice: getValue('insuranceprice'),
				d_type: getValue('credit_type'),
				d_location: getValue('credit_locations'),
				d_address: getValue('credit_delivery_address')
			};
			break;
		case 'region':
			p = {
				lastname: getValue('lastname'),
				firstname: getValue('firstname'),
				secondname: getValue('secondname'),
				email: getValue('clientemail'),
				phone: getValue('clientphone'),
				birthday: getValue('birthday'),
				passport: getValue('passport'),
				passportissue: getValue('passportissue'),
				address: getValue('address'),
				additionalinfo: getValue('additionalinfo') ? getValue('additionalinfo') : null,
				source: getValue('source') ? getValue('source') : null,
				newlogin: getValue('newlogin') ? getValue('newlogin') : null,
				deliveryaddress: getValue('delivery_address'),
				deliverydate: getValue('delivery_date'),
				deliverytime: getValue('delivery_time'),
				paytype: apaytype,
				deliveryprice: getValue('deliveryprice'),
				insuranceprice: getValue('insuranceprice'),
				d_type: getValue('region_town'),
				d_location: getValue('region_town') + ' ' + getValue('region_index'),
				d_address: getValue('region_delivery_address')
			};
			break;
	}
	new Ajax.Request('/ajax/order/', {
		method: 'post',
		parameters: p,
		onSuccess: function(transport) {
			if (transport.responseText == '1') {
				window.location.href = '/cabinet/new-order/';
			} else
			alert(transport.responseText);
		}
	});
	
	return false;
}

function showJob(id) {
	new Ajax.Request('/ajax/job/', {
		method: 'get',
		parameters: {
			job: id
		},
		onSuccess: function(transport) {
			//alert(transport.responseText);
			var xml = transport.responseXML.documentElement;
			$('jobtitle').innerHTML = nodeText(xml, 'title');
			$('jobrequirements').innerHTML = nodeText(xml, 'requirements');
			$('jobduties').innerHTML = nodeText(xml, 'duties');
			$('jobconditions').innerHTML = nodeText(xml, 'conditions');
			$('jobphone').innerHTML = nodeText(xml, 'phone');
			$('jobemail').innerHTML = nodeText(xml, 'email');
			$('jobemail').href = 'mailto:' + nodeText(xml, 'email');
			$('vacancy_top').style.display = 'block';
			$('vacancytop_id').value = id;
			$('aposition').value = id;
		}
	});
	
	return false;
}

function getSubs() {
	new Ajax.Request('/ajax/salones/', {
		method: 'get',
		parameters: {
			action: 'options',
			region: $('region').value
		},
		onSuccess: function(transport) {
			//alert(transport.responseText);
			$('subsdiv').innerHTML = transport.responseText;
		}
	});
}

function recalcDelivery() {
	if ($('pay_self').checked) deliverySelf();
	if ($('pay_cash').checked) deliveryCash();
	if ($('pay_company').checked) deliveryCompany();
	if ($('pay_credit').checked) deliveryCredit();
	if ($('pay_region').checked) deliveryRegion();
	if (!$('pay_cash').checked && !$('pay_company').checked && !$('pay_credit').checked && !$('pay_region').checked) makeTotalPrice();
}

function showHidePay(selected) {
	if($('paydiv_cash')) $('paydiv_cash').setStyle({ display: (selected == 'cash') ? 'block' : 'none' });
	if($('paydiv_company')) $('paydiv_company').setStyle({ display: (selected == 'company') ? 'block' : 'none' });
	if($('paydiv_credit')) $('paydiv_credit').setStyle({ display: (selected == 'credit') ? 'block' : 'none' });
	if($('paydiv_region')) $('paydiv_region').setStyle({ display: (selected == 'region') ? 'block' : 'none' });
	
	switch (selected) {
		case 'self': {
			deliverySelf();
			break;
		}
		case 'cash': {
			deliveryCash();
			break;
		}
		case 'company': {
			deliveryCompany();
			break;
		}
		case 'credit': {
			deliveryCredit();
			break;
		}
		case 'region': {
			deliveryRegion();
		}
	}
}

function updatePrice() {
	if (select = $('tariff')) {
		//alert('tariff_' + select.value);
		name = 'tariff_' + select.value;
		price = $(name).value;
		$('finalprice').innerHTML = price;
	}
}

function brIf(str) {
	return (str != '') ? '<br/>' : '';
}

function makeTotalPrice() {
	selected = $('pay_self').checked ? 'self' : ($('pay_cash').checked ? 'cash' : ($('pay_company').checked ? 'company' : ($('pay_credit').checked ? 'credit' : ($('pay_region').checked ? 'region' : 'nufing'))));

	di = $('delivery_instance');
	ii = $('insurance_instance');
	tdd = di.getElementsByTagName('td');
	tdi = ii.getElementsByTagName('td');
	
	rp = $('rawprice');
	dp = $('deliveryprice');
	ip = 0;
	
	switch(selected) {
		case 'self': {
			$('insurance_instance').hide();
			$('delivery_instance').hide();
			break;
		}
		case 'cash': {
			$('insurance_instance').hide();
			tdd[1].innerHTML = '';
			if (Number($('rawprice').value) < 1000 && Number($('totalgoods').value) > Number($('tariffgoods').value)) tdd[1].innerHTML += 'Платная доставка для заказов на сумму менее 1000 руб';
			if ($('cash_type').value == 'outmkad') {
				tdd[1].innerHTML += brIf(tdd[1].innerHTML) + 'Платная доставка за пределы МКАД';
			}
			if ($('cash_type').value == 'mo') {
				tdd[1].innerHTML += brIf(tdd[1].innerHTML) + 'Платная доставка в Московскую область';
			}
			if (tdd[1].innerHTML == '') $('delivery_instance').hide();
			break;
		}
		case 'company': {
			$('insurance_instance').hide();
			if (Number(dp.value) > 0) $('delivery_instance').show(); else $('delivery_instance').hide();
			tdd[1].innerHTML = '';
			switch ($('company_type').value) {
				case 'inmkad': {
					if ($('rawprice').value < 1000) tdd[1].innerHTML += 'Платная доставка для заказов на сумму менее 1000 руб';
					break;
				}
				case 'outmkad': {
					if ($('rawprice').value < 1000) tdd[1].innerHTML += 'Платная доставка для заказов на сумму менее 1000 руб';
					tdd[1].innerHTML += brIf(tdd[1].innerHTML) + 'Платная доставка за пределы МКАД';
					break;
				}
				case 'mo': {
					if ($('rawprice').value < 1000) tdd[1].innerHTML += 'Платная доставка для заказов на сумму менее 1000 руб';
					tdd[1].innerHTML += brIf(tdd[1].innerHTML) + 'Платная доставка в Московскую область';
					break;
				}
				case 'region': {
					$('insurance_instance').show();
					ip = Number(rp.value) * 0.0025;
					tdi[3].innerHTML = number_Delimit(ip) + ' руб';
					tdd[1].innerHTML = 'Платная доставка в регионы РФ (за 1 кг)';
					break;
				}
			}
			if (tdd[1].innerHTML == '') $('delivery_instance').hide();
			break;
		}
		case 'credit': {
			$('insurance_instance').hide();
			tdd[1].innerHTML = '';
			if ($('rawprice').value < 1000) tdd[1].innerHTML += 'Платная доставка для заказов на сумму менее 1000 руб';
			if ($('credit_type').value == 'outmkad') {
				tdd[1].innerHTML += brIf(tdd[1].innerHTML) + 'Платная доставка за пределы МКАД';
			}
			if ($('credit_type').value == 'mo') {
				tdd[1].innerHTML += brIf(tdd[1].innerHTML) + 'Платная доставка в Московскую область';
			}
			if (tdd[1].innerHTML == '') $('delivery_instance').hide();
			break;
		}
		case 'region': {
			$('insurance_instance').show();
			tdd[1].innerHTML = 'Платная доставка в регионы РФ (за 1 кг)';
			ip = Number(rp.value) * 0.0025;
			tdi[3].innerHTML = number_Delimit(ip) + ' руб';
			break;
		}
	}

	if (Number(dp.value) > 0) $('delivery_instance').show(); else $('delivery_instance').hide();
	tdd[3].innerHTML = number_Delimit(dp.value) + ' руб';
	$('insuranceprice').value = ip;
	$('total_summ').innerHTML = number_Delimit(Number(rp.value) + Number(dp.value) + Number(ip)) + ' руб';
	//alert(dp.value);
	
	$('passportreq').setStyle({display: ((selected == 'pay_self' || selected == 'pay_cash') && rp.value >= 8000) ? 'inline' : 'none'});
}

function getMetros(select) {
	try {
		new Ajax.Request('/ajax/location/', {
			method: 'get',
			parameters: {
				type: '5',
				parent: '1'
			},
			onSuccess: function(transport) {
				$('select_' + select).innerHTML = '<select id="' + select + '">' + transport.responseText + '</select>';
			}
		});
	} catch (err) {
		alert("Error in getMetros()");
	}
}

/*function getRegions() {
	new Ajax.Updater('regionselect', '/ajax/location/', {
		method: 'get',
		parameters: {
			type: '3'
		}
	})
}*/

function getCities(mo, select) {
	//alert(select);
	click = '';
	if (select == 'region_town') click = 'deliveryRegion';
	if (select == 'company_locations') click = 'companyLocation';
	
	try {
		if (mo) {
			new Ajax.Request('/ajax/location/', {
				method: 'get',
				parameters: {
					type: '4',
					parent: '2'
				},
				onSuccess: function(transport) {
					html = '<select id="' + select + '"' + (click != '' ? ' onclick="' + click + '();"' : '') + '>' + transport.responseText + '</select>';
					$('select_' + select).innerHTML = html;
				}
			});
		} else {
			new Ajax.Request('/ajax/location/', {
				method: 'get',
				parameters: {
					type: '4',
					parent: '0'
				},
				onSuccess: function(transport) {
					html = '<select id="' + select + '" onclick="' + click + '();">' + transport.responseText + '</select>';
					$('select_' + select).innerHTML = html;
					//alert(html);
				},
				onComplete: function() {
					if (select == 'company_locations') {
						companyLocation();
					}
				}
			});
		}
	} catch (err) {
		alert("Error in getCities()");
	}
}

function getDeliveryPrice(locationid) {
	new Ajax.Request('/ajax/location/', {
		method: 'get',
		parameters: {
			price: 'yes',
			location: locationid
		},
		onSuccess: function(transport) {
			$('deliveryprice').value = transport.responseText;
			makeTotalPrice();
		}
	});
}

function deliverySelf() {
	$('deliveryprice').value = 0;
	makeTotalPrice();
}

function deliveryCash() {
	type = $('cash_type').value;
	
	var dp = 0;
	if (Number($('rawprice').value) < 1000 && Number($('totalgoods').value) > Number($('tariffgoods').value)) dp += Number($('minprice').value);
	
	switch (type) {
		case "inmkad": {
			$('cash_loctitle').innerHTML = 'Ближайшая станция метро:';
			getMetros('cash_locations');
			break;
		}
		case "outmkad": {
			$('cash_loctitle').innerHTML = 'Ближайшая станция метро:';
			dp += Number($('mkadprice').value);
			getMetros('cash_locations');
			break;
		}
		case "mo": {
			$('cash_loctitle').innerHTML = 'Город:';
			dp += Number($('moprice').value);
			getCities(true, 'cash_locations');
			break;
		}
	}
	$('deliveryprice').value = dp;
	//alert('Cash: ' + dp);
	makeTotalPrice();
}

function deliveryCredit(type) {
	type = $('credit_type').value;
	
	var dp = 0;
	if ($('rawprice').value < 1000) dp += Number($('minprice').value);
	
	switch (type) {
		case "inmkad": {
			$('credit_loctitle').innerHTML = 'Ближайшая станция метро:';
			getMetros('credit_locations');
			break;
		}
		case "outmkad": {
			$('credit_loctitle').innerHTML = 'Ближайшая станция метро:';
			dp += Number($('mkadprice').value);
			getMetros('credit_locations');
			break;
		}
		case "mo": {
			$('credit_loctitle').innerHTML = 'Город:';
			dp += Number($('moprice').value);
			getCities(true, 'credit_locations');
			break;
		}
	}
	//alert('Credit: ' + dp);
	$('deliveryprice').value = dp;
	makeTotalPrice();
}

function deliveryCompany() {
	type = $('company_type').value;
	
	var dp = 0;
	if ((type == 'inmkad' || type == 'outmkad' || type == 'mo') && ($('rawprice').value < 1000)) dp += Number($('minprice').value);
	
	switch (type) {
		case 'inmkad': {
			$('company_loctitle').innerHTML = 'Ближайшая станция метро:';
			getMetros('company_locations');
			$('deliveryprice').value = dp;
			makeTotalPrice();
			break;
		}
		case 'outmkad': {
			$('company_loctitle').innerHTML = 'Ближайшая станция метро:';
			dp += Number($('mkadprice').value);
			getMetros('company_locations');
			$('deliveryprice').value = dp;
			makeTotalPrice();
			break;
		}
		case 'mo': {
			$('company_loctitle').innerHTML = 'Город:';
			dp += Number($('moprice').value);
			getCities(true, 'company_locations');
			$('deliveryprice').value = dp;
			makeTotalPrice();
			break;
		}
		case 'region': {
			$('company_loctitle').innerHTML = 'Город:';
			getCities(false, 'company_locations');
			break;
		}
	}
	//alert('Company: ' + dp);
}

function deliveryRegion() {
	acity = $('region_town').value;
	new Ajax.Request('/ajax/location/', {
		method: 'get',
		parameters: {
			price: 'yes',
			city: acity
		},
		onSuccess: function(transport) {
			//alert(transport.responseText);
			$('deliveryprice').value = transport.responseText;
			//alert('Region: ' + $('deliveryprice').value);
			makeTotalPrice();
		}
	});
}

function companyLocation() {
	//alert($('company_type').value);
	try {
		if ($('company_type').value == 'region') {
			new Ajax.Request('/ajax/location/', {
				method: 'get',
				parameters: {
					price: 'yes',
					city: $('company_locations').value
				},
				onSuccess: function(transport) {
					//alert(transport.responseText);
					$('deliveryprice').value = transport.responseText;
					makeTotalPrice();
				}
			});
		}
	} catch (err) {
		alert("Error in companyLocations();");
	}
}

function unsubscribeNews(aemail, aoffkey) {
	new Ajax.Request('/ajax/subscribe/', {
		method: 'post',
		parameters: {
			action: 'unsub_news',
			email: aemail,
			offkey: aoffkey
		},
		onSuccess: function(transport) {
			if (transport.responseText == '1') {
				$('unsub_news').hide();
			} else {
				alert(transport.responseText);
			}
		}
	});
	
	return false;
}

function unsubscribeChange(aid) {
	new Ajax.Request('/ajax/subscribe/', {
		method: 'post',
		parameters: {
			action: 'unsub_change',
			id: aid
		},
		onSuccess: function(transport) {
			if (transport.responseText == '1') {
				$('unsub_change_' + aid).hide();
			} else {
				alert(transport.responseText);
			}
		}
	});
	
	return false;
}

function sendResume() {
	if ($('filephoto').value == '') {
		alert('Не указан файл с фотографией!');
		$('filephoto').focus();
		return false;
	}
	if ($('fileresume').value == '') {
		alert('Не указан файл с резюме!');
		$('fileresume').focus();
		return false;
	}
	closeres();
	$('fileform').submit();
}

function ajaxGetGoods(guid) {
	acategory = $('catdiv2');
	if (!acategory || acategory.value == '') return false;
	
	new Ajax.Request('/ajax/salones/', {
		method: 'get',
		parameters: {
			action: 'goods',
			category: acategory.value,
			defaultguid: guid
		},
		onSuccess: function(transport) {
			$('subs2div').innerHTML = transport.responseText;
			//alert(transport.responseText);
		}
	});
}

function reviewNotify(form) {
	if ($(form).fio.value.strip() == "") {
		form.fio.focus();
		return false;
	}
	
	if (!isEmail($(form).email.value)) {
		form.email.focus();
		return false;
	}
	
	new Ajax.Request('/ajax/preorder/', {
		method: "post",
		parameters: {
			reviewid: form.reviewid.value,
			review: form.review.value,
			email: form.email.value,
			fio: form.fio.value,
			phone: form.phone.value,
			comments: form.comments.value
		},
		onSuccess: function(transport) {
			$(form).up().hide();
		}
	});

	return false;
}

function selectionCategoryChange(select) {
	if (select.selectedIndex == 0) return false;
	
	select.form.action = select.options[select.selectedIndex].title + 'selection/';
	
	$("selection-submit").hide();
	
	new Ajax.Updater('selection-parameters', '/ajax/selection/', {
		method: 'post',
		parameters: {
			category: select.options[select.selectedIndex].value
		},
		onSuccess: function(transport) {
			$("selection-submit").show();
		}
	});
	return true;
}