;(function($) {

	$.widget("ui.modalHotels", {
		
		_init: function() {
		
			this.init.apply(this, arguments);
		},
		
		init: function() {
			$.widget.prototype._init.apply(this,arguments)
	
			this.ajaxController = new AjaxController(this, '/tour/', '.php')
	
			this.pagesPerList = 4
	
			this.rowsPerPage = 10
	
			this.firstShow = true
	
			this.page = 1;
	
			this.values = {}
	
			// preload loader
			this.imgLoader = new Image()
			this.imgLoader.src = "/i/tour/loading.gif"
	
			this.tb_close_label = "Закрыть";
	
			this.caption = 'Выберите отели'
			// создаём модельную форму
	
	
		},
	
		set: function(values) {
			this.values = values
	
			this.renderInputValues()
		},
	
	
		isEmpty: function() {
			for(var p in this.values) return false
			return true
		},
	
		renderInputValues: function() {
			var self = this
	
			//console.log(this.values)
			//console.log(this.values['5022'])
	
			$("input[type=checkbox]", this.$list).each(function(i,elem) {
				var id = elem.id.substr(2)
	
				elem.checked = self.values[id] ? true : false
			})
		},
	
		search: function(params) {
			params = params || {}
			this.page = params.page || 1
			this.loadHotels()
		},
	
	
		bindSearch: function() {
			var self = this
	
			// e.g when controls are in filling stage (not yet shown), we do not search
			var search = function() { self.isShown && self.search() }
	
			$('#hotel-filter-Re').bind('select', function() {search()} )
			$('#hotel-filter-AlCa').bind('select', function() {search()} )
	
			var lastInputVal, timeout
	
			var onChange = function(code) {
				// get current value, not event-time (short by 1 char) value
				var value = $('#hotel-filter-name').val()
	
				// ignore if the following keys are pressed: [del] [shift] [capslock]
				if( code == 46 || code==38 || code==40 || (code > 8 && code < 32) ) {
					return
				}
	
				if (value === lastInputVal) return
	
				search()
	
				lastInputVal = value
	
			}
	
			$('#hotel-filter-name').keydown(function(e) {
			// track last key pressed
				var code = e.keyCode;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){onChange(code)}, 400)
			})
	
			//$('#hotel-filter-favorite').click(function() {search()})
			$('#hotel-filter-favorite').bind('select', function() {search()} )
	
		},
	
		build: function() {
	
			this.$navs = $('.hotel-filter-nav', this.element)
	
			var self = this
	
			this.$navs.click(function(e) {
				var o = e.target
				var page
				while (!(page = o.getAttribute('page')) && o.tagName!='UL') {
					o = o.parentNode
				}
	
				if (page) {
					self.search({page: page})
				}
	
			})
	
			$('#hotel-filter-accept').click(function() { self.accept() })
			$('#hotel-filter-cancel').click(function() { self.cancel() })
	
			this.$list = $('#hotel-filter-list')
	
	
			this.$list.click(function(e) {
				var o = e.target
				if (o.tagName!='INPUT' || o.type != 'checkbox') return
	
				var id = +o.id.substr(2)
	
				if (o.checked) {
					self.values[id] = self.currentPageHotels[id]
				} else {
					delete self.values[id]
				}
	
			})
	
			$('#hotel-filter-form').submit(function(e) {
				e.stopPropagation()
				self.accept()
				return false
			})
	
			this.navTmpl = tmpl("hotel-filter-nav-pattern")
			this.listTmpl = tmpl("hotel-filter-list-pattern")
	
			this.buildModalControls()
	
	    //jQuery('#HC_window img').ifixpng();
	   // jQuery('img').ifixpng();
		},
	
	
		showLoading: function(on) {
			if (on) {
				$('.page', this.element).addClass('loading')
			} else {
				$('.page', this.element).removeClass('loading')
			}
		},
	
		isShow: function() {
			return !!this.isShown
		},
	
	
		closeControls: function() {
			$('#hotel-filter-Re').stringCheckbox("close")
			$('#hotel-filter-AlCa').stringCheckbox("close")
		},
	
		close: function() {
			this.closeControls()
	
			$("#HC_imageOff").unbind("click");
			$("#HC_closeWindowButton").unbind("click");
			this.$container.hide()
	
			this.$container.fadeOut("fast",function(){
				$('#HC_window,#HC_overlay,#HC_HideSelect').trigger("unload").unbind().remove();
				fixIE.hide();
			});
			$("#HC_load").remove();
			if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
				$("body","html").css({height: "auto", width: "auto"});
				$("html").css("overflow","");
			}
	
			//this.setEscapeClose(false)
			floatWidget.activePop(this)
	
			this.isShown = false
		},
	
		position: function() {
			this.$container.css({marginLeft: '-' + parseInt((this.HC_WIDTH / 2),10) + 'px', width: this.HC_WIDTH + 'px'});
			if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
				this.$container.css({marginTop: '-' + parseInt((this.HC_HEIGHT / 2),10) + 'px'});
			}
		},
	
		onLoaded: function(data) {
	
			if (!this.isShown) return // user closed window while I was loading data
	
			if (!data.count) {
				this.showError('.notfound');
			}
			else {
				this.currentPageHotels = data.hotels
	
				this.showHotels(data)
			}
	
		},
	
		onLoadError: function(errinfo) {
			if (!this.isShown) return // user closed window while I was loading data
	
			if(errinfo.errcode == 'timeout'){
				this.showError('.timeout')
			}else{
				this.showError('.server-error')
			}
	
		},
	
		showError: function(selector) {
			this.$navs.empty()
			this.$list.empty()
			$(selector, this.element).show();
		},
	
		showHotels: function(data) {
	
			var pagesTotal = Math.ceil(data.count / this.rowsPerPage)
			var first = data.page - this.pagesPerList/2
			data.first = Math.max(1, first)
			data.last = Math.min(data.first + this.pagesPerList, pagesTotal)
	
			if (data.last - data.first < this.pagesPerList) {
				data.first = Math.max(1, data.last - this.pagesPerList)
			}
	
	
			data.searchName = $('#hotel-filter-name').val()
	
			this.$navs.html(this.navTmpl(data))
			this.$list.html(this.listTmpl(data))
	
			this.renderInputValues()
		},
	
		loadHotels: function() {
			$('.error', this.element).hide();
	
			var req = {
				url: 'hotels',
				data: {
					country: $('#Co').CoSelect('get'),
					city: $('#city').stringSelect('get'),
					name: $('#hotel-filter-name').val(),
					efavorite: $('#hotel-filter-favorite').stringSelect('get'),
					AlCa: $('#hotel-filter-AlCa').stringSelect('get'),
					Re: $('#hotel-filter-Re').stringCheckbox('get').join('-'),
					page: this.page,
					rows: this.rowsPerPage
				}
			}
	
	
	
			var self = this
			this.ajaxController.sendRequest(req)
	
		},
	
		// Modal is used only to add hotels to list
		// so I clean it after either accept or cancel
		accept: function() {
			this.close()
			
			// first call handler to let it access my methods with current values
			this.element.triggerHandler('select', [true, this.values])
			// then clean
			this.set({})
		},
	
		cancel: function() {
			this.close()
			this.element.triggerHandler('select', [false])
			this.set({})
		},
	
	
		/**
		 *  Fill modal window with options from current controls
		*/
	    buildModalControls: function() {

			$('#hotel-filter-Re').stringCheckbox(
				{options: $('#Re').stringCheckbox('getData','options'), empty_title:'Любой'}
			)
	
			$('#hotel-filter-AlCa').stringSelect({options: formDefaults.AlCa})
	
			var self = this
			// each time user changes main control => we clear our settings. So next time we'll refill them
			// this allows user to change hotel search settings, close -> reopen modal window with them
			$('#Re, #Co').bind('select', function() { self.fillReDone = false })
	
	    $('#hotel-filter-favorite').stringSelect({options: formDefaults.OnlyFavorites})
		},
	
		fillModalControls: function() {
			
			var Co = this.globalControls.Co
			var city = this.globalControls.city
			var AlCa = this.globalControls.AlCa

			if (!this.fillReDone) {
				$('#hotel-filter-Re').stringCheckbox('loadOptions',
						{url:'regions', data:{city: city.stringSelect('get'), country: Co.CoSelect('get')}})
						
				//$('#hotel-filter-Re').stringCheckbox('set', $('#Re').stringCheckbox('get'))
				this.fillReDone = true
			}
	
	
		},
	
	
		show: function(values) {
	
			this.globalControls = values[1];
			values = values[0];
			
			
			if (this.firstShow) {
				this.build()
				this.bindSearch()
			}
			this.showModal()
	
			this.isShown = true
	
			// first time - take from regions/meals
			// next time - update my controls using event bind on regions/meals
	
			// copy values, don't take values object as reference!
			this.values = {}
			if (values) $.extend(this.values, values)
	
			this.fillModalControls()
			this.search()
	
			this.firstShow = false
	
		},
	
		/**
		 * build generic modal window
		*/
		showModal: function() {
	
			function tb_detectMacXFF() {
			  var userAgent = navigator.userAgent.toLowerCase();
			  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
				return true;
			  }
			}
	
			fixIE.show()
			floatWidget.activePush(this)
	
			var self = this
			$(document.body).append("<div id='HC_overlay'></div><div id='HC_window'></div>")
	
			this.$container = $("#HC_window")
	
			if(tb_detectMacXFF()){
				$("#HC_overlay").addClass("HC_overlayMacFFBGHack");//use png overlay so hide flash
			}else{
				$("#HC_overlay").addClass("HC_overlayBG");//use background and opacity
			}
	
			$(document.body).append("<div id='HC_load'><img src='"+this.imgLoader.src+"' /></div>");//add loader to the page
			$('#HC_load').show();//show loader
	
	
			this.HC_WIDTH = (this.getData('width')*1) || 630; //defaults to 630 if no paramaters were added to URL
			this.HC_HEIGHT = (this.getData('height')*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = this.HC_WIDTH - 1;
			ajaxContentH = this.HC_HEIGHT - 45;
	
	
	    // FIX: 0:52 07.10.2008
	    // without   height property fot flexibility
		// FIX: 12:30 16.03.2010
		// image fix
			if(this.$container.css("display") != "block"){
				if(this.getData('modal') != "true"){//ajax no modal
					//this.$container.append("<img src='/css/tour/hc_top_bg.png' alt=''><div id='HC_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div><img src='/css/tour/hc_bottom_bg.png' alt=''>");
					//this.$container.append("<img src='/css/tour/hc_top_bg.png' alt=''><div id='HC_ajaxContent' style='width:"+ajaxContentW+"px;'></div><img src='/css/tour/hc_bottom_bg.png' alt=''>");
					this.$container.append("<img src='/css/tour/hc_top_bg.png' alt='' style='display: block;' /><div id='HC_ajaxContent' style='width:"+ajaxContentW+"px;'></div><img src='/css/tour/hc_bottom_bg.png' alt=''>");
				}else{//ajax modal
					$("#HC_overlay").unbind();
					this.$container.append("<div id='HC_ajaxContent' class='HC_modal' style='width:"+ajaxContentW+"px;'></div>");
				}
			}else{//this means the window is already up, we are just loading new content via ajax
				with($("#HC_ajaxContent")[0]) {
					style.width = ajaxContentW +"px"
					style.height = ajaxContentH +"px"
					scrollTop = 0
				}
				$("#HC_ajaxWindowTitle").html(caption);
			}
	
			// close and cancel all selected
			$("#HC_closeWindowButton").click(function() { self.cancel() });
	
	
			var dataParent = this.element.parent();
			this.element.appendTo($("#HC_ajaxContent"));
			this.$container.unload(function () {
				self.element.appendTo(dataParent);
			});
	
			this.position();
			$("#HC_load").remove();
			this.$container.css({display:"block"});
	
	
		}
	
	
	});
	$.extend($.ui.modalHotels, {
		
		defaults: {
			width: 700,
			height: 480
		},
		getter: "isEmpty"
	});
	
})(jQuery);