function PXAjax(url, onfunction, options, cache, method, onOptions) {
	var req = new Subsys_JsHttpRequest_Js();

	req.onreadystatechange = function() {
		if(req.readyState === 4) {
			if (typeof onfunction.call == 'undefined') {
				/* for IE 5.01 */
				req.responseJS.$call = onfunction;
				req.responseJS.$call(req, onOptions);
			} else {
				onfunction.call(req.responseJS, req, onOptions);
			}
		}
	};

	var cache  = (typeof cache != 'undefined') ? cache  : true;
	var method = (typeof method != 'undefined') ? method : 'post';

	req.caching = cache;
	req.open(method, url, true);
	req.send(options);
}

function SumCalcPrice(addpacks) {
	var calc = document.getElementById('calc');
	var x = parseFloat(calc.getAttribute('calc'));

	for(var i=0; i< addpacks.length;i++) {
		var t = addpacks[i];
		if (t.checked) {
			x += parseFloat(t.getAttribute('calc'));
		}
	}
	calc.value = x;
}

if ('undefined' == typeof String.prototype.trim) {
	String.prototype.trim = function() {
		return this.replace(/^\s+/, '').replace(/\s+$/, '');
	}
}

function SuggestAddress(street, house) {
	(function () { /* init */
		var container = document.createElement('div');
		container.style.position = 'relative';
		container.style.margin = '0 0 0 2px';
		var div = document.createElement('div');
		div.className = 'eSuggest';
		div.$str = '';
		div.afterclick = function() {
			street.onblur();
			house.focus();
		}
		div.afterblur = function() {
			if (!this.$cur) {
				var str = this.$input.value.trim().toLowerCase();
				for (var s in this.$list) {
					if (s.toLowerCase() == str) {
						this.$cur = this.$list[s];
					}
				}
			}
			if (this.$cur) {
				this.$input.value = this.$cur.value;
				house.$div.$list = this.$houses[this.$cur.value];
				house.value = '';
			} else {
				house.$div.$list = {};
			}
			house.$div.$str = '~~~buildme~~~';
		}
		street.$div = div;
		div.$input = street;
		container.appendChild(div);
		street.parentNode.insertBefore(container, street.nextSibling);

		container = document.createElement('div');
		container.style.position = 'relative';
		container.style.margin = '0 0 0 2px';
		div = document.createElement('div');
		div.className = 'eSuggest';
		div.$str = '';
		div.afterclick = function() {
			Debug('ac');
			this.$input.onblur();
//			this.$input.form.submit();
		}
		div.afterblur = function() {
			Debug('abl');
			if (this.$cur) {
				this.$input.value = this.$cur.value;
			}
		}
		house.$div = div;
		div.$input = house;
		container.appendChild(div);
		house.parentNode.insertBefore(container, house.nextSibling);

		street.$div.buildList = house.$div.buildList = function() {
			var str = this.$input.value.trim().toLowerCase();
			if (str == this.$str) return;
			this.$str = str;
			Debug('Build: ' + this.$input.name)
			while(this.firstChild) {
				this.removeChild(this.firstChild);
			}
			if ((str == '') && (this.$houses)) {
				return;
			}
			this.$cur = null;
			for (var s in this.$list) {
				if (s.toLowerCase().indexOf(str) == 0) {
					this.appendChild(this.$list[s]);
					if (this.$list[s].className != '') {
						this.$cur = this.$list[s];
					}
				}
			}
		}

		street.$div.showList = house.$div.showList = function (show) {
			if(typeof show == 'undefined') {
				show = true;
			}
			this.style.display = (show && this.firstChild) ? 'block' : '';
			if (this.style.display == '') return;
			if (this.$cur) {
				var fco = this.firstChild.offsetTop;
				if (this.offsetHeight + this.scrollTop < this.$cur.offsetTop + this.$cur.offsetHeight - fco) {
					this.scrollTop = this.$cur.offsetTop + this.$cur.offsetHeight - this.offsetHeight - fco + 2;
				}
				if (this.scrollTop > this.$cur.offsetTop - fco) {
					this.scrollTop = this.$cur.offsetTop - fco;
				}
			} else {
				this.scrollTop = 0;
			}
		}

		street.$div.onmousedown = house.$div.onmousedown = function(e) {
			Debug('MouseDown');
			try {
				e.preventDefault();
			} catch(err) {
				this.$input.preventHide = true;
			}
		}
		street.$div.onmouseover = house.$div.onmouseover = function(e) {
			e = e || event;
			var target = e.target || e.srcElement;
			if (target.tagName.toLowerCase() == 'a') {
				if (this.$cur) {
					this.$cur.className = '';
				}
				target.className = 'current';
				this.$cur = target;
			}
		}
		street.$div.onclick = house.$div.onclick = function(e) {
			e = e || event;
			var target = e.target || e.srcElement;
			if (target.tagName.toLowerCase() == 'a') {
				if (this.$cur) {
					this.$cur.className = '';
				}
				target.className = 'current';
				this.$cur = target;
				this.$input.preventHide = false;
				this.afterclick();
				try {
					e.preventDefault();
				} catch (err) {
					e.returnValue = false;
				}
			}
		}
		street.$div.ondragstart = house.$div.ondragstart = function() {return false}
	})();

	function Debug(s) {
	/*
		document.getElementById('debug').innerHTML += s + '<br>';
		document.getElementById('debug').scrollTop = 10000;
	*/
	}

	street.onfocus = house.onfocus = function (e) {
		Debug('focus: ' + this.name);
		this.$div.buildList();
		this.$div.showList();
	}

	street.onblur = house.onblur = function (e) {
		Debug('blur: ' + this.name)
		if ((typeof this.preventHide != 'undefined') && this.preventHide) {
			Debug('blur: prevent hide')
			this.preventHide = false;
		} else {
			Debug('blur: hide')
			this.$div.showList(false);
			this.$div.afterblur();
		}
	}

	var onKeyDown = function(e) {
		var key = (e || event).keyCode;
		var next = null;
		switch (key) {
			case 38:
				next = (this.$div.$cur) ? this.$div.$cur.previousSibling : this.$div.lastChild;
				break;
			case 40:
				next = (this.$div.$cur) ? this.$div.$cur.nextSibling : this.$div.firstChild;
				break;
			case 13:
				this.$div.afterclick();
				try {
					e.preventDefault();
				} catch (err) {
					event.returnValue = false;
				}
				return false;
			case 27:
				break;
			default:
				return true;
		}
		if (this.$div.$cur) {
			this.$div.$cur.className = '';
		}
		this.$div.$cur = next;
		if (next) {
			next.className = 'current';
		}
		this.$div.showList();
		try {
			e.preventDefault();
		} catch (err) {
			event.returnValue = false;
		}
	}
	if (document.all && !window.opera) {
		street.onkeydown = house.onkeydown = onKeyDown;
	} else {
		street.onkeypress = house.onkeypress = onKeyDown;
	}

	street.onkeyup = function (e) {
//		var c = this.value.trim().substr(0, 3).toLowerCase();
		var c = this.value.trim().toLowerCase();

//		if ((c.length > 2) && (this.$div.$letter != c)) {
		if ((c.length > 0) && (this.$div.$letter != c)) {

			new PXAjax('/eshop.json', SaveResponse, {letter: c}, true, 'get', c);
			return;
		}
		this.$div.buildList();
		this.$div.showList();
	}

	house.onkeyup = function (e) {
		this.$div.buildList();
		this.$div.showList();
	}

	var SaveResponse = function (req, letter) {
		if (street.value.trim().substr(0, 3).toLowerCase() != letter) return;
		var streets = {};
		var houses  = {};
		if (typeof this.streets === 'object') {
			for (var s in this.streets) {
				streets[s] = {};
				var curstr = this.streets[s];
				var link = document.createElement('a');
				link.value = s;
				link.href = '#' + s;
				link.appendChild(document.createTextNode(s));
				streets[s] = link;
				houses[s] = {};
				for (var i = 0; i < curstr.length; i++) {
					var link = document.createElement('a');
					link.value = curstr[i];
					link.href = '#' + curstr[i];
					link.appendChild(document.createTextNode(curstr[i]));
					houses[s][curstr[i]] = link;
				}
			}
		}
		street.$div.$letter = letter;
		street.$div.$list = streets;
		street.$div.$houses = houses;

		street.$div.buildList();
		street.$div.showList();
	}
}


// Саггест
var street = document.getElementById('streetInput');
var house  = document.getElementById('houseInput');

if(street && house) {
	SuggestAddress(street, house);
}

var streetCh = document.getElementById('streetInputCh');
var houseCh  = document.getElementById('houseInputCh');

if(streetCh && houseCh) {
	SuggestAddress(streetCh, houseCh);
}


// Кпопка назад
var back = document.getElementById('backButton');
if(back !== null) {
	back.onclick = function() {
		window.history.back();
		return false;
	}
}

// Выбор дополнительных пакетов
var addpacks = document.getElementsByName('addpacket[]');
if(addpacks.length) {
	if (addpacks[0].form.DEPS) {
		for (var elId in addpacks[0].form.DEPS) {
			var dep = addpacks[0].form.DEPS[elId];
			for(var i = 0; i < dep.b.length; i++) {
				dep.b[i] = document.getElementById('packet' + dep.b[i]);
			}
			if (dep.c) {
				for(var i = 0; i < dep.c.length; i++) {
					dep.c[i] = document.getElementById('packet' + dep.c[i]);
				}
			}
			document.getElementById('packet' + elId).DEPS = dep;
		}
	}
	addpacks[0].form.onclick = function(e) {
		e = e || event;
		var t = e.target || e.srcElement;
		if (t.tagName.toLowerCase() != 'input' || t.name != 'addpacket[]') return true;
		if (this.DEPS) {
			for(var i = 0; i < addpacks.length; i++) {
				if (!addpacks[i].DEPS) continue;
				if (addpacks[i].checked) continue;
				if (!addpacks[i].DEPS.c) continue;
				var flag = true;
				var text = [];
				for (var j = 0; j < addpacks[i].DEPS.c.length; j++) {
					flag = flag && addpacks[i].DEPS.c[j].checked;
					text[j] = " \xAB" + addpacks[i].DEPS.c[j].parentNode.nextSibling.getElementsByTagName('label')[0].innerHTML + "\xBB";
				}
				if (flag) {
					text = 'Выбранные пакеты' + text + ' входят в пакет \xAB' + addpacks[i].parentNode.nextSibling.getElementsByTagName('label')[0].innerHTML + '\xBB стоимость которого меньше суммы этих пакетов. Рекомендуем выбрать его.';
					if (window.confirm(text)) {
						addpacks[i].checked = true;
					}
					break;
				}
			}
			for(var i = 0; i < addpacks.length; i++) {
				addpacks[i].disabled = false;
				addpacks[i].parentNode.nextSibling.removeAttribute('disabled');
			}
			for(var i = 0; i < addpacks.length; i++) {
				if (!addpacks[i].DEPS) continue;
				if (!addpacks[i].checked) continue;
				for (var j = 0; j < addpacks[i].DEPS.b.length; j++) {
					addpacks[i].DEPS.b[j].disabled = true;
					addpacks[i].DEPS.b[j].checked = false;
					addpacks[i].DEPS.b[j].parentNode.nextSibling.setAttribute('disabled', 'disabled');
				}
			}
		}
		SumCalcPrice(addpacks);
	}
	addpacks[0].form.onclick({target:{tagName:'input',name:'addpacket[]'}});
}


$('form#eTariffs').each(function(){
	var form = this;

	$('input[type=radio]', this).click(function() {
		if (this.name == 'tariff' || this.name == 'tariff[tv]') {
			$('#additional').each(function() {
				if (this.$no) {
					return;
				}
				
				this.disabled = false;
				this.src = '/i/eshop/choose_tv.gif';
			});
		}
	});
	
	$('label', this).each(function() {
		if (!/^type\d$/.test(this.htmlFor)) {
			return;
		}

		$('img', this).click(function() {
			this.parentNode.click();
		});
	});

	$('input[type=radio][name=type]', this).click(function(a) {
		var input = this;

		var myParent = $(this).parents('.cornered')[0];

		if (myParent.className == 'sel' && a !== 'init$') {
			return;
		}

		$('#additional').each(function(){
			this.disabled = true;
			this.src = '/i/eshop/choose_tv_disabled.gif';
			this.$no = (input.id === 'type2' || input.id === 'type5') ? true : false;
		});

		$('div.cornered', form).each(function() {
			if(this == myParent) {
				$(this).addClass('sel');
			} else {
				$(this).removeClass('sel');
			}
		});

		var my_first_tariff = $('input', myParent)[0];
		if (my_first_tariff) {
			for(i=0; i < this.form.tariff.length;i++) {
				var t = this.form.tariff[i];

				if (a === 'init$' && t.checked) {
					t.onclick();
				} else {
					t.checked = false;
				}

				t.setAttribute('min', (t == my_first_tariff) ? 1 : 0);
			}
		}

	}).each(function() {
		if (this.checked) {
			this.click('init$');
		}
	});
	
	//Для юр. лиц
	$('input[type=checkbox][name=type]', this).click(function(a) {
		var input = this;

		var myParent = $(this).parents('.cornered')[0];

		if (myParent.className == 'sel' && a !== 'init$') {
			return;
		}
		
		if (this.checked) {
			$('div.cornered', form).each(function() {
				if(this == myParent) {
					$(this).addClass('sel');
				}
			});
		}
		else {
			$('div.cornered', form).each(function() {
				if(this == myParent) {
					$(this).removeClass('sel');
				} 
			});
		}

		var my_first_tariff = $('input', myParent)[0];
		if (my_first_tariff) {
			for(i=0; i < this.form.elements.length;i++) {
				if (this.form.elements[i].type == 'radio') {
					var t = this.form.elements[i];
					var mySel = $(t).parents('.sel')[0];
					if (t.checked && !mySel) { 
						t.checked = false;
					}
				}
			}
		}

	}).each(function() {
		if (this.checked) {
			this.click('init$');
		}
	});

});


/*
// Выбор тарифов
var types = document.getElementsByName('type');
if((types !== null) && (types.length > 0)) {


		}
	}
}
*/