;(function($) {
	
	$.widget("ui.selectedHotels", {

		get: function() {
			return this.values
		},

		set: function(values) {
			this.clear()
			for(var prop in values) {
				this.values[prop] = values[prop]
			}

			this.checkEmpty()

			this.setInputValues(values)

			// only helper uses this ATM
			this.element.triggerHandler('select')

		},

		checkEmpty: function() {
			for(var prop in this.values) {
				this.$list.show()
				this.$empty.hide()
				return
			}
			this.$list.hide()
			this.$empty.show()
		},

		clear: function() {
			this.values = {}
			this.$list.empty().hide()
			this.$empty.show()
		},

		removeValue: function(id) {
			delete this.values[id]
			$('#hotelSelected'+id).addClass('hotel-name-deleted').fadeOut(100, function() { $('#hotelSelected'+id).remove() })
			this.checkEmpty()
		},

		setInputValues: function(values) {
			var list = []
			for(var prop in values) {
				if (values[prop].hotel_link) {
					var hotel_text = '<a target="_blank" title="информация" href="'+values[prop].hotel_link+'">'+values[prop].name+'<span class="hotel-name-info" action="info"><img src="/css/tour/search-picbtn-info.gif" alt="информация"></span></a>'
				} else {
					var hotel_text = values[prop].name
				}
				list.push('<li id="hotelSelected'+prop+'">\
						  <span class="hotel-name-delete"><img action="delete" src="/css/tour/search-picbtn-delete.gif" alt="удалить"></span> \
						  ' + hotel_text + ' \
					</li>')
			}

			this.$list.html(list.join('\n'));

		},

		getParams: function(params) {

			var ids = []
			for(var p in this.values) ids.push(p)

			if (!ids.length) return

			params.Als = ids.join('-')
		},

		loadHotels: function(ids) {
			if (typeof ids == 'array') ids = ids.join('-')

	        var self = this

			this.ajaxController.sendRequest({url:'hotel_names', data: {ids: ids}})
		},


		onLoaded: function(hotels){
			if (hotels) { // if no error occured
				this.set(hotels)
			}
		},

		showLoading: function(on) {
			if (on) {
				this.element.addClass('hotel-choose-name-tab-loading')
			} else {
				this.element.removeClass('hotel-choose-name-tab-loading')
			}
		},

		isEmpty: function() {
			for(var p in this.values) return false
			return true
		},
		
		_init: function() {
			
			this.init.apply(this, arguments);
		},
		
		init: function() {
			
			$.widget.prototype._init.apply(this,arguments)

			this.ajaxController = new AjaxController(this, '/tour/', '.php')

			this.values = {}

			this.$list = $('#hotel-choose-name-list')
			this.$empty = $('#hotel-choose-name-empty')

			var self = this
			this.$list.click(function(e) {
				var o = e.target
				if (o.getAttribute('action')!='delete') return

				while(o.tagName!='LI') o=o.parentNode

				id = +o.id.substr('hotelSelected'.length)

				self.removeValue(id)
				e.stopPropagation()

			})
		}
	});
	
	$.extend($.ui.selectedHotels, {
		'getter': 'isEmpty, get'
	});
	
})(jQuery);
