var Address = {

	loaders: {},

	ChangeCountry: function(country, city) {

		if ( typeof(country) == 'string' )
			country = '#'+country;

		if ( typeof(city) == 'string' )
			city = '#'+city;

		var country = $(country);
		var city = $(city);
		var code = country.val();

		city.attr('disabled', true).show();
		city.get(0).options[0].selected = true;
		if ( !city.get(0).options[0]._text )
			city.get(0).options[0]._text = city.get(0).options[0].text;
		city.get(0).options[0].text = 'Сначала выберите страну';

		city.change();
		this.StopLoading(city);
		if ( code <= 0 ) {

			if ( code == -1 )
				this._getCountryList(country);

			return ;
		}

		this._getCityList(code, city);
	},

	_getCountryList: function(country) {

		var Progress = this.Progress(country);

		country.hide();

		this.loaders[country.attr('id')] = $.ajax({
            type: 'POST',
            url: '/service/source/db.address',
            data: {
				type: 'country_list'
			},
            dataType: 'json',
            error: function() {
				country.show();
				Progress.remove();
			},
            success: function(json) {

				country.each(function() {
					this.selectedIndex = 0;
					if ( json.list && json.list.length ) {

						this.options.length = 1;
						for (var i in json.list)
							this.options[this.options.length] = new Option(
								json.list[i].Name,
								json.list[i].Code,
								false, false);
					}
				});
				country.show();
				Progress.remove();
			}
        });
	},

	ChangeCity: function(country, city, region, street, house) {

		if ( typeof(country) == 'string' )
			country = '#'+country;

		if ( typeof(city) == 'string' )
			city = '#'+city;

		if ( typeof(region) == 'string' )
			region = '#'+region;

		if ( typeof(street) == 'string' )
			street = '#'+street;

		if ( typeof(house) == 'string' )
			house = '#'+house;

		var country = $(country);
		var city = $(city);
		var code = {country: country.val(), city: city.val()};
		var region = (undefined === region ? region : $(region));
		var street = (undefined === street ? street : $(street));
		var house = (undefined === house ? house : $(house));

		if ( region !== undefined ) {
			region.attr('disabled', true).show();
			region.get(0).options[0].selected = true;
			if ( !region.get(0).options[0]._text )
				region.get(0).options[0]._text = region.get(0).options[0].text;
			region.get(0).options[0].text = 'Сначала выберите город';
			this.StopLoading(region);
		}

		if ( street !== undefined ) {
			street.attr('disabled', true).show();
			street.get(0).options[0].selected = true;
			if ( !street.get(0).options[0]._text )
				street.get(0).options[0]._text = street.get(0).options[0].text;
			street.get(0).options[0].text = 'Сначала выберите город';
			
			$('#'+street.attr('id')+'_suggest').remove();
			
			street.change();
			this.StopLoading(street);
		}
		
		$('#'+city.attr('id')+'_suggest').remove();		
		if ( code.city <= 0 ) {
			if ( code.city == -1 )
				this._showCitySuggest(code.country, city);

			return ;
		}

		if ( region !== undefined )
			this._getRegionList(code.city, region);
		
		if ( street !== undefined )
			this._getStreetList(code.city, street, house);
	},

	ChangeStreet: function(city, street, house) {
		if ( typeof(city) == 'string' )
			city = '#'+city;

		if ( typeof(street) == 'string' )
			street = '#'+street;

		if ( typeof(house) == 'string' )
			house = '#'+house;

		var house = $(house);
		var street = $(street);
		var city = $(city);

		house.attr('disabled', true).show();
		house.get(0).options[0].selected = true;
		if ( !house.get(0).options[0]._text )
			house.get(0).options[0]._text = house.get(0).options[0].text;
		house.get(0).options[0].text = 'Сначала выберите улицу';

		if ( street.is(":visible") )
			$('#'+street.attr('id')+'_suggest').remove();
		$('#'+house.attr('id')+'_suggest').remove();

		if ( $('#addr_house_simple').size() )
			$('#addr_house_simple').hide();

			
	/*	$('#'+street.attr('id')+'h').remove()
		$('<input type="hidden" />').attr({
			id: street.attr('id')+'h',
			name: street.attr('name'),
			value: street.val(),
		}).insertAfter(street);*/
			
		if ( street.val() <= 0 ) {
			if ( street.val() == -2 )
				this._showStreetSuggest(city.val(), street);

			return ;
		}

		this._showHouseSuggest(street.val(), house);
	},

	_showCitySuggest: function(code, el) {

		el = $(el);
		var citySuggest = $('<input type="text"/>').attr({
			value: ''
		}).css({
			width: el.css('width') ? el.css('width') : el.width(),
			display: 'block'
		});

		var self = this;
		citySuggest.autocomplete("/service/source/db.address", {
			extraParams: {
				type: 'city_list',
				code: code
			},
			dataType: 'json',
			parse: function(json) {
				var parsed = [];

				if ( !json.list || !json.list.length )
					return parsed;

				for (var i in json.list) {
					/*var Desc = '';
					if ( json.list[i].Desc && json.list[i].Desc.length ) {
						Desc = '<div class="ac_describe">';
						for (var j in json.list[i].Desc)
							Desc += json.list[i].Desc[j] + '<br />';
						Desc += '</div>';
					}*/

					/*parsed[parsed.length] = {
						data: json.list[i].FullName + Desc,
						value: json.list[i].Code,
						result: json.list[i].Name
					};*/
					parsed[parsed.length] = {
						data: json.list[i].FullName,
						value: json.list[i]/*.Code*/,
						result: json.list[i].Name
					};
				}
				return parsed;
			},
			formatItem: function(text, i, max, value) {
				//return text;
				var Desc = '';
				if ( value.Desc && value.Desc.length ) {
					Desc = '<div class="ac_describe">';
					for (var j in value.Desc)
						Desc += value.Desc[j] + '<br />';
					Desc += '</div>';
				}
				return value.FullName + Desc;
			},
			blurClear: true,
			returnFocus: false,
			max: 20
		}).result(function(event, Name, value/*Code*/) {
			el.each(function() {

				var Code = value.Code;
				var inList = false;
				for (var i=0;i<this.options.length;i++) {

					if ( this.options[i].value != Code )
						continue ;

					inList = true;
					this.options[i].selected = true;
					break ;
				}

				if ( inList == false ) {
					var option = $('<option />').attr({
							value: Code
					}).html(Name.replace(/<.*>/, ''));

					$(this.options[this.options.length-1]).before(option);
					this.options[this.options.length-2].selected = true;
				}
			});

			el.change();
		});

		$('<span></span>').attr({
			id: el.attr('id')+'_suggest'
		}).append(citySuggest).insertAfter(el);
	},

	_showHouseSuggest: function(code, el) {
		if ( $('#addr_house_simple').size() ) {
			$('#'+$(el).attr('id')+'_cont').get(0).style.display = '';
			$('#addr_house_simple').show();
		}

		$(el).hide();

		/*$('<input type="text"/>').attr({
			name: el.attr('name')+'_index',
			maxlength: 2,
			value: ''
		}).css({
			width: 23
		}).insertAfter(el);

		$('<span />').html('<br />Пример: 37, 29-Б').insertAfter(el);
		$('<span />').html(' - ').insertAfter(el);

		var houseSuggest = $('<input type="text"/>').attr({
			id: el.attr('id')+'_suggest',
			name: el.attr('name'),
			maxlength: 8,
			value: ''
		}).css({
		//	width: el.css('width') ? el.css('width') : el.width()
		}).insertAfter(el);
		el = $(el).hide();

		/*var self = this;
		houseSuggest.autocomplete("/service/source/db.address", {
			extraParams: {
				type: 'house_list',
				code: code
			},
			dataType: 'json',
			parse: function(json) {
				var parsed = [];

				if ( !json.list || !json.list.length )
					return parsed;

				for (var i in json.list)
					parsed[parsed.length] = {
						data: json.list[i].Name,
						value: json.list[i].Code,
						result: json.list[i].Name
					};

				return parsed;
			},
			formatItem: function(text, i, max, value) {
				return text;
			},
			blurClear: true,
			cacheLength: -1,
			max: 20
		}).result(
			function(event, Name, Code) {

				el.each(function() {

					var inList = false;
					for (var i=0;i<this.options.length;i++) {

						if ( this.options[i].value != Code )
							continue ;

						inList = true;
						this.options[i].selected = true;
						break ;
					}

					if ( inList == false ) {
						this.options[this.options.length] = new Option(
								Name, Code, false, false);

						this.options[this.options.length-1].selected = true;
					}
				});

				houseSuggest.unautocomplete();
				houseSuggest.bind("keyup", {Name: Name}, function(event) {
					var curName = this.value;
					if ( Name == curName)
						return ;

					$(this).remove();

					var visible = el.is(":visible");

					el.show();
					var houseSuggest = self._showHouseSuggest(code, el);
					if ( !visible )
						el.hide();

					houseSuggest.val(curName).focus();
					if ( $.browser.opera )
						houseSuggest.keypress();
					else
						houseSuggest.keydown();
				});
			}
		);

		houseSuggest.insertAfter(el);*/
	},

	_showStreetSuggest: function(code, el) {

		el = $(el);
		var streeSuggest = $('<input type="text"/>').attr({
			id: el.attr('id')+'_suggest',
			value: ''
		}).css({
			width: el.css('width') ? el.css('width') : el.width()
		});

		var self = this;
		streeSuggest.autocomplete("/service/source/db.address", {
			extraParams: {
				type: 'street_list',
				code: code
			},
			dataType: 'json',
			parse: function(json) {
				var parsed = [];

				if ( !json.list || !json.list.length )
					return parsed;

				for (var i in json.list)
					parsed[parsed.length] = {
						data: json.list[i].Name,
						value: json.list[i].Code,
						result: json.list[i].Name
					};

				return parsed;
			},
			formatItem: function(text, i, max, value) {
				return text;
			},
			blurClear: true,
			returnFocus: el.val() != -2,
			max: 20
		}).result(
			function(event, Name, Code) {

				var isList = el.val() == -2;
				el.each(function() {

					var inList = false;
					for (var i=0;i<this.options.length;i++) {

						if ( this.options[i].value != Code )
							continue ;

						inList = true;
						this.options[i].selected = true;
						break ;
					}

					if ( inList == false ) {
						this.options[this.options.length] = new Option(
								Name, Code, false, false);

						this.options[this.options.length-1].selected = true;
						this.disabled = false;
					}
				});

				if ( isList )
					return el.change();

				self.StreetRestSuggest(code, el, Name);
				el.change();
			}
		);

		return streeSuggest.insertAfter(el);
	},

	StreetRestSuggest: function(code, el, Name) {

		var self = this;
		var el = $(el);
		var Name = ( Name === undefined && el.val().length == 22 ? el.get(0).options[el.get(0).selectedIndex].text : Name );
		var streeSuggest = $('#'+el.attr('id')+'_suggest');

		if ( streeSuggest.size() == 0 ) {
			var streeSuggest = $('<input type="text"/>').attr({
				id: el.attr('id')+'_suggest',
				autocomplete: 'off',
				value: ''
			}).css({
				width: el.css('width') ? el.css('width') : el.width()
			});
			streeSuggest.insertAfter(el);
		} else
			streeSuggest.unautocomplete();

		streeSuggest.val(Name);
		streeSuggest.bind("keyup", {Name: Name}, function(event) {
			var curName = this.value;
			if ( Name == curName)
				return ;

			$(this).remove();

			el.get(0).selectedIndex = 0;
			el.change();
			var streeSuggest = self._getStreetSuggest(code, el);
			streeSuggest.val(curName).focus();
			if ( $.browser.opera )
				streeSuggest.keypress();
			else
				streeSuggest.keydown();
		});
	},
	
	_getStreetSuggest: function(code, el) {
		var visible = el.is(":visible");
	
		el.show();
		var streeSuggest = this._showStreetSuggest(code, el);
		if ( !visible )
			el.hide();
		return streeSuggest;
	},
	
	_getRegionList: function(code, region) {

		var Progress = this.Progress(region);

		region.hide();
		this.loaders[region.attr('id')] = $.ajax({
			mode: 'abort',
			port: region.attr('id'),
            type: 'POST',
            url: '/service/source/db.address',
            data: {
				type: 'region_list',
				code: code
			},
            dataType: 'json',
            error: function() {
				region.attr({'disabled': true}).hide();
				$('#'+region.attr('id')+'_cont').hide();
				Progress.remove();
			},
            success: function(json) {

				region.each(function() {
					this.selectedIndex = 0;
					this.options.length = 1;

					if ( json.list && json.list.length ) {

						$('#'+this.id+'_cont').get(0).style.display = '';
						for (var i in json.list)
							this.options[this.options.length] = new Option(
								json.list[i].Name,
								json.list[i].Code,
								false, false);
					} else
						$('#'+this.id+'_cont').hide();

					this.options[0].text = this.options[0]._text || this.options[0].text;
				});

				region.attr({'disabled': false}).show();
				Progress.remove();
			}
        });
	},

	_getStreetList: function(code, street, house) {

		var Progress = this.Progress(street);
		var self = this;

		street.hide();
		this.loaders[street.attr('id')] = $.ajax({
			mode: 'abort',
			port: street.attr('id'),
            type: 'POST',
            url: '/service/source/db.address',
            data: {
				type: 'street_list',
				code: code
			},
            dataType: 'json',
            error: function() {
				street.attr({'disabled': true}).hide();
				$('#'+street.attr('id')+'_cont').hide();
				Progress.remove();
			},
            success: function(json) {

				street.each(function() {

					this.selectedIndex = 0;
					this.options.length = 1;

					if ( json.count > 0 && !json.list.length ) {
						$(this).show();
						self._showStreetSuggest(code, this);
						$(this).hide();
						
						$('#'+this.id+'_cont').get(0).style.display = '';
					} else if ( json.list.length > 0 ) {
						if ( json.list.length >= 50 ) {
							this.options[this.options.length] = new Option(
									'-------------', 0, false, false);
							this.options[this.options.length] = new Option(
									'Поиск по списку', -2, false, false);
							this.options[this.options.length] = new Option(
									'-------------', 0, false, false);

							this.options[this.options.length-1].disabled = true;
							this.options[this.options.length-3].disabled = true;
						}

						$('#'+this.id+'_cont').get(0).style.display = '';
						if ( json.list.length <= 200 ) {
							for (var i in json.list)
								this.options[this.options.length] = new Option(
									json.list[i].Name,
									json.list[i].Code,
									false, false);
						} else {
							$(this).show();
							self._showStreetSuggest(code, this);
							$(this).hide();
						}
						
					} else {
						$('#'+this.id+'_cont').hide();
						house.hide();
					}

					this.options[0].text = this.options[0]._text || this.options[0].text;
				});

				if ( json.list.length && json.list.length <= 200 ) {
					street.attr({'disabled': false}).show();
				} else
					street.hide();
				Progress.remove();
			}
        });
	},

	_getCityList: function(code, city) {

		var Progress = this.Progress(city);

		city.hide();
		this.loaders[city.attr('id')] = $.ajax({
			mode: 'abort',
			port: city.attr('id'),
            type: 'POST',
            url: '/service/source/db.address',
            data: {
				type: 'city_list',
				code: code
			},
            dataType: 'json',
            error: function() {
				city.attr({'disabled': false}).show();
				if ( city.get(0).options[0]._text )
					city.get(0).options[0].text = city.get(0).options[0]._text;

				Progress.remove();
			},
            success: function(json) {

				city.each(function() {
					this.selectedIndex = 0;
					this.options.length = 1;

					if ( json.list && json.list.length ) {

						for (var i in json.list)
							this.options[this.options.length] = new Option(
								json.list[i].FullName,
								json.list[i].Code,
								false, false);
					}

					this.options[this.options.length] = new Option(
						' - Другой - ', -1, false, false);

					this.options[0].text = this.options[0]._text || this.options[0].text;
				});

				city.attr({'disabled': false}).show();
				Progress.remove();
			}
        });
	},

	Progress: function(el) {

		var el = $(el);
		var id = el.attr('id')+'progress';

		$('#'+id).remove();

		var Progress = $('<div>Идет загрузка...</div>').css({
			padding: '3px',
			backgroundImage: 'url(/_img/design/200608_title/progress.gif)',
			border: '1px solid #C0CAD5'
		}).attr({id: id});
		Progress.insertAfter(el);

		return Progress;
	},
	
	StopLoading: function(el) {

		var el = $(el);
		var id = el.attr('id')+'progress';

		$('#'+id).remove();
		
		if ( this.loaders[el.attr('id')] )
			this.loaders[el.attr('id')].abort();
	}
};
